text
stringlengths
180
608k
[Question] [ A question that had popped up in my head once - how many NAND gates would it take to build a larger, "meta-NAND" gate? Your task is to build a black-box circuit that takes two input wires `A` and `B` and returns one output wire that satisfies `A NAND B`, subject to the following restrictions: * You must use at least two `NAND` gates in this construction (and no gates other than `NAND`). * You may not have null configurations of gates - that is, systems of gates that are equivalent to a gateless wire. (For example, two `NOT` gates in series are a null configuration.) * You cannot have any stray wires (discarded values or constants). Fewest gates wins. [Answer] Three gates. Compute (((A nand A) nand B) nand B). Unlike the four-gate solution above in which three of the four gates compute A nand B, two of them simultaneously, and substituting one of the simultaneous outputs for the other would yield two consecutive inverters, the three-gate solution uses the three gates to compute different functions: "not A", "A or not B", and "A nand B". Only the last gate computes the desired function. [Answer] # 4 gates (A NAND B) AND-using-NAND (A NAND B) ``` A---NAND _ \ / \ / \ X NAND-< NAND--> / \ / \_/ B---NAND ``` ![](https://i.stack.imgur.com/ITJlg.png) [Answer] # 3 gates ``` /-----------\ A-< \ \-----\ \ \ NAND-- NAND--/ B-<NAND---/ ``` ]
[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/3741/edit). Closed 7 years ago. [Improve this question](/posts/3741/edit) Read input of up to 8 characters presented as hexadecimal number and print this number as decimal number. In case that input can not be presented as hexadecimal input it has to print 0 **Rules:** It is not allowed to use any function that takes or returns strings/characters, beside function that reads string/char from input and return strings/char as-is, function that takes integer and prints that integer to output as decimal number and function (if needed) that takes character and return its ASCII/UNICODE represented integer. Shortest code wins Example input `C0cAc01a` output `3234512922` [Answer] ## Ruby, 74 characters ``` n=0;p gets.gsub(/./).all?{|x|n=n*16+(x>?9?9:0)+x.ord%16;/[\da-f]/i=~x}?n:0 ``` Input must be given on STDIN. With command line option `-ln` (counted as 4) it can be shortened to 69 characters. ``` n=0;p chars.all?{|x|n=n*16+(x>?9?9:0)+x.ord%16;/[\da-f]/i=~x}?n:0 ``` [Answer] # Haskell, ~~114~~ 106 ``` x#y=16*x+mod y 16 main=getLine>>=print.maybe 0(foldl(#)0).mapM(`lookup`zip"ABCDEF0123456789abcdef"[-6..]) ``` Handles input of arbitrary size. [Answer] ## c -- 181 Input passed on the commandline (one argument only). Relies on K&R function typing defaults. ASCII specific, but has ***no*** reliance on the language or library to know how to parse numbers. Lots of characters given up to specifying a large integer type for this purpose. ``` #include <stdio.h> main(int c,char**v){unsigned long b=0;char*d=v[1]-1,e;while(e=*++d){ e-=(e>96)?87:(e>64)?55:(e>57)?33:(e>47)?48:0;if(e>15){b=0;break;} b=b*16+e;}printf("%lu\n",b);} ``` ## Ungolfed: ``` #include <stdio.h> main(int c,char**v){ unsigned long b=0; char*d=v[1]-1,e; while(e=*++d){ if(e>'`')e-=87; // reduce lowercase letters to 10-- if(e>'@')e-=55; // reduce uppercase letters to 10-- if(e>'9')e-=33; // reduce punctioation immediately above the // digits so it does not iterfere if(e>'/')e-='0';// reduce digits to 0-9 if(e>15){b=0;break;} // terminate immediately on bad input b=b*16+e; } printf("%lu\n",b);} ``` ## Validation: ``` $ gcc -o dehex dehex_golfed.c $ ./dehex C0cAc01a 3234512922 $ ./dehex 1 1 $ ./dehex 1f 31 $ ./dehex g 0 $ ./dehex 1g 1 $ ./dehex 1:2 0 ``` [Answer] ## JavaScript, 127 119 characters (thanks trinithis!) [Code-Golfed](http://jsfiddle.net/briguy37/6vzs9/): ``` function f(n){for(o=i=0,c=1;l=n[i++];)o*=16,l=l.charCodeAt(0),o+=l-(l>96?87:l>64?55:48);return /[\W_g-z]/i.test(n)?0:o} ``` [Formatted](http://jsfiddle.net/briguy37/vuzpV/): ``` function hexToDec(hexChars) { //Iterate through hex chars for (dec=i=0,count = 1; hexChar = hexChars[i++];) { dec *= 16; hexCharCode = hexChar.charCodeAt(0); //Get the hex number and add it hex = hexCharCode; if(hexCharCode > 96){ hex -= 87;//For lower case letters } else if (hexCharCode > 64){ hex -= 55;//For upper case letters } else { hex -= 48;//For numbers } dec += hex; } //Return 0 if invalid, decimal value otherwise if(/[\W_g-z]/i.test(hexChars)){ return 0; } return dec; } ``` [Answer] ## Ruby 1.9 (84) ``` gets.chomp!;n=0;p~/[^0-9A-Fa-f]/?0:($_.chars{|c|o=c.ord-48;n=16*n+(o>9?o%32-7:o)};n) ``` If we're allowed to use command line options, this is shortened to 72 characters + 4 for `-ln`: ``` n=0;p~/[^0-9A-Fa-f]/?0:($_.chars{|c|o=c.ord-48;n=16*n+(o>9?o%32-7:o)};n) ``` [Answer] ## Python, 106 characters ``` n=0 e=9e9 for c in raw_input():n=n*16+ord(c)-[e,48,e,55,e,87,e][sum(c>x for x in'/9@F`f')] print[n,0][n<0] ``` [Answer] ## Scheme, 24 chars ``` (string->number(read)16) ``` I hope this is not considered cheating. If it is: ``` (string->number(string-append "#x"(read))) ``` String to number conversion is mandatory. In Scheme, if your program is not simple, something is wrong and you should start over until it is made simple. Scheme's power relies on removing restrictions instead of adding features so that the language can be easily extended. Scheme is, with Lisp-derived languages, a programmable programming language. [Answer] ## D 194 chars ``` void main(string[] a){ulong r;foreach(c;a[1]){switch(c){case '0'..'9':r+=c-'0';break;case 'a'..'f':r+=c-'a'+10;break;case 'A'..'F':r+=c-'A'+10;break;default: write(0); return;}r*=16;}write(r);} ``` I could get some profit by replacing the char literals with the numerals and get thus get rid of the +10 for the `a-f` but this doesn't depend on char encoding though D defines ascii support IIRC [Answer] ## Mathematica, 64 By the rules: ``` FromDigits[#-If[#<58,48,If[#<97,55,87]]&/@ToCharacterCode@#,16]& ``` [Answer] # JavaScript, 48 chars ``` function h(n){return 0/0==+("0x"+n)?0:+("0x"+n)} ``` ## Formatted + Uncompressed ``` function h(n){ if(+("0x"+n)==NaN) { return 0; } else { return +("0x"+n); } } ``` > > The plus operator set before a string converts it into a **decimal** number. So I just had to prepend a "0x" and return 0 if it isn't a valid number to conform the rules. > > > [Answer] # Groovy, 74 ``` i={it.inject(0){a,v->a*16L+('0123456789abcdef'.indexOf(v.toLowerCase()))}} ``` test case: ``` assert 3234512922 == i('C0cAc01a') ``` Not sure I understood the rules, though. [Answer] ## Perl, 39 characters ``` print<>=~m/^[[:xdigit:]]{1,8}$/?hex$&:0 ``` I kind of feel weird doing it this way in Perl but I believe it follows the rules, since the `hex()` function is a language construct and not a library function. If not... ## Perl, 64 characters ``` print<>!~m/^[[:xdigit:]]{1,8}$/?0:unpack 'L',reverse pack'H8',$& ``` I hope is fine. [Answer] **C# - 192 189** oldschool, uses Console arguments for input, Console.WriteLine() for output. could possibly save a few chars, but can't get rid of most lengthy keywords. Makes evil use of foreach, ternary operator madness, bitwise complement ~ and signedness. Reads any length input and aborts on bad characters ([^0-9a-fA-F]). ``` namespace _{class _{static void Main(string[]a){long b=0;foreach(int c in a.Length>0?a[0]:"")b=b<<4|(c-'0'<10?c-'0':c-'A'<6?c-'A'+10:c-'a'<6?c-'a'+10:~0L);System.Console.Write(b<0?0:b);}}} ``` A little deobfuscated (old ver): ``` using System; namespace CodeGolf { class Program { static void Main() { long ret = 0; int nextChar; while ((nextChar = Console.Read()) != '\r') { ret <<= 4; ret |= nextChar - '0' < 10 ? nextChar - '0' : nextChar - 'A' < 6 ? nextChar - 'A' + 10 : nextChar - 'a' < 6 ? nextChar - 'a' + 10 : ~0L; } Console.WriteLine(ret < 0 ? 0 : ret); } } } ``` Would love to see a C# implementation in hardcore MSIL ;) [Answer] # Python, 98 chars ``` print sum(16**n*i for i,n in zip(((ord(c)|32)-[48,87][c>'9']for c in raw_input()[::-1]),range(9))) ``` A one-liner with the nifty bonus that you can use characters > 'f' for shorthand notation, e.g 'g' counts for 16, 'h' for 17 etc :D [Answer] # Mathematica 93 92 chars ``` Fold[16 #1 + #2 &, 0,ToExpression[Characters@n /. Thread@Rule["a"~CharacterRange~"f", 10~Range~15]]] ``` Not as streamlined as Mr.Wizard's answer, but I'll include it for variety. It makes use of no native base conversion routines. There is a shortcoming in my answer: I assumed that characters `a` to `f` would be given in lowercase. [Answer] ## Perl - 77 chars ``` @h{0..9,'a'..'f'}=0..15;$n+=$h{lc$_}*16**($a++-1)for reverse split//,<>;say$n ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- 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). Closed 8 years ago. [Improve this question](/posts/54498/edit) Find the shortest way to generate a random number between 0-9 without repeating the last generated number. Here is an example written in javascript. ``` var n=t=0; while(n==t){ t=Math.floor(Math.random()*9); } n=t; ``` I don't know if it is possible, but it would be interesting if there is a solution using only one variable. To clarify the solution can be in any language. Based on the comments I am going to disallow using arrays since apparently that makes it very easy and this is code-golf so the shortest answer wins. [Answer] # Pyth, 7 bytes ``` e=+ZhO9 ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=e%3D%2BZhO9%0Ae%3D%2BZhO9%0Ae%3D%2BZhO9%0Ae%3D%2BZhO9%0Ae%3D%2BZhO9%0Ae%3D%2BZhO9%0Ae%3D%2BZhO9&debug=0) ### Explanation ``` implicit: Z = 0 O9 Generate a random int from [0, 1, ..., 8] h add 1 =+Z add this to Z and update Z e print Z modulo 10 ``` [Answer] # CJam, ~~10~~ 8 bytes Thanks @Dennis for a 2 bytes golf! You can repeat this piece of code how many times you want. ``` A,W-mR:W ``` Explanation: ``` e# At startup, W = -1 A, e# Push [0 ... 9] W- e# Remove W from the list mR e# Random choice from list :W e# Assign to W e# The number is left on the stack ``` [Try it online](http://cjam.aditsu.net/#code=%7B%0AA%2CW-mR%3AW%0A%7D100*). [Answer] # K5, 19 bytes Not particularly clever: ``` t:-1;r:{t::*1?10^t} ``` Each time `r` is invoked, it picks 1 random number (`*1?`) from the set formed by taking the range 0-9 except (`^`) the previous random number and then stores the result in t (`t::`). We initialize t (`t:-1;`) such that the first result can be any digit 0-9. The definition of `r` is purely for convenience in repeatedly invoking it, so you're really only using a single variable. ## edit: Just for fun, here's a k5 program which will generate a sequence of N numbers containing no immediate repetitions (as in the above problem) without using *any* variables: ``` 1_(*1?10^)\[;-1] ``` For example, ``` 1_(*1?10^)\[;-1]10 1 8 0 6 8 5 1 0 5 1 1_(*1?10^)\[;-1]3 4 0 7 ``` Doesn't work quite right in [my K implementation](http://johnearnest.github.io/ok/index.html), so I suppose writing this and discovering a bug was a decent use of my time! [Answer] # Java, 62 bytes ``` int a(int p){p+=9*(p+Math.random());return p%10==p/10?9:p%10;} ``` This is a function. You call it with the previously returned value. Uses only the variable supplied. # 2 variables, 59 bytes ``` int a(int p){int a=(int)(Math.random()*9);return a==p?9:a;} ``` [Answer] # Julia - ~~25~~ 18 bytes ``` t=(rand(1:9)+t)%10 ``` Or, for a slightly longer, iterative solution: ``` while t==(t=rand(0:9))end ``` No temporary second variable necessary. [Answer] # Python 2, 79 bytes Here's a simple one you can repeatedly run in a REPL: ``` from random import* try:p except:p=n=0 while p==n:n=int(random()*9) print n p=n ``` [Answer] **Java 8, 89 bytes** As an IntStream... ``` // Int Stream (89 bytes) IntStream.iterate(0,(o)->new Random().ints(0,10).filter(x->x!=o).findFirst().getAsInt()); ``` Minimal usage... ``` // Usage (119 bytes) IntStream.iterate(0,(o)->new Random().ints(0,10).filter(x->x!=o).findFirst().getAsInt()).forEach(System.out::println); ``` [Answer] # Octave, 24 bytes Here's an anonymous function using one variable (plus the function handle): ``` r=@(n)mod(randi(9)+n,10) ``` Sample run: ``` >> n=5; >> n=r(n) n = 2 ``` [Answer] # Javascript, 39 bytes Not the most exciting answer, but it is in Javascript. ``` t=-1;while(t==(t=(Math.random()*9)|0)); ``` To test it: ``` //set the value here, or it will produce repeated numbers: t=-1; for(var i=0; i < 10; i++){ //generate a new random number, using the code in the answer while(t==(t=(Math.random()*9)|0)); document.write(t + '<br>'); } ``` [Answer] # Python 3, ~~42~~ 33 bytes If your criteria for "random" is generating a number 0-9, > > [...] without repeating the last generated number. > > > Something like this would work: ``` i=(i+1)%10if"i"in globals()else 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 4 years ago. [Improve this question](/posts/38691/edit) ## Note: although this is tagged as Python, other languages are permitted ## Challenge What you have to do is write the shortest functions to perform the same actions as the following Python 2 built in functions: ### [Range](https://docs.python.org/release/1.5.1p1/tut/range.html) ``` >>> range(1, 10, 1) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1, 10, 2) [1, 3, 5, 7, 9] >>> range(10, 5, -1) [10, 9, 8, 7, 6] range(start, end, step) ``` When run, this produces an ascending list of numbers. Generally used in for loops, this can also be used for golfing when lists of numbers are required. ### [Type](https://docs.python.org/2/library/functions.html#type) ``` >>> type(12) 'int' >>> type(12.0) 'float' >>> type('12') 'str' >>> type([13, 45]) 'list' type(var) ``` Returns the data type of a variable. The required types are in the examples. ### [Round](https://docs.python.org/2/library/functions.html#round) ``` >>> round(0.5, 0) 1.0 >>> round(0.2, 0) 0.0 >>> round(3.14159, 3) 3.142 >>> round(127.56, -2) 100.0 >>> round(12.5640, 2) 12.56 >>> round(1457, -2) 1500 round(number, ndigits) ``` Given a floating point integer, it rounds it to ndigits. Floor and ceil functions are not allowed. For ties, round away from zero. ### [Enumerate](https://docs.python.org/2/library/functions.html#enumerate) ***Note:*** Return a list despite the fact that in Python, **`enumerate`** returns an object. ``` >>> enumerate([1, 2, 3, 4]) [[0, 1], [1, 2], [2, 3], [3, 4]] >>> enumerate(['spam', 'eggs']) [[0, 'spam'], [1, 'eggs']] enumerate(array) ``` Returns a two dimensional list with the index as part of the embedded list. ## Rules People writing in Python must *not* use the built-in functions listed above (or magic variables). If there are similar built-in functions in your language, you must not use them. For invalid arguments return 1: ``` >>> enumerate(23) 1 >>> round(56, 'hello') 1 >>> range('hi', 4, 1) 1 ``` You may use your own functions (range, type, round and enumerate). ## Winning Your score is the sum of the byte count for each function (the function declaration should not be counted). The lowest score wins. [Answer] # MIPS ## Range - 40 Probably can be golfed much more with x86 or some clever instruction. Input: ``` .text .globl main main: # Read inputs li $v0, 5 syscall move $t0, $v0 li $v0, 5 syscall move $t1, $v0 li $v0, 5 syscall move $t2, $v0 ``` Actual program (writes to stack): ``` loop: bgtz $t2, pos ble $t0, $t1, exit # i <= end j l pos: bge $t0, $t1, exit # i >= end l: addi $sp, $sp, -4 sw $t0, 0($sp) # Push $t1 add $t0, $t0, $t2 j loop ``` ## Type - 12 (non-serious) In MIPS all registers can be used with integer instructions, even the floating point ones. ``` .text .globl main main: li $v0, 4 la $a0, msg syscall .data msg: .asciiz "Integer (probably)" ``` [Answer] # Ruby, 183 ``` range=->a,b,s{r=[a];r<<a while(a+=s)<b;r<<a} # 38 bytes type=->x{%w[int float str list 1][[1,1.0,'',[]].find_index{|y|x.class===y}||4]} # 74 bytes round=->n,d{a=10**d;b=n*a;z=b%1;b-=z<0.5?z:(-1+z);b/a} # 48 bytes enumerate=->l{(0...l.size).zip l} # 23 bytes ``` I've not counted the names of the lambdas and the `=` that follows them. Only `type` handles invalid input. It returns the `String` `"1"` when an object with a class other than `Integer`, `Float`, `String` or `Array` is given. The other functions blow up when, for example, a `Symbol` is passed where a `Numeric` is expected. I suspect Python behaves similarly. [Answer] ## JavaScript ES 6 - 175 Bytes I'm counting everything up to the arrow as part of the declaration. **Range 57:** ``` range=(a,b,c)=>{for(r=[i=0];i<Math.ceil((b-a)/c);r[i]=a+i++*c);return r} ``` **Type 45:** ``` type=a=>a.big?'str':a.map?'list':~~a!=a?'float':'int' ``` **Round 54:** ``` round=(a,b)=>(c=Math.pow(10,b),d=a*c,e=d-~~(d),(e<0.5?d-e:d+1-e)/c) ``` **Enumerate 19:** ``` enumerate=a=>a.map((x,y)=>[y,x]) ``` [Answer] ## Python 2 – ~~309~~ 303 ``` t=type=lambda x:["list","string","int","float"][(`x`[0]!="[")*(1+(`x`[0]!="'")*(1+("."in`x`)))] def T(s,a,i,b=1): try:return(1/(t(i)=='int'))*eval(s) except:return 1 r=range=lambda a,b,i:T("[a]+r(a+i,b,i)if b*i>a*i else[]",a,i,b) enumerate=lambda a:T("map(list,zip(r(0,len(a),1),a))",a,1) def round(a,i):b=T("10.**-i/2*a/abs(a)",a,i);return T("a-(a+b)%(b*2)+b",a,i,b) ``` It’s so long, because it complies with the requirements (if I am not mistaken), in particular returning `1` for invalid input. [Matsjoyce’ answer](https://codegolf.stackexchange.com/a/38700/11354) provided some inspirations. [Answer] # Python 3 - 199 ## Range - 48 ``` def range(s,e,g): r=[] while[s>e,s<e][g>0]:r+=[s];s+=g return r ``` ## Enumerate - 32 ``` enumerate=lambda x:[[i,x[i]]for i in range(len(x))] ``` Or ``` enumerate=lambda x:zip(range(len(x)),x) ``` But this doesn't return a list ## Round - 29 ``` def round(x,a): a=10**-a return(x+a/2)//a*a ``` ## Type - 90 ``` def type(x): x=repr(x) if x[0]in"'\"":return str if x[0]=="[":return list return[int,float]["."in x] ``` [Answer] # Haskell, 86 ``` import Data.Typeable approx f n=toEnum(fromEnum$10^n*f+0.5)/10^n getType a=typeOf a range a b c=[a,a+c..b-c/abs c] enumerate=zip[0..] ``` In Haskell there is a type system, so I allowed myself to have a `Typeable` type-class restriction in `getType`'s type (`type` is a reserved name in Haskell). to clarify, this is impossible in any other way, as in Haskell you can't cast variables to other types and catch the resulting type exceptions - Haskell simply does not have type errors. The `enumerate` functions returns a list of two tuples instead of a list of lists, and I figured that if python tuples weren't immutable they would use them instead. note that there's already a `round` function in Haskell so I called the `round` function `approx`. [Answer] # AppleScript, 382 AppleScript is fun to golf but can't compete with other languages. I count the function bodies, but not the declarations of `on handler(arg)` and `end handler`. ``` --range: 82 bytes on r(i,j,c) try set a to{} repeat while i/c<j/c set a to a&i set i to i+c end a on error 1 end end r -- type: 131 bytes on type(x) try if x=x as list "list" else if x=x as text "str" else if x=x as real and"."is in x as text "float" else "int" end on error 1 end end type -- round: 70 bytes on round2(x,p) try set m to 10^-p if x<0then set m to-m (x+m/2)div m*m on error 1 end end round2 -- enumerate: 99 bytes on enumerate(x) try set a to{} repeat with i in r(1,1+count x,1) set a to a&{{i-1,x's item i}} end a on error 1 end end enumerate -- examples: see results in event log log r(1, 10, 1) log r(1, 10, 2) log r(10, 5, -1) log type(12) log type(12.0) log type("12") log type({13, 45}) log round2(0.5, 0) log round2(0.2, 0) log round2(3.14159, 3) log round2(127.56, -2) log round2(12.564, 2) log round2(1457, -2) log enumerate({1, 2, 3, 4}) log enumerate({"spam", "eggs"}) log enumerate(23) log round2(56, "hello") log r("hi", 4, 1) ``` ## range I renamed `range` to `r` because my `enumerate` function calls `r`. I use AppleScript errors to detect invalid arguments. If AppleScript raises an error, then the `try` structure returns 1. Beware that `range([1], "10", 1)` raises TypeError in Python, but `r({1}, "10", 1)` is valid here, because AppleScript's operators accept single-item lists and strings as numbers. The `try` body is just this: ``` set a to {} -- empty list repeat while i / c < j / c set a to a & i -- append i to list set i to i + c end ``` The condition needs to be `i < j` when c is positive, or `i > j` when c is negative. I golfed it as `i/c<j/c`, because the division reverses the comparison when c is negative. As a bonus, c being zero raises a division by zero error, so I correctly reject c being zero as invalid. Beware that `set a to a & i` is slow because it copies the whole list `a` every time. The fast way might look like `set r to a reference to a`, then `set end of r to i`, but that is not golf. ## type AppleScript's type operator is `class of x` (or `x's class`). My own `type` function uses operator `=`, because `1 + "1"` is 2 but `1 = "1"` is false. The `try` body is this: ``` if x = (x as list) "list" else if x = (x as text) "str" else if x = (x as real) and "." is in (x as text) "float" else -- assume x = (x as integer) "int" end ``` Some arguments are invalid; try calling `type(AppleScript)` or `type(type)`. Then `x as text` or `x as real` raises an error and I return 1. It helps that `x as list` always works and `x as text` works with any number. Because `12 = 12.0` is true, I need another way to tell floats from ints. I observe that `12 as text` is "12" but `12.0 as text` is "12.0", so I check for "." in string. I have no check for infinities or NaN because trying to compute those would raise errors. ## round I renamed `round` to `round2` because AppleScript has `round` in its standard additions. The `try` body is this: ``` set m to 10^-p if x < 0 then set m to -m ((x + m / 2) div m) * m ``` I observe `div` truncating toward zero. For rounding, I must calculate `x + m / 2` when x is positive, or `x - m / 2` when x is negative. For golf, I can negate m. In the `div m*m` part, the negative sign of m cancels itself. Python's `round` typically returns a float, but this `round2` often returns an integer. AppleScript's operators like to convert floats to integers, perhaps to help 68k Macs with no FPU. (PowerPC Macs emulated a 68LC040 with no FPU.) ## enumerate My `enumerate` also works with strings. The `try` body is this: ``` set a to {} repeat with i in r(1, 1 + (count x), 1) set a to a & {{i - 1, x's item i}} end a ``` I must not use AppleScript's range loop (`repeat with i from 1 to count x`), but I may call my own range function. I tried to golf away the final a, but I need it when enumerating the empty list or string. Beware that i is a reference to a number, not the number itself. If I looped in `r(0,count x,1)` and collected `{{i,x's item(i+1)}}`, the result might look like `{{item 1 of {0, 1}, "spam"}, {item 2 of {0, 1}, "eggs"}}`. The operations `i-1` and `x's item i` coerce i to a number. [Answer] ## APL (43+19+18+38=118) ``` type←{''≡0↑⍵:'str'⋄⍬≢⍴⍵:'list'⋄⍵=⌈⍵:'int'⋄'float'} ⍝ 43 round←{0::1⋄∆÷⍨⍎0⍕⍵×∆←10*⍺} ⍝ 19 enumerate←{0::1⋄(¯1+⍳⍴⍵),¨⊂¨⍵} ⍝ 18 range←{0::1⋄0<∆←-⍺⍺:⌽∆+⍵(∆∇∇)⍺⋄⍺<⍵:⍺,⍵∇⍨⍺-∆⋄⍬} ⍝ 38 ``` I made the argument order consistent with general APL style. [Ungolfed, with explanation](https://gist.github.com/marinuso/884915fb157c0c102fa8). Test: ``` ⍝ range: <start> <step> range <end> 1 (1 range) 10 1 2 3 4 5 6 7 8 9 1 (2 range) 10 1 3 5 7 9 10 (¯1 range) 5 10 9 8 7 6 ⍝ type: type <obj>. ⍝ 1.0 is considered int, because APL itself does not make the distinction type 12 int type 12.1 float type '12' str type (13 45) list ⍝ APL's native type function: ⎕DR¨ 12 12.0 12.1 83 83 645 ⍝ round: <digits> round <value> 0 round 0.5 1 0 round 0.2 0 3 round 3.14159 3.142 ¯1 round 127.56 130 ¯2 round 127.56 100 2 round 12.5640 12.56 ¯2 round 1457 1500 ⍝ enumerate: enumerate <list> enumerate 1 2 3 4 ┌───┬───┬───┬───┐ │0 1│1 2│2 3│3 4│ └───┴───┴───┴───┘ enumerate 'spam' 'eggs' ┌────────┬────────┐ │┌─┬────┐│┌─┬────┐│ ││0│spam│││1│eggs││ │└─┴────┘│└─┴────┘│ └────────┴────────┘ ``` [Answer] # Axiom, ~~438~~ 445 bytes ## The macro used 18 bytes ``` I==>"int";T==>type ``` Two macros named I=="int" and T=="type" ## the type function 124 bytes ``` T a==(y:=(tex domainOf a).1;suffix?("Integer()",y)=>I;y="Float()"=>"float";y="String()"=>"str";prefix?("List ",y)=>"list";y) ``` Function type()[or T] that retrun "int" "float" or "list" it depend of the type of its argument. It can not fail, it would return the right string for the type int, float, list of ???, string, or othewise would return one unknow string different, in Tex language that says its type in Axiom. Example: ``` (26) -> q:=set [x**2-1, y**2-1, z**2-1];type(q) (26) "Set \left( {{Polynomial \left( {{Integer()}} \right)}} \right)" Type: String ``` ## the round function 152 bytes ``` Round(a,c)==(v:=T a;(v~="float"and v~=I)or T c~=I=>%i;a<0=>-Round(-a,c);z:=a*10.^c;x:=truncate(z);w:=0.5+x-z;0<=w and w>10^-digits()=>x/10^c;(x+1)/10^c) ``` It would return the Round() of the number (it is in count the error of float so we impose bheaviour of it is of the kind Round(0.4999999999999999999, 0) is 0.0 but Round(0.499999999999999999999, 0) is 1.0 and so Round(0.49999999999999999999999999999999, 0) is 1 too). if Round(a,c) find one error it return the complex number %i [the complex costant i]. I don't know how write it without one call one function equivalent to floor (I'm sorry) ## the range function 95 bytes ``` Range(a,b,c)==(T a~=I or T b~=I or T c~=I=>[];[a+c*i for i in 0..(Round((b-a)/c*1.,0)::INT-1)]) ``` It would return the result range as a list of number; if find one error it would return the void list []. It use the above type() and Round(,) function too. ## The enumerate function 56 bytes ``` enumerate a==(T a~="list"=>[];[[i-1,a.i]for i in 1..#a]) ``` It would enumerate the element of the list as in the question; in case of error return [] void list. ## Result in the session ``` (5) -> [[i,j,Round(i,j)] for i in [0.5,0.2,3.14159,127.56,12.5640,1457] for j in [0,0,3,-2,2,-2]] (5) [[0.5,0.0,1.0], [0.2,0.0,0.0], [3.14159,3.0,3.142], [127.56,- 2.0,100.0], [12.564,2.0,12.56], [1457.0,- 2.0,1500.0]] Type: List List Complex Float (6) -> Range(1,10,1) (6) [1,2,3,4,5,6,7,8,9] Type: List Integer (7) -> Range(1,10,2) (7) [1,3,5,7,9] Type: List Integer (8) -> Range(10,5,-1) (8) [10,9,8,7,6] Type: List Integer (9) -> type(12) (9) "int" Type: String (10) -> type(12.0) (10) "float" Type: String (11) -> type([13,45]) (11) "list" Type: String (12) -> enumerate([1,2,3,4]) (12) [[0,1],[1,2],[2,3],[3,4]] Type: List List Integer (13) -> enumerate(["spam","eggs"]) (13) [[0,"spam"],[1,"eggs"]] Type: List List Any (14) -> enumerate(23) -- error for enumerate (14) [] Type: List None (15) -> Round(56,"hello") -- error for Round (15) %i Type: Complex Integer (16) -> Range("hi",4,1) -- error for range (16) [] Type: List None ``` In total and in partial too it is a very good question: Thank you very much. ]
[Question] [ What is the shortest way to check if two or more variables are equal to 0 in JavaScript? I'm curious to know if there's something shorter than `if(!x&&!y&&!z){...}`. [Answer] (**EDIT:** This first part refers to the original phrasing of the question.) First, `(!x&&!y&&!z)` returns a boolean, which makes `?true:false` entirely redundant. It's basically like using ``` if (x == true) return true; else if (x == false) return false; ``` instead of `return x;`. That gives you ``` !x&&!y&&!z ``` (**EDIT:** The remainder still applies to the new version of the question.) Now you could apply [De Morgan's law](http://en.wikipedia.org/wiki/De_Morgan%27s_laws). The above is equivalent to ``` !(x||y||z) ``` Which is the same length for 3 variables and longer for 2 variables. But for each variable beyond the third, you save one more character! Lastly, if you know that your variables are numbers, you can also use the bitwise operator, i.e. ``` !(x|y|z) ``` If you actually need booleans (which I assume from your snippet), this doesn't work for the `&` case, because `!x&!y&!z` will give you an integer. Then again, in JavaScript it's often enough to have *truthy* or *falsy* values, in which case, that's a perfectly valid option. **Bonus tip:** if you ever *want* to turn a truthy/falsy value (like a non-zero/zero number) into a boolean, *don't* use `x?true:false` either, but use `!!x` instead. `!x` is a boolean with the opposite truthiness/falsiness than `x`, so `!!x` is `true` for `x` *truthy* and `false` for `x` *falsy*. [Answer] Just an addendum. In the special case where the block contains just a procedure call, you can replace ``` if(!x&&!y&&!z){call();} ``` by ``` x||y||z||call(); ``` [Answer] This function is obviously not the shortest until you have a lot of numbers to check (the poster did say "or more"). It verifies that all arguments are equal to zero. ``` function AllZero() { var args = Array.prototype.slice.call(arguments); args.push(0); return Math.min.apply(Math,args) === Math.max.apply(Math,args); } ``` If you push a different number in the args.push(x) line, it will check that all of the arguments are equal to that number. ]
[Question] [ 8-bit XOR encryption takes a single byte and XORs every byte in the file by that byte. Here is a reference program in C++: ``` /*xorcipher.cpp *Encrypts a file using 8-bit xor encrytpion */ #include <iostream> #include <fstream> #include <stdlib.h> using namespace std; int main(int argc, char** argv){ ifstream* in = NULL; ofstream* out = NULL; if(argc < 3){ cerr << "Usage: xor <key> <filename...>" << endl; exit(1); } int key = atoi(argv[1]); for(int x = 2; x < argc; x++){ in = new ifstream(argv[x], ios::binary); if(!in->good()){ cerr << "Error reading from " << argv[x] << endl; exit(1); } //Get file size in->seekg(0, ios::end); int size = in->tellg(); in->seekg(0, ios::beg); //Allocate memory int* data = new int[size]; int c = 0; for(int y = 0; (c = in->get()) != EOF; y++) data[y] = c ^ key; in->close(); delete in; in = NULL; out = new ofstream(argv[x], ios::binary); if(!out->good()){ cerr << "Error writing to " << argv[x] << endl; exit(1); } for(int y = 0; y < size; y++) out->put(data[y]); out->flush(); out->close(); delete out; out = NULL; delete[] data; data = NULL; } cout << "Operation complete" << endl; return 0; } ``` The shortest answer (whitespace doesn't count) that produces the same end result will be selected. It does not have to store everything in memory at once or open and close every file multiple times. It can do anything as long as a file encrypted with the reference program can be decrypted with the answer, and vice versa. --- **Edit**: The above program is not a specification. The only requirement is that answers should be able to decrypt a file encrypted with the above program, and the above program should be able to decrypt a file encrypted with the answer. I'm sorry if that was unclear. The above program can be compiled with: ``` g++ xorcipher.cpp -o ~/bin/xor ``` It can be run like this: ``` xor <key> <filename...> ``` For example, if the key is `42` and the file is `alpha.txt`, you would use: ``` xor 42 alpha.txt ``` [Answer] # Brainfuck - 269 ``` ,>,[<[>>+>+<<<-]>>>[<<<+>>>-]>>>++++++++[-<<<<<[->>+<<[->>->+<]>>[->>> >+<<]<<<<]>>>[-<<<+>>>]<<[->+<[->->+>>>>>]>[->>>>>+>>]<<<<<<<<]>>[-<<+ >>]>>>[->>+<<]>[>[-<->]<[->+<]]>[[-]<<<[->+>-<<]>[-<+>]+>+++++++[-<[-> >++<<]>>[-<<+>>]<]<[->>>>+<<<<]>>]<<<]>>>>>.[-]<<<<<<<<<<,] ``` [Answer] ## PHP ~~40~~ 38 bytes ``` <?for(;;)echo@~fgetc(STDIN)^~$argv[1]; ``` And updated version. Now handles all inputs correctly, and 2 bytes shorter as well. Sample usage: ``` $ more in.dat This is a test. This is only a test. $ php xor-cipher.php A < in.dat > out.dat $ more out.dat §)(2a(2a a5$25oK§)(2a(2a./-8a a5$25o $ php xor-cipher.php A < out.dat This is a test. This is only a test. ``` --- ## Perl 30 bytes ``` $k=pop;s/./print$&^$k/egsfor<> ``` I/O is the same as for the PHP solution above. [Answer] ## C, 61 59 bytes Quite simple, and very similar to [primo's solution](https://codegolf.stackexchange.com/a/9258/3544). First parameter is the key, in decimal, reads stdin, writes stdout. The only tricky part is using `~getchar`, so `EOF` becomes `0` and terminates the loop, then printing `c^~key`, where the additional `~` undoes the previous one. ``` main(c,v)int*v;{ while(c=~getchar())putchar(c^~atoi(v[1])); } ``` [Answer] # The Powder Toy, 598 bytes, 8 particles Only 8 particles and O(n) speed. :) (This is unsurprisingly difficult in TPT for most tasks unless you know subframe really well; I do not.) This creation takes input at a rate of 8 bits per frame, with a 8 bit word size. If you input the xor byte 3 times at once (24bit), then you can process 3 bytes of the stream per frame. Reversible xxd dump: ``` 00000000: 4f50 5331 5d04 9960 151d 0c00 425a 6839 OPS1]..`....BZh9 00000010: 3141 5926 5359 5cdf 0ea9 006c 37ff ffff 1AY&SY\....l7... 00000020: f553 0252 11d7 423f 27df b6bf f7df e340 .S.R..B?'......@ 00000030: 0200 4000 0400 1050 0008 0000 2002 0840 [[email protected]](/cdn-cgi/l/email-protection).... ..@ 00000040: 01fc 69b5 3508 44d1 0068 0034 1ea0 6800 ..i.5.D..h.4..h. 00000050: 0d03 4034 6800 000d 0814 d4fd 2626 4c89 ..@4h.......&&L. 00000060: a68d 0190 0000 d343 4069 9003 4d03 8686 [[email protected]](/cdn-cgi/l/email-protection)... 00000070: 4d34 34c8 d0d3 2320 c8c8 d0c8 0c4d 1934 M44...# .....M.4 00000080: 0193 2310 c244 9232 86a6 327a 4191 a260 ..#..D.2..2zA..` 00000090: 0046 2604 6260 8600 d263 4dbb b2e2 d1e3 .F&.b`...cM..... 000000a0: 21f5 cd39 7920 2062 4360 0924 1e6c 4021 !..9y bC`.$.l@! 000000b0: 2224 22bb f2b3 9fbd 77d2 c6ad dc4e 4b3c "$".....w....NK< 000000c0: 9fac 12d3 9ad6 6cae 6940 2409 08b2 9961 ......l.i@$....a 000000d0: a30e 9a64 b599 68b6 e10a 87ac c869 64a6 ...d..h......id. 000000e0: 6977 e649 2102 4227 62ce 6214 0641 cc41 iw.I!.B'b.b..A.A 000000f0: b575 205e 255c 520c 4603 15cc a222 4325 .u ^%\R.F...."C% 00000100: 1df7 2106 df63 c319 3bfd d191 25a8 0020 ..!..c..;...%.. 00000110: 0484 3ab5 62ab ef4d 0902 4236 d9d3 eb8d ..:.b..M..B6.... 00000120: 23f1 3ee4 8113 30c0 6435 d122 2572 033d #.>...0.d5."%r.= 00000130: 9edb f17a ac03 636c 60c0 82b9 1226 125c ...z..cl`....&.\ 00000140: 20c0 8855 972a ac26 833a 8466 8143 208a ..U.*.&.:.f.C . 00000150: 4c9d 811d 9ec1 d800 356e ad3f 9b51 e0a0 L.......5n.?.Q.. 00000160: 8a96 54ff 891d c761 71c3 3618 5844 f4f2 ..T....aq.6.XD.. 00000170: 5453 ac54 d94a b86d 8261 11c9 3b70 4222 TS.T.J.m.a..;pB" 00000180: 9bfb 2445 4443 f202 f004 5b14 e01d 1696 ..$EDC....[..... 00000190: e06d 7348 e262 981e 847f 9e4d ba42 9040 .msH.b.....M.B.@ 000001a0: d740 45b1 8fd9 7a62 20b8 7850 a40b a2a1 [[email protected]](/cdn-cgi/l/email-protection) .xP.... 000001b0: 34a5 a790 c2ab 8af3 2bec d254 9b50 c39e 4.......+..T.P.. 000001c0: 1b74 9ec7 3627 63b2 f9da f832 09a4 9406 .t..6'c....2.... 000001d0: 135c 78e3 0a29 a9ac 991a 44da a6d9 e38c .\x..)....D..... 000001e0: 4886 f6db 9a65 3ce9 bd32 b3a9 8522 a053 H....e<..2...".S 000001f0: 5ee2 a930 527b 8dd6 f7b5 b5a9 15d7 b771 ^..0R{.........q 00000200: 8d2f bace a196 d95b f48c a895 05a1 0402 ./.....[........ 00000210: c2c3 48cc 8e90 3567 0b0c acab 0eb2 1ce2 ..H...5g........ 00000220: 80e9 40e7 1432 82fe b141 4412 b86b e551 [[email protected]](/cdn-cgi/l/email-protection) 00000230: 33bf 6160 a733 e306 cca3 5479 bf93 9a21 3.a`.3....Ty...! 00000240: 8921 0024 2342 f402 4090 8f91 7724 5385 .!.$#[[email protected]](/cdn-cgi/l/email-protection)$S. 00000250: 0905 cdf0 ea90 ``` ### I/O This creation takes the byte to XOR data by in particle #0, and the data stream at particle #4. Output is given by any particle at X 501. Once the stream is over it decodes the last byte(s) forever. The XOR byte must have the 30th bit set, and the data byte must NOT have the 30th bit set. This is due to the fact that a input of 0 will cause no output if this is not done in this manner (TPT filt logic restriction, cannot be worked around) ### What does it look like? [TODO] ### How does it work? [Also TODO. Sorry.] [Answer] **Python, 78 chars** ``` from sys import argv as v print ''.join(chr(ord(v[1])^ord(i)) for i in open(v[2]).read()) ``` Must be run like: ``` python solution.py <key> <input_file> > <output_file> ``` Where `solution.py` is the python file that contains the above code, key is the single byte to XOR, `input_file` is the file to be encrypted and `output_file` will contain the decrypted output. I am not sure if it matches your solution (as per "...that produces the same end result will be selected") since your example doesn't seem to produce output. However, it does successfully decrypt an encrypted file with the same key byte. Since whitespace doesn't count, I used the following code to count chars: ``` >>> with open('solution.py') as f: ... text = f.read() ... >>> len(text) - text.count('\n') - text.count(' ') # There are no tabs in this code 78 ``` [Answer] # Python 75 ``` import sys for j in sys.stdin:print''.join(chr(int(sys.argv[1])^ord(i))for i in j), ``` The hardest requirement was not to keep the whole file in memory. Usage: ``` python xor.py 123 <file.in >file.out ``` [Answer] ### GolfScript, 16 characters ``` "#{$*}"~{^}+%:n; ``` Usage is as given above - the key (numeric) passed as parameter while input/output is through console: ``` golfscript.rb xor.gs 42 <in.txt >out.txt ``` *Edit:* The issues with the trailing newline are now solved. [Answer] # Postscript ~~101~~ 67 ``` (]){exch def}def ARGUMENTS aload pop(w)file/O](r)file/I]cvi/K]{O I read not{exit}if K xor write}loop ``` The 67 byte version is equivalent to the above with all executable system names replaced by binary tokens. It is produced as output by this program (which shows a hex representation). ``` (xorb.ps)(w)file < 285D297B923E92337D9233 415247554D454E54539202927528772992412F4F5D 28722992412F495D922C2F4B5D 7B4F2049927B92707B92407D92544B92C192BC7D9265 > writestring ``` Invoke with ghostscript's argument-processing option `--`. ``` josh@Z1 ~ $ gs -dNODISPLAY -- xorw.ps GPL Ghostscript 9.06 (2012-08-08) Copyright (C) 2012 Artifex Software, Inc. All rights reserved. This software comes with NO WARRANTY: see the file PUBLIC for details. josh@Z1 ~ $ xxd xorb.ps 0000000: 285d 297b 923e 9233 7d92 3341 5247 554d (]){.>.3}.3ARGUM 0000010: 454e 5453 9202 9275 2877 2992 412f 4f5d ENTS...u(w).A/O] 0000020: 2872 2992 412f 495d 922c 2f4b 5d7b 4f20 (r).A/I].,/K]{O 0000030: 4992 7b92 707b 9240 7d92 544b 92c1 92bc I.{.p{.@}.TK.... 0000040: 7d92 65 }.e josh@Z1 ~ $ gs -dNODISPLAY -- xorb.ps 42 xor.ps xor.ps.out GPL Ghostscript 9.06 (2012-08-08) Copyright (C) 2012 Artifex Software, Inc. All rights reserved. This software comes with NO WARRANTY: see the file PUBLIC for details. josh@Z1 ~ $ gs -dNODISPLAY -- xorb.ps 42 xor.ps.out xor.rev GPL Ghostscript 9.06 (2012-08-08) Copyright (C) 2012 Artifex Software, Inc. All rights reserved. This software comes with NO WARRANTY: see the file PUBLIC for details. josh@Z1 ~ $ diff xor.ps xor.rev josh@Z1 ~ $ ``` [Answer] # q/kdb+, 35 bytes (41 including whitespace) **Solution:** ``` {x 1:0b sv'(0b vs 4h$y)<>/:0b vs'read1 x} ``` **Example:** ``` q)read0 `:test.txt "Hello World!" "Welcome to PPCG :)" q){x 1:0b sv'(0b vs 4h$y)<>/:0b vs'read1 x}[`:test.txt;"A"] `:test.txt q)read0 `:test.txt "\t$--.a\026.3-%`" "\026$-\".,$a5.a\021\021\002\006a{h" q){x 1:0b sv'(0b vs 4h$y)<>/:0b vs'read1 x}[`:test.txt;"A"] `:test.txt q)read0 `:test.txt "Hello World!" "Welcome to PPCG :)" ``` **Explanation:** Read in the file as a bytestream, convert to bitstream, convert key to bitstream and xor `<>` with each byte. Convert back to bytestream and write back to file: ``` {x 1:0b sv'(0b vs 4h$y)<>/:0b vs'read1 x} / ungolfed solution { } / lambda function taking x and y as implicit parameters read1 x / read file x as bytestream 0b vs' / convert each byte to bits (boolean list) <>/: / xor (<>) left with each-right (/:) ( ) / do this together 4h$y / convert key to a byte 0b vs / convert byte to bits (boolean list) 0b sv' / convert each list of bits to a byte x 1: / write bytes to file x ``` **Notes:** If we drop to the `k` prompt we have a 32 byte solution (33 inc whitespace), pretty much a straight port except we dont have `<>` for xor. ``` {x 1:0b/:'~(0b\:4h$y)=/:0b\:'1:x} ``` **K4 Example:** ``` {x 1:0b/:'~(0b\:4h$y)=/:0b\:'1:x}[`:test.txt;"A"] `:test.txt 0:`:test.txt ,"\t$--.a\026.3-%`K\026$-\".,$a5.a\021\021\002\006K" {x 1:0b/:'~(0b\:4h$y)=/:0b\:'1:x}[`:test.txt;"A"] `:test.txt 0:`:test.txt ("Hello World!";"Welcome to PPCG") ``` [Answer] # [Tcl](http://tcl.tk/), 120 bytes ``` set t [open t w] lmap x [split [read [open $argv]] ""] {puts -nonewline $t [format %c [expr 255^[scan $x %c]]]} close $t ``` [Try it online!](https://tio.run/##pZNRa4MwFIXf/RUX59jGcA@WvuxtWAvCqFAdbKQZiEu3DJuIuZ1C6W/vUqu24qCWvSb3nnM8n8Ek3V0VOUcGMSx5yqDg@AVPoev7MHIAJTjjsaEYwhKIzJgAJdd5wh6wRCiogXzFYJOtUYEtpGBFygUDSw8vZb6KEa4TIKzMcq12T7hIcuCU0i04zshIUqn2w4ZRCZhh8DJ3PZj6z96jeTgjOYs/es6UNisLcbJU53aDiRe2At@SCyDpKs6gBKKylGNH1Yrzzx9KwTQpbPYfquCWqCTWN6VOT@@21d1BbSFs2z7rDa/B/Mab/C9CVZou//00TJNmt5/Cer0CMVC9Rwr7pHqmdNugwso46ugfaRzaacpxg1nkzaIQgqmOqGuJ/NlbB64V/bnYHR4M1YrqAtvkNbnLPIbAa62GsBri33Z1gflZbPWvsju@m18 "Tcl – Try It Online") [Answer] # [Chip](https://github.com/Phlarx/chip), 39 bytes (62 incl. whitespace) ``` A0 C2 E4 G6 a{L}bc{L}de{L}fg{L}hS!9 1B 3D 5F 7H ``` [Try it online!](https://tio.run/##S87ILPj/X8HRQEFBwdkISLiaAAl3M67Eap/apGQgkZIKJNLSgURGsKIll4KCoRNQhbELkDB1AxLmHv//Oyjrq6gmqOvrqAEA "Chip – Try It Online") The first byte of stdin is the key, all other bytes are the message. The elements `H-A` are the eight bits of each input byte, `h-a` are the eight bits of each output byte, and `7-0` are the eight bits of the stack head. On the first cycle, `S!9` causes the input bits to be written to the stack (along with the pairs like `A0`, `1B`...), and prevents any output. On subsequent cycles, the input bits are xor'd with their corresponding stack bits to produce the output bits. A single bit is computed like this: ``` A0 a{' ``` or like this: ``` ,}b 1B ``` (which are just rotations of each other). Those two patterns can be made to overlap slightly, and we use four of each to cover all eight bits. ]
[Question] [ This is how I checkout to see if a number is in a range (in between two other numbers): ``` var a = 10, b = 30, x = 15, y = 35; x < Math.max(a,b) && x > Math.min(a,b) // -> true y < Math.max(a,b) && y > Math.min(a,b) // -> false ``` I have to do this math in my code a lot and I'm looking for shorter equivalent code. This is a shorter version I came up with. But I am sure it can get much shorter: ``` a < x && x < b true a < y && y < b false ``` But downside is I have to repeat `x` or `y` [Answer] 13 chars, checks both variants a<b and b<a ``` (x-a)*(x-b)<0 ``` In C may be used expression (may be also in JavaScript). 11 chars, No multiplications (fast) ``` (x-a^x-b)<0 ``` [Answer] ``` a<x==x<b ``` JavaScript, 8 chars. [Answer] # JavaScript, 7 bytes ``` a<n&n<b ``` ]
[Question] [ **This question already has answers here**: [Find the occurrences of a character in an input string](/questions/55880/find-the-occurrences-of-a-character-in-an-input-string) (58 answers) Closed 4 years ago. Your task is to input a string, and output the number of spaces in the string. This is code-golf, so least number of bytes win. Your # Test Cases Double quotes are not part of the test cases. ``` "test" => 0 "Hello, World!" => 1 "C O D E G O L F" => 7 " " => 6 ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 3 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") ``` +/= ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X1vf9n/ao7YJj3r7HvVN9fR/1NV8aL3xo7aJQF5wkDOQDPHwDP6fpl6SWlyizpWm7pGak5OvoxCeX5SToggScFbwV3BRcFVwB9I@Cm4gIQUwUAcA "APL (Dyalog Extended) – Try It Online") `+/` sum the mask where `=` equal to the prototypical element of that element, which is space for characters. [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 93 bytes ``` [S S S N _Push_0][N S S N _Create_Label_LOOP][S N S _Duplicate_top][S N S _Duplicate_top][T N T S _Read_STDIN_as_character][T T T _Retrieve_input][S S S T S T S N _Push_10][T S S T _Subtract][S N S _Duplicate_top][N T S T N _If_0_jump_to_label_DONE][S S S T S T T S N _Push_22][T S S T _Subtract][N T S S N _If_0_jump_to_label_SPACE][N S N N _Jump_to_Label_LOOP][N S S S N _Create_Label_SPACE][S S S T N _Push_1][T S S S _Add][N S N N _Jump_to_Label_LOOP][N S S T N _Create_Label_DONE][S N N _Discard_top][T N S T _Print_as_integer] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. Since Whitespace inputs one character at a time, the input should contain a trailing newline so it knows when to stop reading characters and the input is done. [Try it online](https://tio.run/##LY3BCcAwDAPf8hTaoROlJZD8CjF0g747Yxdx5TRgS/hs4at1r@MsR40gaabmFBgIQFBODanpsJ8tmKKYZZRzlYSLIF2CCG99UFWoj66T9364cT4fyMHLbh8) (with raw spaces, tabs and new-lines only). An appropriate language for the challenge I guess. PS: The program itself contains 44 spaces. **Explanation in pseudo-code:** ``` Integer counter = 0 Start LOOP: Character c = STDIN as character If(c == ' '): Call function SPACE Else-if(c == '\n'): Call function DONE Go to next iteration of LOOP function SPACE: counter = counter + 1 Go to next iteration of LOOP function DONE: Print counter as integer to STDOUT ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 3 2 bytes ``` ð¢ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8IZDi/7/d1bwV3BRcFVwB9I@Cm4A "05AB1E – Try It Online") Simple explanation: ``` ð Pushes ' ' space character onto stack ¢ Counts the spaces in the input string ``` Found the 'ð' Command which saves 1 Byte for pushing a space. [Answer] # [J](http://jsoftware.com/), 8 bytes ``` 1#.' '=] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX11BXUbWP/a3JxpSZn5AOlbBXSFNRLUotL1CEihhARj9ScnHwdhfD8opwURaiUOUTKWcFfwUXBVcEdSPsouEElzSCSCmCg/h8A "J – Try It Online") [Answer] # [PHP](https://php.net/), 26 bytes ``` <?=count_chars($argn)[32]; ``` [Try it online!](https://tio.run/##K8go@P/fxt42Ob80ryQ@OSOxqFhDJbEoPU8z2tgo1vp/anJGvoJSTJ6S9f@S1OISLo/UnJx8HYXw/KKcFEUuZwV/BRcFVwV3IO2j4MalAAb/8gtKMvPziv/rugEA "PHP – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 20 bytes I really hope this is not optimal ``` a=>a.Count(b=>b==32) ``` [Try it online!](https://tio.run/##Sy7WTS7O/O9WmpdsU1xSlJmXrqOQmVdip@CmYPs/0dYuUc85vzSvRCPJ1i7J1tbYSPO/NVcAUFmJhpuGUolCqkKxQomSpqb1fwA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 7 bytes ``` $_=y; ; ``` [Try it online!](https://tio.run/##K0gtyjH9X6wfp1SjpKelr59u/V8l3rbSWsH6/3@lktTiEiUFWzsFAy4lj9ScnHwdhfD8opwURbCgIZeSs4K/gouCq4I7kPZRcAMLm3MpKYABmGf2L7@gJDM/r/i/bk4BAA "Perl 5 – Try It Online") [Answer] ## CJam (5 bytes) ``` q' e= ``` [Online demo](http://cjam.aditsu.net/#code=q'%20e%3D&input=This%20is%20a%20test) ``` qS/,( ``` [Online demo](http://cjam.aditsu.net/#code=qS%2F%2C(&input=This%20is%20a%20test) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 18 bytes ``` ($args-eq32).count ``` [Try it online](https://tio.run/##HY7LCgIxDEX3/YpridJCFR@gIAiCz4Xg0qWMWnQxWO2MKIzz7fU62STnXELyCG8fi5vP8yQnzFAlI1m8Fl3/HA1t7xxe9zLVShld@qLUDn3rCFsuBIdDiPmlRTto7AJ7LLHChn2HNf2k8WiKOLb4ol0pQDIH@fCgHP8UOXXAD@YZUYthxhcY2CmkirVWdfoB). Expects input via [splatting](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting). [Answer] # Java 8, 27 bytes ``` s->s.split(" ",-1).length-1 ``` [Try it online.](https://tio.run/##ZU@xTsMwEN37FQ8vtZXGUlcqWKCFAcrQgQEYjGNaF9eJcpdKCPXbg2PCUOHhrHvv3b13e3M05b767G0wRHg0Pn5PAB/ZtR/GOqyHNgOwcsOtj1uQWiTwNEmF2LC3WCPiqqfymjQ1wbMUELNyrnRwccu7ct4vBnXTvYekHoeOta9wSI7j3pc3GPVrx47SjqGK7PWH3LsQ6hme6zZUF@fUDZ5wiyXu0v@A1TmJ/MS/3DlCloyn@dh0PIbYfBG7g6471k0iOUQ5FdMiSwrxKi4hiqitzIC2O9OSVGr0OPU/) **Explanation:** ``` s-> // Method with String as parameter and integer return-type s.split(" ", // Split the input on spaces -1) // While retaining empty strings as items .length // Get the amount of items in the array -1 // And subtract 1 ``` Using the `count()` builtin with a filter for spaces would be 2 bytes longer (or 1 if the input is guaranteed to not contain tabs/newlines/other characters below spaces - in which case the `==32` can be `<33`): ``` s->s.filter(c->c==32).count() ``` [Try it online.](https://tio.run/##ZZA9T8MwEED3/orDS22FeICNKl34lqAMHRgog3Hc4uDYUXyuhFB/e7i4YajwcLbvnu@e3Ki9Kpv6a9BOxQjPyvqfGYD1aPqt0gZW4xXABb8DzRvCZULrZMTeqFY@elznE0SxIPIwoxBRodWwAg/VEMtllFvrqCHX5VJX1eWFkDokj1wMi5Hv0ocjfnq2D7aGlkQ4dbZ@9/YOShwt0ETkbIwsT/vLPBjnwjm8ht7VZ6ela3iBG7iFe9qf4O60CHmxf@ZZISNHBfqPLuEksf6OaFoZEsqOiug8n7N5kZGCbdgVsMJLzXNC6k/VRy7ENOMw/AI) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` {∋Ṣ}ᶜ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv/pRR/fDnYtqH26b8/9/tFJJanGJko6SR2pOTr6OQnh@UU6KIpDvrOCv4KLgquAOpH0U3IAiCmCgFAsA "Brachylog – Try It Online") ``` { }ᶜ The output is the number of ways in which ∋ an element of the input can be chosen Ṣ such that the element is a space. ``` Alternatively, # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes ``` ṇ₁l-₁ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3w/@HO9kdNjTm6QOL//2ilktTiEiUdJY/UnJx8HYXw/KKcFEUg31nBX8FFwVXBHUj7KLgBRRTAQCkWAA "Brachylog – Try It Online") ``` l The length of ṇ₁ the input split on spaces -₁ minus one is the output. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` ċ⁶ ``` [Try it online!](https://tio.run/##y0rNyan8//9I96PGbf///3dW8FdwUXBVcAfSPgpuAA "Jelly – Try It Online") Literally `ċ` count `⁶` spaces. [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), ~~6~~ 4 bytes -2 byte thanks to ngn ``` +/^: ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NSls/zup/mrqGUklqcYmStYKSR2pOTr6OQnh@UU6KIkjAWcFfwUXBVcEdSPsouIGEFMBASfM/AA "K (ngn/k) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 21 bytes ``` lambda s:s.count(' ') ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYqlgvOb80r0RDXUFd839BUSaQmaahnpefl6quqckFFwDyFYoLEpNRRXPzi1IVSjIS8xSQ5f8DAA "Python 3 – Try It Online") [Answer] # JavaScript, ~~24~~ 22 bytes -2 bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) and template literals! ``` s=>s.split` `.length-1 ``` [Try it online!](https://tio.run/##NYy9CsJAEIT7e4o1VQLJgXWIjUYtBEsLERIud/lhuQ3Z1UZ89jNGMs3MfAwz1K@azdSPknlqbHBF4GLHmkfspYJKo/WtdNk2oBUQy8JQwF3BrOhXo/SfzxaRUrjRhM1mhXu4wgFKOM1@geOKYVGkHrlSy6V2NJW16WL39EZ68jEn72VryDOh1Uht7Gaa5OqT5OEL "JavaScript (Node.js) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Yawn! ``` èS ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=6FM&input=InRlc3Qi) [Answer] # [Ruby](https://www.ruby-lang.org/), 15 bytes ``` ->s{s.count' '} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf1664ulgvOb80r0RdQb32f4FCWrR6Xn5eqnosF5gNZCoUFyQmwwVy84tSFUoyEvMUkKT@AwA "Ruby – Try It Online") Uhmmm... [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 9 bytes ``` Count@" " ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zm/NK/EQUlB6X9AUWZeSbRSjJKSjrIOmFJS0LVTUNJJc3DOSCxKTC5JLSp2UI5V03eo5lIqSS0uUdLhUvJIzcnJ11EIzy/KSVEECTgr@Cu4KLgquANpHwU3kJACGChx1f4HAA "Wolfram Language (Mathematica) – Try It Online") Takes a list of characters as input. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 5 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` gÅ =£ ``` Input as a list of characters. [Try it online.](https://tio.run/##y00syUjPz0n7/z/9cKuC7aHF//9Hq5eo66inAnExEJeox3JFqysAWZgYJOMBVZsDxflArANVEQ7lF0HlUoBYEazLGarCH0q7QGlXKO2OJu8Dpd3UYwE) **Explanation:** ``` g # Filter the (implicit) input-list Å # Using the following two commands: = # Equals a space £ # Then pop this filtered list and get its length for the amount of spaces # (after which the entire stack joined together is output implicitly) ``` Or alternatively: `mÅ =Σ` ([Try it online](https://tio.run/##y00syUjPz0n7/z/3cKuC7bnF//9Hq5eo66inAnExEJeox3JFqysAWZgYJOMBVZsDxflArANVEQ7lF0HlUoBYEazLGarCH0q7QGlXKO2OJu8Dpd3UYwE)), which is similar but uses a map & sum instead of filter & length. ]
[Question] [ **This question already has answers here**: [Convert a string of binary characters to the ASCII equivalents](/questions/35096/convert-a-string-of-binary-characters-to-the-ascii-equivalents) (69 answers) Closed 6 years ago. Your task is to write a program, which takes a binary input and converts it to plain text. For Example: ``` 01100001 01100010 01100011 = "abc" ``` ## Rules * Input can come from STDIN, function arguments, command line argument, file, whatever suits you. * The program can be a function, full program, whatever works, really, as long as no external uncounted code/arguments are needed to run it. * You can assume that the input is valid. * The length of the input is **not** limited * You can assume that all blocks are seperated with whitespaces ## Test Cases ``` 01010100 01100101 01110011 01110100 = "Test" 01001000 01100101 01101100 01101100 01101111 = "Hello" 01010111 01101111 01110010 01101100 01100100 00001101 00001010 = "World" 01000101 01111000 01100001 01101101 01110000 01101100 01100101 00001101 00001010 = "Example" 01100010 01101001 01101110 00001101 00001010 = "bin" ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution wins. [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 4 bytes Needs as input the binary blocks with no separator. This is allowed by the OP. ``` 2i?P ``` **[Try it online!](https://tio.run/nexus/dc#@2@UaR/w/7@BoaEBEBhCaCCG0IYA)** **Explanation:** using the "abc" example as test case * `2i?` sets 2 as input radix, then reads the line (output radix is 10 by default). This converts the binary input to decimal: 011000010110001001100011 -> 6382179. * `P` is a special printing mode that assumes a base 256 number, using its "digits" as ASCII codes: 6382179 = (**97** \* 256 2) + (**98** \* 256 1) + (**99** \* 256 0) -> **abc** [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` #CçJ ``` Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@6/sfHi51///BoZgaKBgYAgkgUwQA8SCMoBMAA "05AB1E – TIO Nexus") [Answer] # [Perl 5](https://www.perl.org/), 15 bytes 14 bytes of code + `-p` flag. The input must be supplied *without* final newline (with `echo -n` for instance). ``` $_=pack"B*",$_ ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAtyPmvEm9bkJicreSkpaSjEv//v4GhoQEQGEJoIIbQhlwgIQMI2wDCNoTIgmggiwus2ABFAUwzEg03ydAQJgA1CUUhxCSIENQ9EBtgmuE2GcBtghpkgG6QIRaDEJ4zhBtgiGEjAA "Perl 5 – TIO Nexus") [Answer] ## JavaScript (ES6), 52 bytes ``` s=>String.fromCharCode(...s.split` `.map(s=>`0b`+s)) ``` [Answer] ## sed and dc, 23, 19 bytes ``` sed 's/.*/2i&P/'|dc ``` [Answer] # Pyth, 7 Bytes ``` smCid2c ``` Takes input as string. [Try it!](https://pyth.herokuapp.com/?code=smCid2c&input=%2201100001+01100010+01100011%22&test_suite=1&test_suite_input=%2201100001+01100010+01100011%22%0A%2201010100+01100101+01110011+01110100%22%0A%2201001000+01100101+01101100+01101100+01101111%22%0A%2201010111+01101111+01110010+01101100+01100100+00001101+00001010%22%0A%2201000101+01111000+01100001+01101101+01110000+01101100+01100101+00001101+00001010%22%0A%2201100010+01101001+01101110+00001101+00001010%22&debug=0) [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 10 bytes ``` û{$-2Bo}r. ``` # Explained ``` û # Split the implicit input by Spaces. { }r # Replace each element in a list based on a function. $-2B # Convert from Base 2 o # Get the ordinal of the character. . # Concatenate the list. ``` [Try it online!](https://tio.run/nexus/rprogn-2#@394d7WKrpFTfm2R3v///w0MwdBAwcAQSAKZIAaIBWUAmQA "RProgN 2 – TIO Nexus") [Answer] ## [CJam](https://sourceforge.net/p/cjam), 10 bytes ``` l:~8/2fb:c ``` [Try it online!](https://tio.run/nexus/cjam#@59jVWehb5SWZJX8/7@BoYEBEBsqGBgCAZANYhiAxMAMQ5iUAUwKxISoAUuBVMIZQAgA "CJam – TIO Nexus") ### Explanation ``` l e# Read input. :~ e# Evaluate each character, resulting in a flat list of bits. 8/ e# Split into chunks of 8 bits. 2fb e# Convert each from binary to an integer. :c e# Convert each integer to a character. ``` [Answer] ## Mathematica, 50 bytes ``` FromCharacterCode[#~FromDigits~2&/@StringSplit@#]& ``` [Answer] # [Röda](https://github.com/fergusq/roda), ~~36~~ 35 bytes ``` {split|chr parseInteger(_,radix=2)} ``` [Try it online!](https://tio.run/nexus/roda#y03MzFOoVkizjflfXVyQk1lSk5xRpFCQWFSc6plXkpqeWqQRr1OUmJJZYWukWfufs6C0OENDycDQ0AAIDBUgDEMDGMNQSVOhRiGNq/Y/AA "Röda – TIO Nexus") This is an anonymous function that reads the input from the stream and prints the result. It uses three builtins: * `split` splits the input at whitespaces * `parseInteger` converts a binary string to an integer value * `chr` converts an integer to a Unicode character [Answer] # Gema, 33 characters ``` <D><s>=@int-char{@radix{2;10;$1}} ``` Sample run: ``` bash-4.3$ gema '<D><s>=@int-char{@radix{2;10;$1}}' <<< '01010000 01010000 01000011 01000111' PPCG ``` ## Gema, 31 characters Using no delimiter in the input. ``` <D8>=@int-char{@radix{2;10;$1}} ``` Sample run: ``` bash-4.3$ gema '<D8>=@int-char{@radix{2;10;$1}}' <<< '01010000010100000100001101000111' PPCG ``` [Answer] ## Python 2, 49 bytes [Try it online](https://tio.run/nexus/python2#PYpBCoAwDAS/Erw0AZHUo@ArvHrRilipVWr/X9OKblgYMuv6MbnpmJcJhk6pZj@tR7MFtD6iqVui9QxgwHoYmvtyNiJRuoJocFixZpZqYC0RzsD5V0B/ij@V8d0UlZc/yFWUHg) ``` lambda S:''.join(chr(int(c,2))for c in S.split()) ``` [Answer] # Ruby, 36 characters ``` ->b{b.gsub(/\d+ ?/){$&.to_i(2).chr}} ``` Sample run: ``` irb(main):001:0> ->b{b.gsub(/\d+ ?/){$&.to_i(2).chr}}['01010000 01010000 01000011 01000111'] => "PPCG" ``` [Answer] ## PHP <5.3, 53 Bytes Idea by [@manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) ``` foreach(split(" ",$argv[1])as$v)echo chr(bindec($v)); ``` # PHP, 55 Bytes I prefer cause it can work without spaces ``` foreach(str_split($argv[1],9)as$v)echo chr(bindec($v)); ``` without spaces change `9` to `8` for 7 bits `7` ``` foreach(explode(" ",$argv[1])as$v)echo chr(bindec($v)); ``` ## PHP >=7, 62 Bytes ``` <?=join(($a=array_map)(chr,$a(bindec,explode(" ",$argv[1])))); ``` [Answer] # [C (clang)](http://clang.llvm.org/), 43 bytes ``` f(**v){*v&&f(v+!!putchar(strtol(*v,0,2)));} ``` [Try it online!](https://tio.run/##TY3BCgIhFEX3fsWbWQw@c0DbSl8SLURwGjCL0Wwh/novJwi6q8PlHq6bXbBxIfJciIJVlGnyvByG4fHM7mo3nvKW74GLIpU8IqJptMYMN7tGjlAZ9OxDAcWGdL7ACSqMSmvVo0f5Y63@eO8VNMO@ej/sKhrW6O18sEui@fUB "C (clang) – Try It Online") [Answer] ## Jelly, *unfinished* I still haven't figure out how to `repeat for every line in STDIN`, or get `amount of lines in STDIN` in Jelly. So far though, I came up for a solution for a single line/character. ``` ɠO_48ḄỌ ``` Any help is appreciated! ]
[Question] [ # Task Given positive integer `n`, output `a(n)` where `a` is the sequence defined below: `a(n)` is the smallest positive integer not yet appeared so that the sum of the first `n` elements in the sequence is divisible by `n`. # Example * `a(1)` is `1` because it is the smallest positive integer that has not appeared in the sequence, and `1` is divisible by `1`. * `a(10)` is `16` because look at the first nine elements: `1,3,2,6,8,4,11,5,14`. They sum up to `54`, so for the first ten elements to sum up to a multiple of `10`, `a(10)` would need to have a remainder of `6` when divided by `10`. `6` has already appeared, so `a(10)` is `16` instead. # Testcases ``` n a(n) 1 1 2 3 3 2 4 6 5 8 6 4 7 11 8 5 9 14 10 16 11 7 12 19 13 21 14 9 15 24 16 10 17 27 18 29 19 12 20 32 100 62 1000 1618 10000 16180 ``` * [`a(n)` from `n=1` to `n=10000`](http://oeis.org/A019444/b019444.txt) # References * [OEIS A019444](http://oeis.org/A019444) [Answer] ## Python 2, 43 bytes ``` r=.5+5**.5/2 lambda n:[n/r+1,n*r][n%r<1]//1 ``` Outputs floats. Uses the relation > > a(n) = [A002251](http://oeis.org/A002251)(n-1) + 1 > > > to Wythoff pairs. Takes from the upper or lower Beatty sequence by multiplying or dividing by the golden ratio and converting to an integer. [Answer] # [OCaml](https://ocaml.org/), 163 bytes ``` open List let a x=let rec h m s=let rec n m s c=if fold_left(+)c(s)mod m<>0||mem c s then n m s(c+1)else c in if m=x then hd s else h(m+1)((n(m+1)s 2)::s) in h 1[1] ``` [Online interpreter](https://try.ocamlpro.com/) ### Usage ``` >> open List >> let a x=let rec h m s=let rec n m s c=if fold_left(+)c(s)mod m<>0||mem c s then n m s(c+1)else c in if m=x then hd s else h(m+1)((n(m+1)s 2)::s)in h 1[1];; << val a : int -> int = <fun> >> a(100);; << int = 62 ``` where `>>` is STDIN and `<<` is STDOUT. [Answer] # Python 3, 102 bytes Definitely not the shortest solution (not familiar with code golf) but I was bored so here it is in Python. I'm sure you could make it smaller with lambdas/filter. ``` def a(n,s=[]): for j in range(1,n+1): i=1 while i in s or(sum(s)+i)%j:i+=1 s+=[i] return s[-1] ``` [Answer] # Pyth - ~~23~~ ~~21~~ 18 bytes Can probably streamline the generation process with more lambdas or other tricks, but this is my first answer in more than a month. ``` eem=+Yf!|}TY%+TsYh ``` [Try it online here](http://pyth.herokuapp.com/?code=eem%3D%2BYf%21%7C%7DTY%25%2BTsYh&input=10&debug=0). [Answer] # [Actually](http://github.com/Mego/Seriously), 17 bytes This uses [xnor's algorithm](https://codegolf.stackexchange.com/a/90202/47581). Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=LDs7z4YoL3Uoz4YqMc-GKCU8SeKJiA&input=MTA) ``` ,;;φ(/u(φ*1φ(%<I≈ ``` Here's a 31-byte version that uses the function definition, but with the oddity that, at first, the function returns the sequence `a(n)-1`, so the result needs to be incremented at the end. [Try it online!](http://actually.tryitonline.net/#code=W13ilZcsYDEiOyPilZwrO2xAzqMlQOKVnMOtK3VZIsKj4pWT4pWWYG7ilZxOdQ&input=MTA) ``` []╗,`1";#╜+;l@Σ%@╜í+uY"£╓╖`n╜Nu ``` **Ungolfing:** ``` First algorithm ,;; Take the input, duplicate it twice 1φ(%<I If input mod phi less than 1 (φ* then input * phi φ(/u else input / phi + 1 ≈ int() the result Second algorithm []╗ Push a list to register 0 (call this res from now on) , Take input `1 Start function, push 1 " Start string ; Duplicate i #╜+; res + list(i), duplicate l len(new list) @Σ sum(new list) % sum % len @╜í Rotate i to top, check if i in res +uY (sum%len) + (i in res) + 1, negate (1 if i fits conditions, else 0) "£ End string, turn into a function ╓ Push first (1) values where f(x) is truthy, starting with f(0) ╖` Append result to the list in register 0, end function n Run function (input) times ╜Nu Return res[-1]+1 ``` [Answer] # R, 99 bytes ``` f=function(n){a=n b=c() while(0<(a=a-1))b=c(f(a),b) while(a<-a+1)if(!(sum(b)+a)%%n&!a%in%b)break a} ``` Simple algorithm. Runs from `n-1` to `1` and gathers all of those numbers in the sequence. Then it moves up from 1 -- checking membership and whether it divides appropriately. [Answer] # Python 3, 96 bytes ``` n=int(input()) a=[] for L in range(1,n+1): t=L-sum(a)%L while t in a:t+=L a+=[t] print(a[-1]) ``` [Ideone it!](http://ideone.com/nTzTIh) [Answer] ## JavaScript (ES6), 69 bytes ``` n=>{for(a=[],s=i=0;i++<n;a[j]=1,s+=j)for(j=i-s%i;a[j];)j+=i;return j} ``` At each stage just checks all the numbers with the appropriate remainder until it finds one that it hasn't seen before, then marks it seen and updates the total. [Answer] # [Behaviour](https://github.com/FabricioLince/BehaviourExolang), 64 bytes ``` c=&[(~!a{})(l=c:a-1s=0\(~(l<=s+=1)~!(l+s>&a+b)%a)l+s)]f=&(!c)%-1 ``` Test with: ``` f:1 f:2 f:10 ``` Calculates the list recursively and doesn't even work for n > 300, but you know, there was an attempt. Ungolfed and commented: ``` // There are two functions, the first is recursive and creates the entire list createList = & [ (~!a; {}) // Base case, n==0 return empty list ( list = createList:a-1 // create the list for n-1 smallest = 0 // initialize the variable to find the smallest // Repeat the following Sequencer until success \( // Increments smallest and check if it is NOT on the list ~(list <= smallest+=1) // sum up the list with the smallest found sum = list+smallest > &a+b // is the sum divided by n remainder 0 ~!sum%a ) // returns the list with the smallest list + smallest ) ] // The second function just execute the first and return its last item f = &(!createList)%-1 ``` ]
[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/48883/edit). Closed 8 years ago. [Improve this question](/posts/48883/edit) First of all, this is more a challenge, than a serious programming question, I would like to share. Some of you might know the game Kuku kube, where you have to identify a square in a grid, which has a different colour than the others and click it. You can find it under <http://kuku-kube.com/> . As this seems to be an ideal exercise for our image processing students, I want to see, which way is the best to get the highest score. My code so far: ``` from pymouse import PyMouse import time b=time.time() m=PyMouse() start=(2912,895) tl=(2695,387) br=(3129,814) def click(): m.click(start[0],start[1]) time.sleep(0.1) while time.time()-b<60: for i in range(0,9): for l in range(0,9): m.click(2696+i*53.625,390+l*53.125) time.sleep(0.004) click() ``` gets me to about 370-ish. Is it possible to get more? Use image processing? High-score wins! [Answer] # Javascript (Cheating), Score = limitless? I realized that the game timer was using `setInterval`, which is a very unreliable way of keeping time. With that in mind, since js is single threaded, if we simply hog the thread, the timer can't update. As a result, you can essentially get any score you want. If you perform 1000 clicks in a single function call without releasing the thread, you guarantee a score of at least 60000 (in fact I did this and got 180000). This is obviously cheating because the game lasts longer than 60 seconds, though the game doesn't realize it. For this reason, **any js solution at all is really sort of cheating**. Though the time increase is minimal for code that completes quickly, you can still potentially delay the timer for as long as your code runs. ``` var factor = 1000; function findAndClick() { var array = document.getElementById("box").children; for(var j = 0; j < factor; j++){ var one = array[0].style.cssText; var two = array[1].style.cssText; var color; if(one != two){ color = array[2].style.cssText; } else { color = one; } for (var i=0; i < array.length; i++) { if (array[i].style.cssText != color) { array[i].click(); break; } } } } $(".play-btn").click(); setInterval(findAndClick, 0); ``` # Javascript (REALLY Cheating), Score = limitless? The game's object is actually global. As a result, you can tweak various properties to your advantage. The easiest of which is to just set your score to whatever you want it to be: ``` $(".play-btn").click(); Game.lv = 1000000; ``` [Answer] # Javascript, Score ≈ 10700 14400 (Chrome) On the home page, open your developer console (F12), copy/paste the following code and wait 60 seconds. jQuery slow down the execution, so I used the fantastic [Vanilla-JS](http://vanilla-js.com/) ``` function findAndClick() { var array = document.getElementById("box").children; var last = ""; for (var i=0; i < array.length; i++) { if (array[i].style.cssText != last) { array[i].click(); last = array[i].style.cssText; } } } $(".play-btn").click(); setInterval(findAndClick, 0); ``` [Answer] # Javascript/JQuery: 4489 I went the same route as Mig, but I think his is more efficient than mine, as my javascript skills are quite limited. ``` clickBox = function() { a = jQuery("#box span"); if (!a.is(":visible")) { clearInterval(clickBox); return; }; var colors = {}; a.each(function(i, o) { var style = jQuery(this).attr("style"); colors[style] = 1 + (colors[style] || 0) }); a.each(function() { if (colors[jQuery(this).attr("style")] == 1) { jQuery(this).click() } }); }; setInterval(clickBox, 0); ``` ]
[Question] [ I have to fill in 2fa codes all day. They're 6-digit strings. One day I noticed that not once did any of these codes contain 6 unique digits, like 198532 There was always at least one double, like 198539 (here it's 9). For any given uniformly random string of \$N\$ digits in the set \$\{0,1,2,3,4,5,6,7,8,9\}\$, what is the odds for this happening? Your input is a single positive integer, \$N\$, with \$N \le 10\$ Your output is a number between 0 and 1, which is the probability that a string with \$N\$ digits has at least one repetition. The shortest code wins [Answer] # [Haskell](https://www.haskell.org/), 30 bytes ``` f n=1-product[1,0.9..1.1-n/10] ``` [Try it online!](https://tio.run/##HcyxCsIwFEbhV/kpCC2YmDt0sFAnV8HBre0QNcFichNiCr59DC5nO99Lf97GubL6GFLGzXyzvKaVsy0WPJKIKTy3R55or@RRSpIk@EBqKV6vjBFexwvamSFOiP8Rza6XyqK2tzM3YLTVwjDgHLa7M12HSVWKlvID "Haskell – Try It Online") If we pick, for example, 4 digits sequentially, then the odds of each one being "fresh" is * \$10/10\$ for the first digit * \$9/10\$ for the second digit (it must ≠ the first digit) * \$8/10\$ for the third digit (it must ≠ the first and second digits) * \$7/10\$ for the fourth digit (it must ≠ the first, second and third digits) so the probability of getting 4 unique digits is \$\frac{10}{10}\cdot\frac{9}{10}\cdot\frac{8}{10}\cdot\frac{7}{10}\$, and the probability of *not* getting 4 unique digits (i.e. some repetition) is one minus that. In general the answer is $$1 - \prod\_{k=0}^{n-1} \frac{10-k}{10}.$$ (Though not required, this formula is also valid for \$N \geq 11\$, where the answer is \$1\$. In that case, this product contains a factor 0, representing the fact that we can't possibly pick an eleventh digit that is different from all ten digits that exist.) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 bytes Uses the same formula as Lynn's Haskell answer. -1 byte thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)! ``` Ḷ÷⁵CPC ``` [Try it online!](https://tio.run/##y0rNyan8///hjm2Htz9q3Ooc4Pzf0BDEa3/UtCbyPwA "Jelly – Try It Online") ``` Ḷ lowered range: [0, 1, ..., n-1] ÷⁵ divide each value by 10 [0/10, 1/10, ..., (n-1)/10] C complement, subtract each from 1 [10/10, 9/10, ..., (11-n)/10] P take the product of all values (10/10)*(9/10)* ... *(11-n)/10 C complement 1 - (10/10)*(9/10)* ... *(11-n)/10 ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 9 bytes ``` ₀~εrΠ?↵/⌐ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%82%80%7E%CE%B5r%CE%A0%3F%E2%86%B5%2F%E2%8C%90&inputs=9&header=&footer=) Me and the boys on our way to port Lynn's Haskell answer be like. ## Explained ``` ₀~εrΠ?↵/⌐ ₀~εr # the range (10 - input, 10] Π # the product of that / # divided by ?↵ # 10 ** input ⌐ # 1 - that ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` ÇnA /AÃ×n1 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=x25BIC9Bw9duMQ&input=OA) ``` ÇnA /AÃ×n1 :Implicit input of integer U Ç :Map the range [0,U] n : Subtract from A : 10 /A : Divide by 10 à :End map × :Reduce by multiplication n1 :Subtract from 1 ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 19 bytes ``` 1-10!/10^#/(10-#)!& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b731DX0EBR39AgTllfw9BAV1lTUe1/QFFmXkm0sq5dmoOyjpKCrYKSjp8DkB2rVhecnJhXF5SYl54abaBjaBD7HwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [J](http://jsoftware.com/), 13 bytes ``` 1-!*(!%^~)&10 ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DXUVtTQUVePqNNUMDf5rcqUmZ@QrpCkYwhhGMIYxjGECY1jCFRv8BwA "J – Try It Online") * 1 minus `1-` the factorial of the input `!` times `*`... * `(!%^~)&10` the input choose 10 divided by 10 raised to the input. Or, equivalenly: ``` 1-!*!&10%10&^ ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` Tses°/1α ``` [Try it online!](https://tio.run/##yy9OTMpM/W9o6OZnr6Sga6egZO/n9z@kOLX40AZ9w3Mb/@v8BwA "05AB1E – Try It Online") Uses a different formula from the Wikipedia page: $$ 1-{\_{365}P\_{n} \over 10^n} $$ ``` Ts # push 10 and swap implicit input n to the front e # number of permutations s° # 10 ** n / # divide: nPr(10, n) / 10 ** n 1α # absolute difference from 1 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~39~~ 38 bytes ``` f=lambda x:x and(x-1-f(x-1)*(x-11))/10 ``` [Try it online!](https://tio.run/##FcQxDoAgDADA3Vd0pEai1Y3Ex2Cw2kQLIQz4etQbLj3ljLq0xuvl7y14qK6C12CqJcv/2P8T4khT45hBQBSy12M3NKPr4JOyaDEysBHE9gI "Python 3 – Try It Online") * Thanks to @ovs for -1 [Answer] # [APL(Dyalog Unicode)](https://dyalog.com), ~~13~~ 12 bytes [SBCS](https://github.com/abrudz/SBCS) Implements the same formula as Lynn's Haskell answer. ``` 1-(×/1-.1×⍳) ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=M9TVODxd31BXz/Dw9Ee9mzUB&f=e9Q31dP/UdsEA65HvZ2P2iZWKGikHVqhUAEUetS72dBQEwA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f) And 15 bytes with \$1-{1\over 10^n} {10!\over (10-n)!}\$: ``` 10∘(1-*÷⍨⊣÷⍥!-) ``` [Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=MzR41DFDw1BX6/D2R70rHnUtBtFLFXU1AQ&f=e9Tb@ahtYoWCRtqhFQoVj9omHFpvqP2od7OhoSYA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes ``` I⁻¹ΠEN∕⁻χιχ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczr7RYw1BHIaAoP6U0GSiQWKDhmVdQWuJXmpuUWqShqaPgklmWmZIKU2qgo5AJFDQ00AQD6///zf7rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` N Input integer E Map over implicit range χ Predefined variable `10` ⁻ Subtract ι Current index ∕ Divided by χ Predefined variable `10` Π Take the product ⁻¹ Subtract from 1 I Cast to string Implicitly print ``` Alternative approach, also 11 bytes: ``` I⁻¹Π∕⁻χ…⁰Nχ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzczr7RYw1BHIaAoP6U0uUTDJbMsMyUVJm6goxCUmJeeqgFkeOYVlJb4leYmpRZpaGrqKBgaaIKA9f//Zv91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` …⁰N Range from 0 to input integer ⁻χ Vectorised subtract from 10 ∕ χ Vectorised divide by 10 I⁻¹Π Cast product subtracted from 1 to string ``` ]
[Question] [ **This question already has answers here**: [Determine whether strings are anagrams](/questions/1294/determine-whether-strings-are-anagrams) (162 answers) Closed 9 years ago. This is an easy one. [Anagrams](http://en.wikipedia.org/wiki/Anagram) are words which have the same characters but in different order. All you have to do is to figure out if two strings are anagram or not. Rules: * Take two strings as a function argument, command-line argument or from standard input. * Write a function or program which returns truthy value if strings are anagram, falsy value otherwise * Anagrams may have different number of spaces () characters in them. * Anagrams are case insensitive matches. * Anagrams can only have printable ASCII characters for this code-golf. For example(taken from the Wikipedia page itself): `Doctor Who` is an anagram of `Torchwood` . Note missing space and lack of capital D and W in `Torchwood` This is code-golf so minimum bytes code win! Happy golfing. [Answer] # Java, 146 131 144 134 131 128 Not a very exciting answer. Returns true for anagrams, false for others. Actually works now. Cheapass abuse of generics in class declaration. ``` boolean b(T a,T b){return c(a).equals(c(b));}T c(T a){char[]c=a.toLowerCase().toCharArray();sort(c);return(T)valueOf(c).trim();} ``` Ungolfed: ``` boolean b(T a,T b) { return c(a).equals(c(b)); } T c(T a) { char[] c = a.toLowerCase().toCharArray(); sort(c); return (T) valueOf(c).trim(); } ``` [Answer] ## CJam, ~~15~~ 11 bytes Just thought I'd practice CJam a bit more. This is basically the same as my Ruby answer (or most answers): ``` ea{S-el$}/= ``` Quick explanation ``` ea "Push command line arguments"; ea{ }/ "For each element in that array"; ea{S- }/ "Push a space character onto the stack and remove spaces from string"; ea{S-el }/ "Convert string to lower case"; ea{S-el$}/ "Sort the characters in the string"; ea{S-el$}/= "Check for equality"; ``` Prints `1` for anagrams and `0` otherwise. [Answer] # Rebol ~~44~~ 40 (Rebol 2) Define a function `m` which takes two values `a` and `b`. `Sort` each string, `trim` the whitespace and use `=` to check if the strings are the same. ``` m: func[a b][(trim sort a)= trim sort b] ``` ~~m: func[a b][equal? trim sort a trim sort b]~~ Example ``` >> m: func[a b][(trim sort a)= trim sort b] >> m "Doctor Who" "Torchwood" == true ``` It is useful handy that `sort` is case insensitive by default. Note: This function does have side effects if you use this code elsewhere as `sort` modifies a and b directly. (`sort` should work in Rebol 3 but doesn't as there is a known bug) [Answer] ## Ruby, ~~65~~ ~~60~~ ~~58~~ ~~57~~ ~~51~~ ~~48~~ 46 bytes ``` s,t=$*.map{|u|u.upcase.scan(/\S/).sort};p s==t ``` ~~**Edit:** Switched to STDIN to save a few bytes.~~ **Edit:** Switched to ARGV to save three more bytes. Quite long for such a simple problem, hmmmm. * For each string: + Turn to upper case (to make it case in-sensitive). + Split into non-whitespace characters. + Sort (by character code). * Then check that the results are equal. [Answer] # JavaScript (ES6) 68 ~~99~~ Generate a key for each word and compare them. If only JS had some shorter ucase method... ``` A=(a,b,k=s=>[...s.toUpperCase()].sort().join('').trim())=>k(a)==k(b) ``` [Answer] # Python 3 -- ~~73~~ 67 bytes --- Code: ``` f=lambda:sorted(i for i in input().upper()if" "!=i);print(f()==f()) ``` As usual, nice looking, but not very short. Typical python... [Answer] # Cobra - 130 ``` do(a='',b='') print (f=Func<of String,String>(do(s='')=s.toLower.toCharArray.toList.sorted.join('').trim)).invoke(a)==f.invoke(b) ``` [Answer] # JavaScript (ES6) 82 Returns true if the two strings are anagrams, otherwise returns false or throws an exception ``` e=(a,b)=>(a.replace(/\S/g,c=>b=b.replace(b.match(RegExp(c,'i'))[0],'')),!b.trim()) ``` [Answer] # Perl - 84 Always need Perl in these... ``` sub c{map{s/\s//}@a=@_;(join'',sort split//,lc$a[0])eq join'',sort split//,lc$a[1]} ``` Wanted to be able to modify @\_ directly but perl wont allow that [Answer] # Bash+coreutils, 62 bytes ``` s()(tr -d ' '<<<"${@^^}"|fold -1|sort) cmp <(s $1) <(s $2) ``` Takes arguments from the command line. Return code 0 for TRUE and 1 for FALSE. Also something like `/dev/fd/63 /dev/fd/62 differ: byte 1, line 1` is output in the FALSE case. ### Output: ``` $ ./anagram.sh "Doctor Who" Torchwood; echo $? 0 $ ./anagram.sh "Doctor Watson" Torchwood; echo $? /dev/fd/63 /dev/fd/62 differ: byte 1, line 1 1 $ ``` [Answer] ## Clojure : 84 chars Golfed: ``` (defn g[s](sort(remove #(= \ %)(seq(.toLowerCase s))))) (defn f[a b](=(g a)(g b))) ``` Ungolfed: ``` (defn g[s] (sort (remove #(= \ %) (seq (.toLowerCase s))))) (defn f[a b] (= (g a) (g b)) ) ``` Driver program with execution: ``` (def a "Doctor Who") (def b "Torch woo d") (println (f a b)) bash$ java -jar clojure-1.6.0.jar anagram.clj true ``` [Answer] ## Groovy : 96 77 chars Golfed: ``` g={it.findAll{it!=" "}.collect{it.toLowerCase()}.sort()} f={a,b->g(a)==g(b)} ``` Ungolfed: ``` g = { it.findAll{ it!=" " }.collect{ it.toLowerCase() }.sort() } f = { a,b -> g(a)==g(b) } ``` Example main program and execution: ``` a="Doctor Who x x" b="Tor chwoo dxx" println f(a,b) $ groovy Anagram.groovy $ true ``` ]
[Question] [ I have a source file here: ``` #include <FizzBuzz.h> fizzbuzz ``` And I want to make "`fizzbuzz`" turn into a FizzBuzz program solely through the preprocessor. Your task is to write a `FizzBuzz.h` that uses only preprocessor directives (things like include, define, etc.) to create a working FizzBuzz program. Specifically, I want to see the use of macros, which will be required to make this work (at minimum, defining `fizzbuzz` to be some code). However, to make sure people try and take full advantage of the power of macros, your score will be defined as the sum of the cubes of the length of the definition portion (the part after `#define <symbol>`) of each macro. So, for example, the following file: ``` #define A 123 #define B A+A #define C B*2+A ``` would have a total score of 179 (3^3 + 3^3 + 5^3). As a rule, I want multiple shorter lines instead of one long line. [Answer] ## C, Score 1,283 1,213 1,205 **EDIT**: Instead of basing on [Loki Astari's solution](https://codegolf.stackexchange.com/a/12297/3544), now I'm based on [breadbox's](https://codegolf.stackexchange.com/a/12331/3544) The basic code is not exactly the same as breadbox's - I replaced the loop with recursion, which is longer, but has more repetition. With GCC, it can be improved further, by using `?:` instead of `?0:`. ``` #define A "Fi" #define D "Bu" #define E "z" #define L E E #define F L,z #define R F) #define G A R #define H D R #define I "" #define K "%d" #define X printf #define Y puts #define Z main #define M 99 #define N z%5 #define O z%3 #define P Z(z #define Q P) #define a Q{X #define b a(O #define c b?N #define d c?K #define e d:I #define f e:G #define i f;Y #define j i(N #define k j?I #define l k:H #define n l;z #define o n++ #define p o>M #define q p?0 #define r q:Q #define s r; #define fizzbuzz s} ``` Macro-free code: ``` main(z){printf(z%3?z%5?"%d":"":"Fizz",z);puts(z%5?"":"Buzz",z);z++>99?0:main(z);} ``` The 2nd parameter to `puts` does nothing. It allows me to utilize the `zz",z)` sequence. [Answer] ### C score 1602 1592 1535 1515 1505 1451 ``` #include <stdio.h> #define A "%d" #define B "Bu" #define C "Fi" #define w "z" #define D w w #define E "\n" #define F main #define G printf #define I for #define J 99 #define L c++ #define O A E #define P O:B #define Q P D #define R Q E #define S c%3 #define T c%5 #define U S?T #define V U?R #define W V:T #define X W?C #define Y X D #define Z Y E #define a Z:C #define b a D #define d b B #define e d D #define f e E #define g f,c #define r (g) #define h G r #define i ;L #define j J;h #define k i<= #define l k j #define q (l) #define m I q #define n m; #define o {n} #define p F() #define s c;p #define fizzbuzz s o ``` Original source: ``` c;main(){for(;c++<=99;printf(c%3?c%5?"%d\n":"Buzz\n":c%5?"Fizz\n":"FizzBuzz\n",c));} ``` Now I am wondering if we change the code too: ``` c;main(){for(;c++<=99;printf(6*(c%3<1)+12*(c%5<1)+"%d \n\0Buzz\n\0Fizz\n\0FizzBuzz\n\0",c));} ``` It looks longer. But more compressable using macros. [Answer] ## C, score 1267 Best I could do: ``` #define a main #define b for #define c puts #define d printf #define e "" #define f x Z #define g y Z #define h "%d" #define x "Bu" #define y "Fi" #define z "z" #define Z z z #define A 101 #define B i++ #define C B%5 #define D C?e #define E D:f #define F i%3 #define G F?i #define H G%5 #define I H?h #define J I:e #define K J:g #define L K,i #define M i<A #define N M;c #define O a(i #define P N(E #define Q d(L #define R O) #define S b( #define T P) #define U Q) #define V U; #define W R{S #define X W;T #define Y X)V #define fizzbuzz Y} ``` This is roughly the same approach that the other entries are using, looks like. I suspect the marginal improvement comes from the brevity of the target program. At 75 bytes, it's the shortest C fizzbuzz I know (that doesn't depend on compiler-specific behavior): ``` main(i){for(;i<101;puts(i++%5?"":"Buzz"))printf(i%3?i%5?"%d":"":"Fizz",i);} ``` [Answer] ## C, Score 28,703 18,043 4,367 ``` #define S(x) #x"\n" // 6 #define X(a) W?Y(a) // 6 #define W c%5 // 3 #define Y(a) S(a):Z(a) // 9 #define Z(a) S(a##Buzz) // 10 #define fizzbuzz A%Q} // 4 #define A char*B // 6 #define B p,C // 3 #define C c;D(E // 5 #define D main // 4 #define E ){F // 3 #define F for(G // 5 #define G ;c++H // 5 #define H <=I(K // 5 #define I 99;J // 4 #define J printf // 6 #define K *p+L // 4 #define L ~9?M // 4 #define M p:N,O // 5 #define N S(%d) // 5 #define O c))P // 4 #define P p=c // 3 #define Q 3?R; // 4 #define R X():T // 5 #define T X(Fizz) // 7 ``` Original macro-free program: ``` c,*p; main(){ for(;c++<=99;printf(*p+~9?p:"%d\n",c)) p=c%3?c%5?"\n":"Buzz\n":c%5?"Fizz\n":"FizzBuzz\n"; } ``` [Answer] ## C++, Score 68,508 I know this does not meet the criteria (lots of really short macro definitions), but I think it has an advantage over the other answers. First the solution: ``` #include <iostream> #define X(a) H(a,N)H(1,L) #define W(a,b,c) H(U(a,b),c)H(a,M) #define V J:: #define U(a,b) !(a)&&!(b) #define T ==0 #define S K<< #define R %5 T #define Q main #define P int #define O %3 T #define N "Buzz" #define M "Fizz" #define L V endl #define K V cout #define J std #define I if #define H(a,b) I(a)S(b); #define G(a,b,c) W(a,b,c)X(b) #define F(a) G((a)O,(a)R,a) #define E(a,b,c,d) F(a*20+b*4+c*2+d+1) #define D(a,b,c) E(a,b,c,0)E(a,b,c,1) #define C(a,b) D(a,b,0)D(a,b,1) #define B(a) C(a,0)C(a,1)C(a,2)C(a,3)C(a,4) #define A B(0)B(1)B(2)B(3)B(4) #define fizzbuzz P Q(){A} ``` Second, I think the advantage to this is that it truly uses the preprocessor to its "best" advantage. Namely, it does not use any looping constructs or variables in determining FizzBuzz. All parameters are constants, thus all the expressions can be compile time evaluated. Any if-condition that is false can be optimized away, so the final optimized form of the compiled program is really just a bunch of statements like `cout << something; cout << endl`. [Answer] ## C++, Score 24,806 (Revised from Earlier Answer) I came across code I posted last September and decided to refine it. I was able to cut it down significantly (for a savings of 43,702 "points") while keeping in the spirit of my original submission (no variables, just pre-processed constants). Not that anyone *cares*, but hey, I was bored. :) ``` #include <iostream> #define _ {A} #define a () #define b main #define c int #define d a _ #define e c b #define f "u" #define g "B" #define h "i" #define i "F" #define j "z" #define k w v #define l endl #define m << #define n cout #define o :: #define p std #define q g f #define r i h #define s j j #define t N)O #define u l; #define v n m #define w p o #define y q s #define z r s #define Z(a,b) M(a)k b; #define Y 0; #define X return #define W 100 #define V %5 #define U %3 #define T ==0 #define S w v w u #define R(a) Z(a,y) #define Q(a) Z(a,z) #define P(a,b,c) Z(!(a)&&!(b),c) #define O X Y #define N >W #define M if #define L V T #define K U T #define J(a,b,c) P(a,b,c)Q(a)R(b)S #define I(a) M(a t #define H(a) I(a)J((a)K,(a)L,a) #define G(a) H(a+1)H(a+2) #define F(a) G(a)G(a+2) #define E(a) F(a)F(a+4) #define D(a) E(a)E(a+8) #define C(a) D(a)D(a+16) #define B(a) C(a)C(a+32) #define A B(0)B(64) #define fizzbuzz e d ``` ]
[Question] [ **This question already has answers here**: [What's the day today (or other dates)?](/questions/2878/whats-the-day-today-or-other-dates) (7 answers) Closed 7 years ago. Please write a program that takes as input two numbers 'day of the month' and 'month number' for any day of this year (2012) and outputs day of the week. Examples: ``` % ruby ./golf.rb 14 07 # 14th of July "Sat" % ruby ./golf.rb 14 7 # the same "Sat" % ruby ./golf.rb 01 12 # Dec 1 "Sat" % ruby ./golf.rb 31 12 # Last day of the year "Mon" ``` * Output format should be like `Mon, Tue, Wed, Thu, Fri, Sat, Sun`, not less than 3 letters * Do not use date libs/modules, just math and logic * Wins the shortest script in any language. [Answer] ## GolfScript (46 44 chars) ``` ~.5*1$8>+2/\3<++7%"WedThuFriSatSunMonTue"3/= ``` Calculation can be more efficient than lookup if the days are rotated. I doubt that the mapping to day names can get shorter, but it may still be possible to shave a character or two off the hash function. However, my best idea for how to do it, finding a power which starts with a suitable string, doesn't look like a contender. After about 9 CPU-days of brute forcing I found a couple of solutions, but they're also 44 chars. The faster one is ``` ~16795 33303?`=+7%"WedThuFriSatSunMonTue"3/= ``` [Answer] # C++ (142) (135) (129 chars) ``` main(){string s[]={"Mon","Tue","Wen","Thu","Fri","Sat","Sun"};int d,m,t[]={0,5,1,1,4,6,2,4,0,3,5,1,3};cin>>d>>m;cout<<s[(d+t[m]+15-(m<3))%7];} ``` The requirement that the letters Mon, Tue etc. appear made it quite bad, otherwise it would be only **84 chars**. I'll search a golf for the strings... Hm, trying to golf the string only made it 2 chars longer, but I find it more aesthetically pleasing. ``` main(){char s[]={"MonTueWenThuFriSatSun"};int d,m,t[]={0,5,1,1,4,6,2,4,0,3,5,1,3};cin>>d>>m;d=((d+t[m]+15-(m<3))%7)*3;s[d+3]=0;printf("%s",s+d);} ``` Well, this for my first entry at a golf contest, I have still much to learn... HA! Got it! ``` main(){char s[]={"MonTueWenThuFriSatSun"},t[]={"0511462403513"};int d,m;cin>>d>>m;d=((d+t[m]-33-(m<3))%7)*3;s[d+3]=0;printf("%s",s+d);} ``` with a well set compiler and some luck we might chop another 3 characters, by using char\* instead of char[], but it will crash on most systems. Anyway, it doesn't matter, as I believe soon someone will post a solution in J or K with less than 10 characters, as usual :P I'll never give up! ``` main(){char s[]={"MonTueWenThuFriSatSun0511462403513"};int d,m;cin>>d>>m;d=((d+s[m+21]-33-(m<3))%7)*3;s[d+3]=0;printf("%s",s+d);} ``` [Answer] # c, 101 chars ``` d,m;main(){scanf("%d %d",&d,&m);printf("%.3s\n","SunMonTueWedThuFriSat"+(d+".034025036146"[m])%7*3);} ``` [Answer] ## APL (~~57~~ 56) ``` D M←⎕⋄3↑'MonTueWedThuFriSatSun'↓⍨3×7|D+⍎M⌷'512503514624' ``` [Answer] ### Ruby, 75 74 Ok, my ruby: ``` a,b=$*.map &:to_i;p:MonTueWedThuFriSatSun[(a-:x365274263153[b].to_i)%7*3,3] ``` Saved one char: ``` a,b=$*;p:MonTueWedThuFriSatSun[(a.to_i-:x365274263153[b.to_i].to_i)%7*3,3] ``` [Answer] ## Python3 ~~(93)~~ (86) ``` print("MTWTFSSouehraunenuitn"[eval('%s+%s+14'%(input(),"0512573514624"[int(input())]))%7::7]) ``` Thanks to `vsz`. That is just his idea translated to python (plus comments, plus python-tricks). ``` print("MTWTFSSouehraunenuitn"[(int(input())+int("0512573514624"[int(input())]))%7::7]) ``` [Answer] # Pip, 44 **Not a competing entry, language is newer than question.** ``` ("SunMonTueWedThuFriSat"<>3a+562361462503@b) ``` [Pip](https://github.com/dloscutoff/pip) is my imperative code-golf language. The code above requires today's version of the interpreter (`0.15.04.23` or newer) for the `<>` operator. Command-line arguments are stored into `a` and `b` automatically. The program uses a simple lookup-table approach; taking advantage of the fact that numbers and strings are the same data type in Pip, we can define the table via integer literal, get a digit out by subscripting, and again do math with the result. As in CJam, subscripts are cyclic; so when `b` is 12, `562361462503@b` gives `5`. `<>` is the grouping operator: `"Hello"<>2` gives the list `["He";"ll";"o"]`, for instance. We then use the `( )` alternate subscripting syntax (again taking advantage of cyclic subscripts to avoid needing `%7`) to grab the appropriate day name, which is auto-printed. (The main use of the `(x y z)` syntax--borrowed from Lisp--is to call a function `x` with args `y` and `z`; but if `x` is a list or string, the operation is subscripting instead. The typical subscript operator, `@`, is very high-precedence, so when the subscript or list are compound expressions like here, the function-call syntax saves on extra parentheses that `@` would require.) [Answer] ## C, 96 chars Reads from standard input. Usage: `echo 23 7 | ./a.out` ``` main(a,b){ scanf("%d%d",&a,&b); a+=b*30.56-(b>2); puts("Thu\0Fri\0Sat\0Sun\0Mon\0Tue\0Wed"+a%7*4); } ``` The formula `b*30.56`, rounded down, gives the accumulated number of days before each month, assuming a 30-day February. `-(b>2)` corrects for 2012's 29-day February. [Answer] Python (130 chars) ``` d=raw_input().split() n=int(d[0])+sum([31,29,31,30,31,30,31,31,30,31,30,31][:int(d[1])-1])-1 print 'SMTWTFSuouehranneduit'[n%7::7] ``` It's rather longish for Python, but I like it. [Answer] # Factor 98 ``` : day ( x x -- x ) { 0 3 6 5 2 7 4 2 6 3 1 5 3 } nth - 7 mod "MonTueWedThuFriSatSun" 3 group nth ; ``` Output: ``` ( scratchpad ) 23 7 day --- Data stack: "Mon" ``` ]
[Question] [ This is an [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") post, so in this challenge every answer (except the first answer) depends on the previous answer. The goal of this challenge is to output the restricted characters. The restricted characters are the most common `n - 1` characters of **all answers**, if happens to be a tie, then the characters with the lowest UTF-8 range is restricted. The max bytes for every answer is: \begin{align}2n+60\end{align} where `n` is answer number. ## Rules * The answers only output the restricted characters, no newlines, no other characters like that. + The code may output the restricted characters exactly once, in any order. * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. * No answerer may answer twice in a row. * No languages may be reused in the last 5 answers. * Every answer takes empty or no input, and outputs to STDOUT. * The wrong answers (that break rules or don't do that this challenge say) are completely ignored if this answer is 10 minutes old, and should be deleted. The last answer after 5 days of the challenge not getting answers wins. ## Example First answer ``` # 1: Python 3, 13 bytes print(end="") Next charset: `"` [link]() ``` The second answer should output `"`. If the second answer's code is `ppaaa`, then the third answer should output either `pa` or `ap` (because these are the most common characters in all answers), and doesn't use these characters. Note: The scoring formula is based on the byte count and the answer number. The goal is to output the restricted characters efficiently while adhering to the specified byte limits. Have a great day! ### Clarifications * The banned character set is the N most common characters of the concatenation of all answers. [Answer] # 4: Uiua, 10 bytes ``` &pf-1$ ,=? ``` [Uiuapad](https://www.uiua.org/pad?src=0_2_0__JnBmLTEkICw9Pwo=) New banned characters: +-<> [Answer] # 9: [Brachylog](https://github.com/JCumin/Brachylog), 43 bytes (37 characters) ``` [32,43,9,92,114,99,101,10]~ạw ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P9rYSMfEWMdSx9JIx9DQRMfSUsfQwBCIY@se7lpY/v8/AA "Brachylog – Try It Online") Prints `<space>+<tab>\rce<newline>`. Next set: [`<space>+<tab><newline>1\r,c`](https://tio.run/##jVNtjtowEP2NTzFiVyURISJ8rVgt9EerHmDb/togZJLJYm2wU9spIETP0Cv0Gj1A79GTUNvhsxLbmuCMx@M3b148xVrPBe/udmxRCKlBrRXJpFhAIvIcE80EV7DfeydKrlEScgMfSu72QAsTadyQzKmkidkGkSSllMgTVLBkeg6a4UwifTF7s7UJlJ4PjIPErygVgpCpAU0xq5CmRyQ13Yd4Glfavydgxk1F4yKLyABpMj9xcJF2Na3IjQ7cKyS3vUf7aCs7pXQM3Zm/GQLlKeg5chvymbNEpAhuKgSr4hNqgzOgtmSHrww6pq4kZVhUS@/ELGQaF8rzA3jB9Sini1lKwfruwWvZ91M0CWx@zy3aE9@/YP@eqSKn6zP1Hexe@EyUElRBrUZUW/Iww2fGOePPR9FyxiuumZAOJzgJcE6/kt8Olrk4GI2gAY2T345CGi28rG7tB5d6DC3YOMRt3T/GYn6OEuvXYDSd/RcIfw2E49JW@g@g0OhpT9FZjp5/HW5jg7dXsBReHryBRywkKjSilvyIf37rSmU/CaqEFggKv5TuYl9NH8erjb0UFsG/b3dWl1SIzUhT8wWLUoNrZ6VTxolzTG0P2Mu4VqFzh6Y5U88nV9vvdMzf7ZZzZrh/kqWpsub6@tf3QgpD18GJUodLaW6rV4/73bjfj@968d2g7r8pslZ0C8HobfM4nlrj02LcfHiYjJuhdVqj2Qxv65uqxl53u7cGnYMVtaOD2RscrGFnaxWq1WpmIs6yC2INN7nOqbmnMgnZG@5HalAdJEAIrjCpF3E06BjpG3GvHWtXUzvuR9bbqD91O0GvGwyDYSeIol4wHAaGlvlPvv3@@WP5Bw "Python 3 – Try It Online") [Answer] # 3: [brainfuck](https://github.com/TryItOnline/brainfuck), 42 bytes ``` ++++++++++[->++++++++++>+<<]>+.[->+<]>+++. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fGw6ide0QHDttG5tYO209kCCIoa2t9/8/AA "brainfuck – Try It Online") Outputs `er`. Can't fit in js [Answer] # 6: [C# (Shell)](http://www.mono-project.com/docs/tools+libraries/tools/repl/), 54 bytes ``` $"{(char)43}{(char)62}{(char)101}{(char)46}{(char)92}" ``` Prints `+>e.\`. Has to be in a shell rather than standalone, since there's no way to output in C# without `e` otherwise. Next set is `+r()ac` ([link](https://tio.run/##jVNdjtowEH5uTjGCVTcREPG3rIqAPrTqAbbt0wYhk0wWa4Od2k4hQtyhp@q1qMcBApXY1g8wnvn8zTeTmbw0KykGhwNf51IZ0KX2UiXXEMssw9hwKTQcY59kIQwqz2vCl0K4GBhpkdYN8YopFtswyDgulEIRo4YNNyswHJcK2auNLUsLVH4AXIDCn6g0glSJJU0wrZgWZya9OEJ8g1sTjD2wp1nJuMoiU0AWr2oNDkm3RSVuetJeMbnwke0rVVandArdm78VAhMJmBUKgnwXPJYJgvvJJa/wMSNwCoxKdvzasmPiStJWRXX1a2UhN7jWftCGVyynGVsvEwbkG4Pfof/n3rxN@X136c6D4Er9Z67zjJUX3Xe0x8anslCgc0Y9YobEwxJfuBBcvJyblnFRaU2lcjztugGX8qv20@Gpw8F0CvdwX/vp5Mr2wk8bZE9c6hl0YOcY943gjMXskiUyb9EYtvwvEvEWicANVfoPotD2k16xZYZ@cJtuR@D9DS6N1w@b8IS5Qo22qYU4819OXaHpk6COWY6g8UfhBvtm@ija7mgoiCEYd/vbaykeZWSJ/YJ5YcCtszYJF55zLGgHaBhLHTp3aJcz8QPv5vrVz4LDYbPiVvs3Vdgq37m9/v0rV9LKdXSyMOFG2Wn1G9HDIHp4iB6H0eOoEbzP007vDtrTj63zee7M6susNZnMZ62QnGS0WuFdY1fVOBzsj9aof7J63d7JHI5O1of@vvEH "Python 3 – Try It Online")) [Try it online!](https://dotnetfiddle.net/a0L3An "C# (Mono C# Shell) – Try It Online") [Answer] # 1: [Python 3](https://docs.python.org/3/), 18 bytes ``` while True: break ``` [Try it online!](https://tio.run/##K6gsycjPM/7/vzwjMydVIaSoNNWKizOpKDUx@/9/AA "Python 3 – Try It Online") ``` e - 3 (Now banned) r - 2 <tab> - 1 <newline> - 1 <space> - 1 : - 1 T - 1 a - 1 b - 1 h - 1 i - 1 k - 1 l - 1 u - 1 w - 1 ``` This [code I stolen from ChatGPT](https://tio.run/##jVNNb9swDD3Pv4JoDrWANOi2W9DssmE/YN1OSxHIMl0LdSRNH02MoL89E@k0Tgqkmw62RT49Pj6Lro@tNZ/3e7121kcIfSgab9egbNehitqaAIfcV5tMRF8UE/ieDOcg2ozMYVCt9FLlNFilkvdoFAbY6NhC1Fh5lE85V/UZ6EsB2oDHZ/QBwfo6k9bYDEyrI1NYHSBlxG0U8wLymgwyzqrYBlCqdtTASNqtBnGLV@0DE6cPbPfU2ViSFfKZtwpBmhpii4Ygv4xWtkbgh7N6wCtJ4AYktcz8IbNjzS2FrGLYlqOymY64DqWYwhP2i06uq1oCxeZQ3tD798eHKdUveXP7IMSZ@m86uE72J@4z7cH4xiYPwUnySEYSDxU@amO0eTya1mkzaG2sZ57paMCp/MF@WrphHCwWcA3XY5yW89mLsrmi7zsu/QVuYMeML1fiiMXulGUZ36OJsvovEvMeicENdfoPoln2k07JqsNSXKbbEfjlAlfA84MT@IHOY8BsajJH/tNblwL9EgxKOoSAfxJf7Ivll8vtji4FMYj57aftuZSCKso6/0GXIvA4h1hrU3BgRTNAl7EPMw7P8nDWpSgujt94TOz3m1Zn7T99yl1@4Ln@Cw "Python 3 – Try It Online") makes easier to make the character list, but you have to combine answers manually. [Answer] # 2: [Keg](https://github.com/JonoCode9374/Keg), 2 bytes ``` Ɛ ``` [Try it online!](https://tio.run/##y05N////2IT//wE "Keg – Try It Online") Simply prints the letter `e` and exits. [Answer] # 7: [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 73 bytes The byte-count is 1 below the limit of \$2\times7+60\$. :) ``` [S S S T T T S S T N _Push_57_c][S S S T T S T T T N _Push_55_a][S S T T N _Push_-1_)][S S T T S N _Push_-2_(][S S S T S S T S S S N _Push_72_r][S S S T N _Push_1_+][N S S N _Create_Label_LOOP][S S S T S T S T S N _Push_42][T S S S _Add_top_two][T N S S _Print_as_char][N S N N _Jump_to_Label_LOOP] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [**Try it online**](https://tio.run/##K8/ILEktLkhMTv3/X0FBgZOTE0hwgVkgDheIASYUwIJgBGFycUEZYMjFqQDRyKXAxfX/PwA) (with raw spaces, tabs and new-lines only). **Explanation in pseudo-code:** ``` Push the codepoint-integers minus 42 of string "ca)(r+" Start LOOP: Add 42 to the top integer Print it as character to STDOUT Go to next iteration of LOOP ``` The constant `42` is generated [by this Java program](https://tio.run/##fVLda9swEH/vX3HoSUKpyWB7qB1RWujAsHRQp9uglCG7aqJOkT3pHAgjf7sr1x9xttEXSdzd70N39yJ38vzl6VfTFEZ6D0up7Z8zgKrOjS7Ao8Rw7Ur9BNuQohk6bdcPjyBZWwbQBcApXxsEAfJh/pi8ZbRF8FtpjPJtIrWo1spFy6sfP79dfbm/mUEqLpIpyVB9N5AR0uW/3q9u7uLn0tGWVIs00YsPn@aJ5ry3cTQiCJnhrBIDFqDF5XtUkMedzWit8DoEPGUjPPh9BpoLoRkUpUVta9XpJmMFiiC/Kr9vdMBWslDX2kq375Rpfq5ZMmGjGKnftTSeVlMZCBZd5FRlAsFn7TzSalZxkt1mZII/gDJewSkOuZtUjK9K4BAegkHeRUbZNW4og8XY2omRf7o94Z7M7UhzTKchrk8luzPbe1TbqKwxqkJT0FhKOrggfCDlJAkzJDzlBGIg/L2mpqyX/ZuZntp/qzqchaNf2X4d3uNud8n2DdlJF8ZLsoxwaoWYXxIS20W4ViQm42CGDSziYZuxPKFss2wpcRPJ3FPL2P9WDbkoFh8vLgNvHPiTSf@cwtrZUEFuSfejQ9M03FEmi1c), based on [this Whitespace tip of mine](https://codegolf.stackexchange.com/a/158232/52210). --- The next set is [`<space>+<tab><newline>r()`](https://tio.run/##jVNdjtowEH7GpxjBqpsIiJafZVW00IdWPUB/njYImWSyWBvs1HbKIsQdeqpei3ocIFCJbZ3ImRnPfPPNxFNs7FLJwX4vVoXSFszGsEyrFSQqzzGxQkkDh7OPqpQWNWMt@FxKfwZWOU9nhmTJNU/cMagkKbVGmaCBtbBLsAIXGvmLO1tsnKMOQhASNP5EbRCUTh1oilmFND8hmfnBJbD4asMxA7daFY2LLCoD5Mmy5uA9SZtX5CZH7hWSPz6gfaXK6pSeoY/5myFwmYJdoiSX71IkKkXwW6FE5Z9wcs6AU8ke3zh0TH1JxrGo1KBmFgmLKxOEHXjBzSTnq0XKgWxjCLr0ferNOpQ/8MrdLAwv2H8Spsj55qz7HvbQ@EyVGkzBqUfcEnlY4LOQUsjnU9NyISuumdIep1M34Jx@1X5aIvN@MJnALdzWdlqFdr0IsibJjz71FLqw9Yi7ZnjyxfwcJbZvwVi@@C8Q@RaIxDVV@g@gyPWTovgixyC8Drcl590VLIOXgS34goVGg66ppTzhn9@60tAvQZPwAsHgj9Jf7Kvp4/h1S5eCEMLxXf/1kgqjjDx1f7AoLfhxNjYVknnDnGaALuPGRN4cueFMg5BdHb86LNzv10vhuH/Tpauy4ef6969CK0fXw6nSRmvtbmvQjO8H8f19/DCMH0bN8F2RdXs30Jl8aJ/WU3daK9P24@Ns2o7ISEK7Hd00t1WNw8HuII36R6l31zuKw9FRet/fUYcajYbbmJdIYST4zU9Ow7@VyNhB8A9rQBXIgLE/). [Answer] # 8: Python 2, 34 bytes ``` exec"p\162int'\40\t\53\50\51\162'" ``` Prints `<space><tab>+()r<newline>`. Next set: [`<space>+<tab><newline>\rce`](https://tio.run/##jVPbjtowEH3GXzHKrkoiLgIWWHW10IdW/YBenjYrZJLJYm2wU9spIMQ/9Kv6W9TjAIFKbOtEzng8PnPmxFNs7ELJu/1eLAulLZiNYZlWS0hUnmNihZIGDnsfVSktasZu4HMp/R5Y5SKdG5IF1zxx26CSpNQaZYIGVsIuwAqca@Svbm@@cYE6jEBI0PgTtUFQOnWgKWYV0uyEZGaHkNDi2kYPDNy4qWhcZFEZIE8WNQcfSatZRW5y5F4h@e0D2leqrE7pGfozfzMELlOwC5QU8l2KRKUIfiqUqOITTsEZcCrZ4xuHjqkvyTgW1TKsmXWFxaUJoza84maS8@U85UC@Bwg79H3qP7cpf@gXvecoumD/SZgi55sz9T3sQfhMlRpMwUkjbok8zPFFSCnky0m0XMiKa6a0x2nXApzTr@SnITIfB5MJNKFZ@2kU2mkRZgHZjz71FDqw9Yi7IDrFYn6OEtu3YCyf/xeIfAtE4ooq/QdQ1@lJp/g8xzC6Drel4N0VLIOXB2/gCxYaDTpRS3nCP791paFfgibhBYLBH6W/2FfTx/F6S5eCEKKH3mB9SYVRRp66P1iUFnw7G5sKybxjRj1Al3Fjut7ddc2ZhhG72n71sWi/Xy2E4/5Nl67Khu/r378KrRxdD6dK211pd1vDIB7dxaNRfD@M78dB9K7IOv1baE8@tE7jqTOtF9PW4@PztNUlJxmtVvc22FY1Du92B2s8OFr9Xv9oDsdH6/1gRwo1Gg03MW/RgpHhJ985Df9WJmMHwz@sAdVBBozhGpOgiPvjgZO@GQ97sfU19eJRn7zN4A8) [Answer] # 5: [JavaScript (Node.js)](https://nodejs.org), 36 bytes ``` process.stdout.write("\53\55\74\76") ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWN1UKivKTU4uL9YpLUvJLS_TKizJLUjWUYkyNY0xNY8xNYszNlDQhaqFaYFoB) This prints `+-<>`. I previously had a more interesting GolfScript solution here, but I realized that it contained a `+` which made it invalid. Next charset is `+>e.\` ([link](https://tio.run/##jZNdbtswDMef51MQybDacGK067ICQZI9bNgB9vFUB4Es07VQR/IkeYkR9A491a6ViXIWJwPSTQ@2RVE//kmTdWtLJW/3e7GulbZgWhMUWq2Bq6pCboWSBg5nH1UjLeogGMLnRvozsMp5OjPwkmnG3TEozhutUXI0sBG2BCsw08ge3VnWOkcdRiAkaPyJ2iAonTtojkVHWh1JZnVwCS1ubTQNwK1hJ@MsiioAGS97Dd6TdqtO3PyP9o7kjw@0r5RZH9Ir9Hf@VghM5mBLlOTyXQqucgT/qJXo/Dkj5wIYpez5xtEx9ykZp6Lbhr2yRFhcmzAawSO284qts5wB2aYQjul9f7McUfzQb66XUXSm/pMwdcXak@p77KHwhWo0mJpRjZgl8ZDhg5BSyIdj0SohO62F0p4z6gtwKr8rPy1ReD@Yz@EKrno7rVq7WoTFgL5nPvQCxrDzxKdBdPTF6pSS2pcwlmX/BZEvQSRuKNN/gBJXT7rFsgrD6DJuR85PF1gGzy8O4QvWGg26ojbyyD/tusbQL0HDWY1g8EfjG/ti@DTd7qgpiBBNr99uz6UEFJHl7g/WjQU/zsbmQgbesKIZoGZsTeLNiRvOPIyCi@PXX4v2@00pnPZvunFZvvJz/eu51srJ9TjV2GSjXbeGg3Rym04m6d279O79IHpTF@Ob1zCaf4iP63686DeLeDZbLuKEjPQRx8lv "Python 3 – Try It Online")) ]
[Question] [ # Input An array A of integers of length 100,000. The array will contain only integers in the range 0 to 1e7. # Output The convolution of A with itself. As this will be of length 199999 you should time just the convolution calculation however, not the time to print out the answer. # Example in Python ``` import numpy as np from scipy.signal import convolve A = np.array([0]+ [1e7]*99999) B = convolve(A,A, method="direct") ``` If I run this code the convolution line takes about 0.74s. It is over 4s if use a list instead of a numpy array. # Precision If I use the numpy FFT method with: ``` convolve(A,A,method="fft") ``` it is very fast but I get the wrong answer due to precision problems. # Task Write code to perform convolution that gives the correct output for all inputs in the specified range. Your score will be the factor by which your code is faster than the above code on my computer. # Computer I will run your code on Ubuntu on a AMD Ryzen 5 3400G. # Possible speed ups Apart from clever coding tricks and parallelization, the following may (or may not) be useful. * [Karatsuba's](https://www.google.com/url?sa=t&source=web&rct=j&opi=89978449&url=https://medium.com/analytics-vidhya/what-is-karatsuba-approach-for-efficient-polynomial-multiplication-e033032f2309&ved=2ahUKEwjR-qP4lsaAAxWcxQIHHW0lBbAQFnoECA4QAQ&usg=AOvVaw2CpYyMDg3s4R2YeYfcORO9) method for polynomial multiplication. * [Toom Cook multiplication](https://en.m.wikipedia.org/wiki/Toom%E2%80%93Cook_multiplication#:%7E:text=The%20Toom%E2%80%93Cook%20approach%20to,(%C2%B7)%20at%20various%20points.) * [The number theoretic transform](https://math.stackexchange.com/questions/4642152/using-ntt-number-theoretic-transform-to-multiply-two-polynomials) # Edit Largest value reduced to 1e7 so that only 64 bit unsigned ints are needed. # Table of leaders per language * Score **0.49**. Takes 1.52s in **Python** by **l4m2** * Score **36**. Takes 0.02s in **C++** by **dingledooper** * Score **5.3**. Takes 0.14s in **Rust** by **Bubbler** * Score **50.3**. Takes 0.015s in **Rust** by **Bubbler** . This is running `ntt_par`. [Answer] # [C++ (gcc)](https://gcc.gnu.org/), ~0.01s ``` #include <algorithm> #include <cmath> #include <cstdint> #include <cstdio> #include <ctime> #include <immintrin.h> struct C { double x, y; C() : x(0), y(0) {} C(double x, double y) : x(x), y(y) {} inline C operator+ (const C &c) const { return C(x + c.x, y + c.y); } inline C operator- (const C &c) const { return C(x - c.x, y - c.y); } inline C operator* (const C &c) const { return C(x * c.x - y * c.y, x * c.y + y * c.x); } inline C conj() const { return C(x, -y); } }; constexpr double PI = acos(-1); constexpr int SIZE = 100000, B = 32 - __builtin_clz(SIZE * 2 - 1), N = 1 << B; alignas(32) C w[N >> 2], f0[N], f1[N]; void init_roots() { w[0] = C(1, 0); for (int len = 1; len < (N >> 2); len <<= 1) { C wn(cos(PI / (len << 2)), sin(PI / (len << 2))); for (int i = len; i < len << 1; i++) w[i] = w[i - len] * wn; } } __m256d avx_complex_mul(__m256d a, __m256d b) { __m256d ax = _mm256_unpacklo_pd(a, a); __m256d ay = _mm256_unpackhi_pd(a, a); __m256d bs = _mm256_shuffle_pd(b, b, 5); return _mm256_fmaddsub_pd(ax, b, _mm256_mul_pd(ay, bs)); } void fft(C *f) { for (int len = N >> 2; len > 1; len >>= 2) { for (int i = 0, m = 0; i < N; i += len << 2, m++) { double w1x = w[m].x, w1y = w[m].y; double w2x = w1x * w1x - w1y * w1y, w2y = 2 * w1x * w1y; double w3x = w1x * w2x - w1y * w2y, w3y = w1x * w2y + w1y * w2x; __m256d w1 = _mm256_setr_pd(w1x, w1y, w1x, w1y); __m256d w2 = _mm256_setr_pd(w2x, w2y, w2x, w2y); __m256d w3 = _mm256_setr_pd(w3x, w3y, w3x, w3y); constexpr __m256d posneg = { 0.0, -0.0, 0.0, -0.0 }; for (int j = i; j < i + len; j += 2) { __m256d c0 = _mm256_load_pd(&f[j + len * 0].x); __m256d c1 = avx_complex_mul(_mm256_load_pd(&f[j + len * 1].x), w1); __m256d c2 = avx_complex_mul(_mm256_load_pd(&f[j + len * 2].x), w2); __m256d c3 = avx_complex_mul(_mm256_load_pd(&f[j + len * 3].x), w3); __m256d a02 = _mm256_add_pd(c0, c2); __m256d a13 = _mm256_add_pd(c1, c3); __m256d s02 = _mm256_sub_pd(c0, c2); __m256d s13 = _mm256_xor_pd(posneg, _mm256_sub_pd(c1, c3)); s13 = _mm256_shuffle_pd(s13, s13, 5); _mm256_store_pd(&f[j + len * 0].x, _mm256_add_pd(a02, a13)); _mm256_store_pd(&f[j + len * 1].x, _mm256_sub_pd(a02, a13)); _mm256_store_pd(&f[j + len * 2].x, _mm256_add_pd(s02, s13)); _mm256_store_pd(&f[j + len * 3].x, _mm256_sub_pd(s02, s13)); } } } for (int i = 0, m = 0; i < N; i += 4, m++) { C w1 = w[m], w2 = w1 * w1, w3 = w1 * w2; C c0 = f[i + 0], c1 = f[i + 1] * w1, c2 = f[i + 2] * w2, c3 = f[i + 3] * w3; C a02 = c0 + c2, a13 = c1 + c3, s02 = c0 - c2, s13 = (c1 - c3) * C(0, 1); f[i + 0] = a02 + a13, f[i + 1] = a02 - a13; f[i + 2] = s02 + s13, f[i + 3] = s02 - s13; } } void ifft(C *f) { for (int i = 0, m = 0; i < N; i += 4, m++) { C w1 = w[m], w2 = w1 * w1, w3 = w1 * w2; C c0 = f[i + 0], c1 = f[i + 1], c2 = f[i + 2], c3 = f[i + 3]; C a01 = c0 + c1, a23 = c2 + c3, s01 = c0 - c1, s23 = (c2 - c3) * C(0, 1); f[i + 0] = a01 + a23, f[i + 1] = (s01 + s23) * w1; f[i + 2] = (a01 - a23) * w2, f[i + 3] = (s01 - s23) * w3; } for (int len = 4; len < N; len <<= 2) { for (int i = 0, m = 0; i < N; i += len << 2, m++) { double w1x = w[m].x, w1y = w[m].y; double w2x = w1x * w1x - w1y * w1y, w2y = 2 * w1x * w1y; double w3x = w1x * w2x - w1y * w2y, w3y = w1x * w2y + w1y * w2x; __m256d w1 = _mm256_setr_pd(w1x, w1y, w1x, w1y); __m256d w2 = _mm256_setr_pd(w2x, w2y, w2x, w2y); __m256d w3 = _mm256_setr_pd(w3x, w3y, w3x, w3y); constexpr __m256d posneg = { 0.0, -0.0, 0.0, -0.0 }; for (int j = i; j < i + len; j += 2) { __m256d c0 = _mm256_load_pd(&f[j + len * 0].x); __m256d c1 = _mm256_load_pd(&f[j + len * 1].x); __m256d c2 = _mm256_load_pd(&f[j + len * 2].x); __m256d c3 = _mm256_load_pd(&f[j + len * 3].x); __m256d a01 = _mm256_add_pd(c0, c1); __m256d a23 = _mm256_add_pd(c2, c3); __m256d s01 = _mm256_sub_pd(c0, c1); __m256d s23 = _mm256_xor_pd(posneg, _mm256_sub_pd(c2, c3)); s23 = _mm256_shuffle_pd(s23, s23, 5); _mm256_store_pd(&f[j + len * 0].x, _mm256_add_pd(a01, a23)); _mm256_store_pd(&f[j + len * 1].x, avx_complex_mul(_mm256_add_pd(s01, s23), w1)); _mm256_store_pd(&f[j + len * 2].x, avx_complex_mul(_mm256_sub_pd(a01, a23), w2)); _mm256_store_pd(&f[j + len * 3].x, avx_complex_mul(_mm256_sub_pd(s01, s23), w3)); } } } } void convolve(uint64_t *a) { init_roots(); for (int i = 0; i < SIZE; i++) f0[i] = C(a[i] & 4095, a[i] >> 12); fft(f0); double t0 = 4 * f0[0].x * f0[0].y, t1 = 4 * f0[1].x * f0[1].y; f1[0].x = 4 * f0[0].y * f0[0].y, f1[0].y = 0; f1[1].x = 4 * f0[1].y * f0[1].y, f1[1].y = 0; f0[0].x = 4 * f0[0].x * f0[0].x, f0[0].y = t0; f0[1].x = 4 * f0[1].x * f0[1].x, f0[1].y = t1; for (int i = 2, msk = 0; i < N; i += 2) { msk |= i >> 1; int j = i ^ msk; C c0 = f0[i] + f0[j].conj(); C c1 = (f0[i] - f0[j].conj()) * C(0, -1); C c00 = c0 * c0, c01 = c0 * c1, c11 = c1 * c1; f0[i] = c00.conj() + c01.conj() * C(0, 1), f0[j] = c00 + c01 * C(0, 1); f1[i] = c11.conj(), f1[j] = c11; } ifft(f0); ifft(f1); for (int i = 0; i < SIZE * 2 - 1; i++) { uint64_t c0 = (uint64_t) (f0[i].x / (N << 2) + 0.5); uint64_t c1 = (uint64_t) (f0[i].y / (N << 2) + 0.5); uint64_t c2 = (uint64_t) (f1[i].x / (N << 2) + 0.5); a[i] = c0 + (c1 << 13) + (c2 << 24); } } uint64_t A[SIZE * 2 - 1]; int main() { for (int i = 1; i < SIZE; i++) A[i] = 1e7; clock_t start = clock(); convolve(A); clock_t end = clock(); uint64_t checksum = 0; for (int i = 0; i < SIZE * 2 - 1; i++) checksum ^= A[i]; printf("checksum: %llu\n", checksum); printf("cpu time: %.3fs\n", (double) (end - start) / CLOCKS_PER_SEC); return 0; } ``` [Try it online!](https://tio.run/##7Vltb9s2EP7uX0F0WCHFUipSSYfVToDWyIdiQ1qs35a5gixLiRK9GJYcy8vy15fd8UWiZNlOgwHbhwaBRB7vnjvyIU8XJlgs7OsgeHr6Ic6CZDUPydhPrvNlXN6k54NGGKR@edMSFOU8zsotUd6SlHEa6oI4TcFoGWfHADYoyuUqKMmEPAwI/Mzz1SwJSWWRzYgLJoZJ3pHKcEwQwZM8PEp5oypbG6FZcc1NrRlnSZyF4CFfhEu/zJdDYgR5VqDT14FJRPuBLMNytcwAuCJDEhxjCLyxMUdkB5J9EMlWSPZ@pKODSEeIBDAb3tpYRIgwRiGqttEB5tboQ7OILYJ5HA0GfDisFku1kJ8/kjPiB3lh2NQcaePAG/ny8fcLGKYO/ljkA7RdBnF53mwVJ2WceUHyp8G1jggOUODjEi3IeEw@gD8/ia8zvzBcZkKM66tLcn5O2NQikXN1iS8KL9C7z@M5uIxLb5nnZQETEXtkfeVMAW9iUIs4ptgmUb4kBoaXhBn6GvHGmBgC3JT9MQwpGL6LyDozcKIw5TfEEDqgDiEXcbYllc5aDmNwBxojaIylE3QfD4dmrSyijjFqeMGagN4UlmedCUDgYTDwvJSdvp0T/77ygjxdJGHlpavEqOUWUc2ZmkM9VgG0l2LHW2ULP7hLcm8xN8DGl0HXqpuu6k28Q3VWNKrFzSqKkhA1ZxaB31OpLDeVVItSfz4vVjOOWHFFOQJT4ULYubMCV/JRMhxFpTEhR5GaU4dKQaDg71wRe35@BnxoRLbogG2Z4ktwcomv4ZnihsEgcKPZanlnTSvOUTrFU7umG9XbjHrVGVeneBTxaXMTbMMs1wytmRziwn4QVwNhGghDEHejDeJhV4MVnBAdTZG2phppYbnERQd7SwYlW@ao35j1GLPKksHI1i5jt8fYrfgk8CFaZifuJrsonEVeZOE1YD0Q5xi4tPmzbpLHDkLN/S3YxCN4jZFxcSpvkXrWpVsPO3CasJPcn2PYr6OrW4EAa@1MMbfutscF3zq0e/Ao4iEL@0DZN4IyCcr2gbrfCOpKULdLWiuhONqmgdOPKAFwFewLxafuthHk88DdY1TonmSSOeip0D1VOd@VYodZXSjhvwerhaFlQpBbhD9Oe1dIGsD3PezdVVZnBWApLVyavhj2glEdTKXfl4KxnsgKBCteAOb2RLYL7HHQbj0OBs/M7SdbSX0iEiEmb0ukNehjErZEnhI9NtIMeCKIrjB1OGDEz7Xo0qkw1aLlB1SMMj7KLHG@hMzlMleHF@cEnEBRKZjBLsWuqyMXSs/memLvwebEvmsC7MSARdCTh4oZTzcYDxHbakIXUhulXRuGowW3KRobV0ltlGoliqjIdn6w/0N@dlLTYaVNCK0JAbc@44SwHkJoTQjoFUwQwp5JCDIM2C1CjIKLAcrkk@7lxUBbG21NucE0ejiCXSPULPWVUCeqGr5syuDv1dP36ul/Uz0drJYOFEoHC6MDNdHBGmhv@UP7y5995Z3INR0jdrD8of3lzz5PBXt2@cN2lj9sR/mDWY0//q3yR6ThF5Y/OyrbuoIRuVtU3i@riXZ4qAsuGT4vw19WKO33oM/hGdWT@mJDkrjPk/vQWME5f3vileTIV2dav18Z9XzOxVcAr3M6dxqRIy40JoaPjdfkxPn5FCaAHfiLnaqaHKuFyFH7Q2btErPGCcwaUHAn1C1IdSVtxmg9RuuvSESFiQ6w0QGEwoZHryxoy4LWFlRZ0LaFs@2jCbKyardnMJXaZMtJE7swkU5KOuqpbPHTWtxtf3lb6Rc1/oI8zZe44b/O3@QrqmxXTZysIb5vp8fiWrClhGtuCC27pVXXNzZtWziOKIqOCM9BqkY64jVSQKkobrE72tozYCzhsdhyqOrUpZQlYhCqQqe3zqISjyoIzuWtlKmaiK@Q2oeyRc0@DrTtrm4vxbbXKKgPEV/Z@kyZcv2A9Dd47chvDLEKPD7VIm6Maa/x5nnGrGtMD3r21dKTIf9rAq8pXZN3GDc5MbVKv3b1/kpfDLyWxbVK/Tgzeut/2k0YgMAd0/AngR8keXAHyEXpL0uMCPtqO9ap6r3Z1g6zeVe3WY6bMLgrVql2fp9Ham349YyHKYwXS7CMjFdq9B35MUlWf2SvrNrA7GguVgT/zQGax25UcFX5/wkgB0O3xXRNYGjy66fJL1@8zxe/eV8uJu1bVAevRZ@e/g6ixL8unuxP7pOd@svg5izzy/g@/Ac "C++ (gcc) – Try It Online") Run with `-O3` or `-Ofast` enabled for best performance. The `-march=native` may also be necessary to run. Uses a standard floating-point radix-4 FFT. Each input integer is split into two 12-bit chunks to avoid precision loss. Since the input comprises of only real numbers, we can get away with doing just a single FFT by using `a&4095` as the real part and `a>>12` as the imaginary part. Upon converting back we still need two FFTs as the output space is twice as large. **Update:** * I realized that the bit reversal was unusually time consuming, so I got rid of it using a DIF-DIT scheme. DIF takes the input in normal order and outputs in bit-reversed order, while DIT takes a bit-reversed input and outputs in normal order. Thus, they magically cancel out :) * I made another mistake in assuming that `llround` was relatively fast. Apparently adding `+0.5` and then truncating is nearly 10x faster than `llround`, which led to a ~30% improvement. * Added SIMD in the FFT loop. This one didn't help that much, presumably because GCC already auto-vectorizes it. [Answer] # [Python 3](https://docs.python.org/3/), 3 seconds ``` R = "".join("%028o"%x for x in A) B = int(R,8)**2 | (1 << 599997*28) t = oct(B) G = [int(t[3+i*28:31+i*28],8) for i in range(199999)] ``` [Try it online!](https://tio.run/##XU09C4MwEN3zK46AkKSlJEppLHbQxd1VMpTSj3RIRDJY6H9Pc0JBfcvdu/dxwye8vCtiDRfolRFKImKXKKWHt7eO0Uzm2tNsgocfYQLroOakSQ7rAuv2mguRwxeYgqqCY5lwErnmJCSLvwXWcNJiPdpDX@xsUs@FmqdJ8bnXYu94dc87U1hRchOHESNtLw0n/10t95UgN2xLl3z@sNVXATTodIg/ "Python 3 – Try It Online") Was a golfing solution somewhere else but also mine [Answer] # Rust + [num-bigint](https://github.com/rust-num/num-bigint/tree/master) or [dashu](https://github.com/cmpute/dashu/tree/master), ~0.3 seconds locally ``` use num_bigint::BigUint; use dashu::integer::UBig; use std::time::Instant; fn solve_num(input: &[u64]) -> (Vec<u64>, u128) { let mut num = Vec::with_capacity(input.len() * 2); for &x in input { num.push(x as u32); num.push(0); } let big = BigUint::from_slice(&num); let instant = Instant::now(); let big2 = &big * &big; let elapsed = instant.elapsed().as_micros(); (big2.to_u64_digits(), elapsed) } fn solve_dashu(input: &[u64]) -> (Vec<u64>, u128) { let big = UBig::from_words(input); let instant = Instant::now(); let square = big.square(); let elapsed = instant.elapsed().as_micros(); (square.as_words().to_vec(), elapsed) } fn main() { let input = ( vec![10_000_000u64; 100_000], vec![1; 5] ).0; let (result, elapsed) = solve_num(&input); println!("elapsed: {}.{:06}", elapsed / 1000000, elapsed % 1000000); eprintln!("{:?}", result); let (result, elapsed) = solve_dashu(&input); println!("elapsed: {}.{:06}", elapsed / 1000000, elapsed % 1000000); eprintln!("{:?}", result); } ``` Instructions to run: * Create a cargo project with `cargo new cg263748` * Add dependencies in `Cargo.toml`: ``` [dependencies] num-bigint = "0.4" dashu = "0.3" ``` * Replace the content of `src/main.rs` with the source above * Run with `cargo run --release 2>/dev/null` Both num-bigint and dashu seem to use "naive/Karatsuba/Toom-3 combo" for inputs with different sizes. For the largest sizes, the main algorithm used is Toom-3. For an input vector of size `10^5`, num-bigint takes ~0.31s and dashu takes ~0.27s. --- I do have an NTT source code for personal use, but I highly doubt it will be competitive given that a term can go up to `10^19`, which means I have to either use 128-bit multiplication and division in the main algorithm, or convolve twice using two (or maybe three) different modulos and combine them using Chinese Remainder Theorem. EDIT: Apparently it is possible to do a single NTT with a prime very close to 2^64, using one of the algorithms described [in this paper](https://www.sciencedirect.com/science/article/pii/S0747717113001181). e.g. one could choose `p = 10485760000033554433`, where `5` is a primitive root. Unfortunately the faster ones won't work because the prime must be under 2^63 for them. EDIT 2: I'm working on the NTT implementation on the paper. I realized I need to do elementwise `a * b % P` anyway, so I came up with a "u128 division"-less algorithm ([godbolt](https://godbolt.org/z/snafEn73z)) for a specific P = `71 * 2^57 + 1` = `10232178353385766913`. This is three times as fast as naive `(a as u128 * b as u128 % P as u128) as u64`: ``` slow mulmod time: [21.182 ns 21.185 ns 21.188 ns] fast mulmod time: [7.0764 ns 7.1222 ns 7.1864 ns] ``` [Answer] # Rust, ~0.048s locally; Rust + [rayon](https://docs.rs/rayon/latest/rayon/index.html), ~0.039s locally The main code (sequential, independent of rayon) is as follows: ``` pub const P: u64 = 10232178353385766913; pub fn mulmod(a: u64, b: u64) -> u64 { let x = a as u128 * b as u128; let y = x >> 57; let y1 = (y >> 35) as u64; let y2 = y as u64 & ((1u64 << 35) - 1); let y_div_71 = y1 * 483939977 + (y1 + y2) / 71; let sub = y_div_71 as u128 * P as u128; let (res, borrow) = x.overflowing_sub(sub); if borrow { (res as u64).wrapping_add(P) } else { res as u64 } } fn powmod(a: u64, p: u64) -> u64 { let mut cur = 1; let mut pow = a; let mut p = p; while p > 0 { if p % 2 > 0 { cur = mulmod(cur, pow); } p /= 2; pow = mulmod(pow, pow); } cur } fn ntt<const INV: bool>(input: &mut [u64], omega_table: &[u64], inv_p2: u64) { // length is a power of 2 let len = input.len(); let l = len.trailing_zeros() as usize; for i in 1..len { let j = i.reverse_bits() >> (64 - l); if i < j { input.swap(i, j); } } let mut root_pow = len / 2; for intvl_shift in 1..=l { let intvl = 1usize << intvl_shift; input.chunks_exact_mut(intvl).for_each(|chunk| { let mut root_idx = 0; let (left, right) = chunk.split_at_mut(intvl / 2); for (u, v) in left.into_iter().zip(right) { let u2 = *u; let v2 = mulmod(*v, omega_table[root_idx]); let (mut x, overflow) = u2.overflowing_sub(P - v2); if overflow { x = x.wrapping_add(P); } *u = x; let (mut y, overflow) = u2.overflowing_sub(v2); if overflow { y = y.wrapping_add(P); } *v = y; root_idx = root_idx + root_pow; // & len - 1; } }); root_pow /= 2; } if INV { for x in input.into_iter() { *x = mulmod(*x, inv_p2); } } } fn ntt_precompute(len: usize) -> (Vec<u64>, Vec<u64>) { let l = len.trailing_zeros(); let primitive_root = 3; let omega = powmod(primitive_root, P >> l); let mut omega_table = vec![1]; // let mut omega_table_prime = vec![((1u128 << 64) / P as u128) as u64]; for i in 1..len { // omega_table.push((omega_table[i-1] as u128 * omega as u128 % P as u128) as u64); omega_table.push(mulmod(omega_table[i-1], omega)); // omega_table_prime.push((((omega_table[i] as u128) << 64) / P as u128) as u64); } let mut inv_p2 = 1; let mut inv_p2_table = vec![1]; for _ in 0..l { if inv_p2 % 2 == 0 { inv_p2 /= 2; } else { inv_p2 = inv_p2 / 2 + P / 2 + 1; } inv_p2_table.push(inv_p2); } (omega_table, inv_p2_table) } pub fn solve_ntt(a: &[u64]) -> (Vec<u64>, u128) { let instant = Instant::now(); let len_max = a.len().next_power_of_two() * 2; let (mut omega_table, inv_p2_table) = ntt_precompute(len_max); let inv_p2 = inv_p2_table[len_max.trailing_zeros() as usize]; let mut a2 = a.to_vec(); a2.resize(len_max, 0); ntt::<false>(&mut a2, &omega_table, inv_p2); for ax in a2.iter_mut() { *ax = mulmod(*ax, *ax); } omega_table[1..].reverse(); ntt::<true>(&mut a2, &omega_table, inv_p2); a2.truncate((a.len() * 2).saturating_sub(1)); let elapsed = instant.elapsed().as_micros(); (a2, elapsed) } ``` This is the version that takes ~0.048s. The code uses NTT (Number Theoretic Transform) with modulo `P = 10232178353385766913 = 71 * 2^57 + 1`. `mulmod` was the major bottleneck until I changed it from u128 multiplication/division to the specialized algorithm for this specific `P`. I also made three variations using `rayon` to parallelize parts of code when possible, with different heuristics. These versions aren't performing well in my local (which is actually a cloud server with only 2 vCPUs) except for the first, but I believe they'll all outperform the original on better CPUs. The entire code can be found at <https://github.com/Bubbler-4/cg263748>. The functions are `solve_ntt`, `solve_ntt_par`, `solve_ntt_par2`, and `solve_ntt_par3` in `lib.rs`. Run instructions: * Clone the repo * `cargo run --release` to see timings and check that the outputs match * `cargo bench` to run the benchmark using the same input (rayon-powered versions are showing very high variance on my local) ]
[Question] [ For the purpose of this challenge, a smaller-base palindrome (SBP) is a number which is palindromic in a base between 1 and itself (exclusive), and is not a repdigit in the same base. For example, 5 is a SBP because it is a palindrome in base 2 (101). The first few SBPs are `5,9,10,16,17,20,21,23,25,26,27,28,29,33...` ## Your Task: Write a program or function that, when given an integer `i` as input, returns/outputs the `i`th SBP. ## Input: An integer `i` where `0 <= i < 1,000,000`. ## Output: The `i`th SBP. ## Test Cases: ``` 12 -> 29 18 -> 41 ``` ## Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), lowest score in bytes wins! [Answer] # [Python 2](https://docs.python.org/2/), ~~133~~ 119 bytes -3 thanks to Ovs -5 thanks to Lynn 1-indexed ``` j=i=0 n=input() while n: j+=1;l=[];N=i while N:l+=N%j,;N/=j if{i%j}<set(l)>l==l[::-1]or j>i:n-=j<i;i+=1;j=1 print~-i ``` [Try it online!](https://tio.run/##Jc6xDoJAEATQmv2KDQkJBIge5cHS0/ADhALhkL2cB0GMGqO/jqD1TGbe9FyG0SZrO3YKCV3XXTUxHcES2@m2@AHcBzYKrQTUIYnUUFWnJTHgPyilCan0dJSWB9KA3L/Y0@/sqhbfBLkhMpWUsajHGXXO0sakM05539IkYJrZLp@Y1@0boN9aBbLFubFn5YsIExFIcH6YDWiay6lrJBbgqIdqcXevXw "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes ``` µNDLвʒÂQ}ʒË_}gĀ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//0FY/F58Lm05NOtwUWAsku@Nr0480/P9vagAA "05AB1E – Try It Online") **Explanation** ``` µ # loop until input matches are found N # push current iteration number D # duplicate L # range в # convert to each base ʒÂQ} # filter, keep elements that are equal to their reverse ʒË_} # filter, keep elements that are not all equal g # length Ā # is trueish (not zero) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` bṖEÐḟŒḂÐfµ#Ṫ ``` [Try it online!](https://tio.run/##ASMA3P9qZWxsef//YuG5lkXDkOG4n8WS4biCw5BmwrUj4bmq//8xOQ "Jelly – Try It Online") -2 thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan), one being for, well, obvious stuff >\_> Explanation: ``` bṖEÐḟŒḂÐfµ#Ṫ Special quick behavior requires full program bṖEÐḟŒḂÐf # Get the first (STDIN number)th integers with truthy results under this function starting from 0 Ṗ Make range [1..tested integer) b Convert the tested integer to each base in the range above EÐḟ Remove repdigits (i.e. negative filter by all-equal) ŒḂÐf Keep palindromes (i.e. filter by is palindrome) µ Ṫ Pop the last element of the integer list formed ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 14 bytes ``` e.f_I#ft{TjLZS ``` [Try it here.](http://pyth.herokuapp.com/?code=e.f_I%23ft%7BTjLZS&input=1&debug=0) 1-indexed. Explanation: ``` e.f_I#ft{TjLZSZQ Trailing ZQ is implicit .f Q Find the first Q (input) positive integers that return a truthy result for SZ Make range [1..Z (tested integer)] jLZ Convert Z to each base in the range f Filter by "non-repdigit" {T Unique elements of T (tested element) t Remove first element _I# Filter by Invariant with Reverse (i.e. palindrome) e Take last element ``` [Answer] # [Python 2](https://docs.python.org/2/), 125 bytes ``` n=5 i=input() while i: n+=1;b=1 while b<n: b+=1;l=[];a=n while a:l+=a%b,;a/=b if{n%b}<set(l)>l==l[::-1]:i-=1;b=n print n ``` [Try it online!](https://tio.run/##JczBCsIwDIDhc/MUvQw25pAKgqSLLzJ2aGCyQIhFKyLis1d01@@HP7/KerVDrUZHEBLLj9J28FxFFy8I3noKkSmA34xHQ3D8U6VpjokM3JYSak@p4V1Me2Jwcnlbw5/xvpRWu7MS6YQ4hBll@E8N8k2seKs1nL4 "Python 2 – Try It Online") `n` represents the integer we test for SBP-ness as we count up. `i` is the input: it is decremented each time `n` is an SBP. We loop over bases `b` from 2 to `n` inclusive\* and compute the (backwards) base-`b` representation of `n`: this is `l`. The only real magical part is the chained comparison `{n%b}<set(l)>l==l[::-1]`: * `{n%b}<set(l)` makes sure `l` contains at least two distinct digits (i.e. `n` is not a repdigit), by checking that `{n%b}` is a *strict* subset of `set(l)`. (We know `n%b` is in `l` as `n%b` is the last digit of `n` in base `b`.) * `set(l)>l` is always true because of how Python sorts types. * `l==l[::-1]` checks that `l` is a palindrome. One final trick is using `b=n` instead of `break` to exit the loop. (\*It’s safe to include `n` in the loop, as `n` in base `n` is always `10`, which isn’t a palindrome. (`while b<n` looks like we exclude `n`, but note where the `b+=1` is!)) [Answer] # [Dyalog APL](https://www.dyalog.com/), 53 bytes ``` {{∨/∧/¨((1<≢∘∪)∧⌽=⊢)¨(⍵+1)⊥⍣¯1⍨¨1↓⍳⍵+1:⍵+1⋄∇⍵+1}⍣⍵⊢2} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24Tq6kcdK/QfdSzXP7RCQ8PQ5lHnokcdMx51rNIEij3q2Wv7qGuRJlDqUe9WbUPNR11LH/UuPrTe8FHvikMrDB@1TX7UuxksZQUmH3W3POpoBzNrgQqBDKB2o1qgVQqHVgCVKhgZAAA) [Answer] # [Perl 6](https://perl6.org), 83 bytes ``` {(5..*).grep({grep {.Set>1&&[.reverse]eqv$_},map {[.polymod($^a xx*)]},2..$_})[$_]} ``` [Try it](https://tio.run/##K0gtyjH7n1upoJacn5KqYPu/WsNUT09LUy@9KLVAoxpEKlTrBaeW2BmqqUXrFaWWpRYVp8amFpapxNfq5CYCZaP1CvJzKnPzUzRU4hIVKiq0NGNrdYz09IAKNKNV4mNr/xcnViqAjTc0suZCcCys/wMA "Perl 6 – Try It Online") ## Expanded ``` { # create a list of SBPs (5 .. *).grep( { # find out if the current value is a SBP grep { # parameter is $_ .Set > 1 # is there more than one distinct digit? && [.reverse] eqv $_ # is it the same in reverse? }, map { # parameter is $a [ # put into an Array so it is not a one shot Seq .polymod( $^a xx *) # convert into new base ] }, 2 .. $_ # possible bases # (don't need to exclude $_ here) } )[ $_ ] # index into the list of SBPs } ``` ]
[Question] [ This challenge consist in adding commas to numbers every `3` spaces like: ``` 123456789 => 123,456,789 ``` ## Specifications: * The possible inputs will be `1,000 <= input <= 100,000,000` * You can ONLY use Mathematical Operators * (\*) You can NOT do string, array, index or character manipulation * You can NOT use any kind of built-in functions that add these commas * The zeros should remain, ex `10000 => 10,000` * You need to print/alert/log the output (so "the output is at x var" is not allowed) (\*) the only exception is when forming/printing the output (but not in a manner that suggest cheating) ## Examples ``` 10100 => 10,100 120406 => 120,406 999999999 => 999,999,999 ``` --- **A basic idea on how to get numbers legally:** ``` n = 123456; m = roundDown(n / 10);//even if ends with .9 d = n - m;//we get the last number ``` [Answer] You weren't very specific on the output format... ## Haskell, 56 ``` reverse.takeWhile(>0).map(`mod`1000).iterate(`div`1000) ``` example: ``` GHCi> reverse.takeWhile(>0).map(`mod`1000).iterate(`div`1000)$93842390862398 [93,842,390,862,398] ``` [Answer] ## GolfScript, ~~13~~ 37 chars ``` 0:|;~{.10%|):|3%''','if@10/.9>}do]-1% ``` Look, Ma, no arrays! Well, almost. The pieces of the output are collected on the stack in right-to-left order, so the final `]-1%` is needed to reverse them. But I assume that's OK, as it counts as "forming/printing the output". Here's an ungolfed version with comments: ``` 0 :| ; # initialize the variable | to the value 0 ~ # eval the input, turning it from a string into a number { # start of loop . # duplicate the number on top of the stack; we'll need it later 10 % # take the remainder modulo 10 and leave it on the stack | ) :| 3 % # increment | by one and take the remainder modulo 3 of the result '' ',' if # if the remainder is 0, push a comma onto the stack, else an empty string @ # pull the value we saved at the start of the loop to top of the stack 10 / # divide it by ten, rounding down . 9 > # check if the result is greater than 9... } do # ...and repeat the loop if so ] # finally, collect the digits and commas off the stack into an array... -1 % # ...and reverse it for output ``` --- If it weren't for a few pesky details, the following 13-char solution would be pretty hard to beat: ``` ~1000base','* ``` However, it fails on two counts: it doesn't correctly preserve leading zeros in digit groups, and the built-in base conversion operator `base` *might* be considered "array manipulation", since it takes a number and returns an array of digits. --- Ps. Here's an older 49-char arrayless solution: ``` ~{.999>}{:^1000%:&9&>99&>+{0}*','^1000/}while]-1% ``` [Answer] ## Python 2, 86 chars I figured this warranted a different enough answer. The first answer is for 3.0 only because of the print statement with `end=`, and this answer because division automatically floors instead of converts to float, and the use of backticks ``` b=input() k=0 x='' while b>0: x=`b%10`+x;b/=10;k+=1 if k%3==0and b>0:x=','+x print x ``` Only string manipulation is building the output edit: by adding 5 characters `int()`, this program can accept any integer, even above 1 billion. The previous program inserts `L`s (python longs) if the number is too large, but is still within the constraints of the challenge. Here is the program that works with any integer: ``` b=input() k=0 x='' while b>0: x=`int(b%10)`+x;b/=10;k+=1 if k%3==0and b>0:x=','+x print x ``` - ``` 879612587634598623589762354009 879,612,587,634,598,623,589,762,354,009 ``` [Answer] AWK, no strings, 84 chars: ``` {for(p=$0;.1<p/=10;++i);for(;i-->0;printf i&&i%3==0?"%d,":"%d",$0/10**i%10);print""} ``` Test runs: ``` % awk -f commas.awk <<< 1230 1,230 % awk -f commas.awk <<< 123012 123,012 % awk -f commas.awk <<< 12301 12,301 % awk -f commas.awk <<< 12301000 12,301,000 ``` [Answer] ## C, 136 ``` i,j,k;main(m,n){scanf("%d",&n);for(m=n;n^0;i++,n/=10);k=i%3;while(j++<i)printf("%d%c",(int)(m/pow(10,i-j))%10,j%3==k?',':0);putchar(8);} ``` [Answer] `awk`, 47 chars > > > ``` > awk '{for(_=NF-2;1<_;_-=3)$_=","$_}NR' FS= OFS= > > ``` > > ``` 10,100 120,406 999,999,999 ``` [Answer] ## Python, 82 chars ``` n=input() x='' while n>999:x=','+`n/100%10`+`n/10%10`+`n%10`+x;n/=1000 print `n`+x ``` I can get it shorter (67 chars) with ``` while n>999:x=',%03d'%(n%1000)+x;n/=1000 ``` Not sure if that's legal. [Answer] ## befunge, 62 ``` &# <v%3-\3%3y+8a$j*d`0:/a\%a: 1`j@>:3%\3/!3*j',,\'0+,1+a8+y ``` well this code is array free, since befunge itself is array free. * the first line simply reads a number and push every digit into stack. * the second line reads those digits and prints then once at a time. and put commas if needed. note that if you are trying to run it using rcfunge, you need run using "-Y" option. [Answer] ### Scala 65: ``` def f(n:Int){if(n<1000)print(n)else{f(n/1000) print("."+n%1000)}} ``` Testcode: ``` val l=List(1,12,123,1234,12345,123456,1234567) l.foreach(x=>{f(x);println}) ``` [Answer] ## Python 3, 165 chars ``` from math import* b=int(input()) j=10**8 k=l=0 while j>0: z=int(floor(b/j));b-=z*j;k+=1;j=floor(j/10) if not l:l=z!=0 if l:print(z,end=','if k%3==0and j>0 else'') ``` No strings except for '' and ',', no arrays/lists/tuples/dicts, or indexing edit: nixxed some characters [Answer] ## Python 2.6.5, ~~65~~ 94 chars ``` n=input() s='' while n: s=','+str(x)+s if x else','+'000'+s n/=1000 print s[1:] ``` Just used the string to store the output. ~~\*Now preserves zeros~~ [Answer] ## C, 80 chars Using recursion within `printf` to reverse the printing order (recursion handles the least significant digits first, but printing is done when returning, so they're printed last). ``` n; p(x) { x=n%1000; n/=1000; printf(n?p(),",%03d":"%d",x); } main(){ p(scanf("%d",&n)); } ``` [Answer] ## JavaScript ~~104~~, ~~99~~, ~~90~~, 81 > > Edit: I just noticed I also have this missing zeros bug when any group of > contains 000 ,00X or 0X0. If you see this message, the code below isn't fixed yet > > > Code: ``` for(n=0,s="",i=m=1e3,r=0;i<n*m;i*=m)r=~~((n%i-r)/i*m),s=r+(i-m?",":"")+s;alert(s) ``` **Note:** change the value of `n` for different inputs ]
[Question] [ ### Backstory, skip if you like Generating high quality pseudo random numbers is a tricky business but the fine engineers at < enter company you love to hate > have mastered it. Their progress bars effortlessly rise above the primitive notion of linearly passing time and add an exhilarating sense of unpredictability to the waiting experience. Cynics have dismissed the entire matter as a ploy to prevent employees from being able to assess whether there is enough time to grab a coffee. All I can say is I feel sorry for those people. It so happens that your boss believes to have reverse-engineered the secret of the < enter company you love to hate > (tm) progress bar and has tasked you with golfing up a simulator. ### Task Given a length L and list of tasks, each represented by a list of times each of the task's steps is expected to take, implement a progress bar that at each time indicates the percentage of steps expected to have completed by that time assuming the tasks are independent. The length of the bar should be L at 100%. ### I/O Flexible within reason. You may pass list lengths separately if you wish. You may also input a time in which case the output should be a single horizontal bar of correctly rounded integer length. Otherwise you may represent time as actual time in a unit of your choice or as one axis (top-to-bottom) in a 2D plot. ### Examples ``` I: [20,[2,2,2],[3,3,3],[10]] O: ### ###### ######### ######### ############## ############## ############## ################# #################### I: [8,[1,1],[2,1],[3,2],[12,1]] O: # ### ##### ##### ###### ###### ###### ###### ###### ###### ###### ####### ######## I: [30,[1,2,3],[2,4,7],[2,2,2,2,2,2,2,2],[9,10],[1,1,3,2]] O: ### ######## ######### ########### ############ ################# ################## #################### ##################### ####################### ####################### ######################## ########################## ########################### ########################### ############################# ############################# ############################# ############################## I: [4.7,20,[1,2,3],[10,10],[1,1,1],[4,10]] O: ############ ``` ### Scoring/rules/loopholes: code-golf as usual. ### Reference implementation Python >= 3.8 ``` def f(l,S,c=0): T=len(sum(S,[])) # total number of steps while S:=[*filter(None,S)]: # check whether any tasks still runnimg for s in S: # go through tasks if s[0]>1:s[0]-=1 # current step terminating? no: update time left else:c+=s.pop(0) # yes: remove step and increment step counter print((T//2+l*c)//T*"#") # output bar ``` [Try it online!](https://tio.run/##XY7BbsIwEETP5StWcLHBLQEuVaS0f9BLuEU5pGaTWDhry1634utTA1WFuntYaTXzZvyFR0eHVx/m@YQ99MKqWumqkOUCjpVFEjFNolZNKyU8zArYcWeB0vSJAVwPkdHHBXyPxiLUZdWse2MZg/hwhKqWbZlNekR9zhrkMbs6ugB38Ryz2VgLIRGZaVgA9C5ABEMZBP9mBYMDHoNLw3h3Zz2YXKAp2rddeT3P1e5Br1MISHxrCLnRZKhjQ8M7kCsh@VPHCGwmBIs9X2loI5Z6U8UX77wo5NMv6YKxhICT@8I7raNTbqnz6y9Au0Q5JGN8MMRCHLfb/cautdxuj@vlailvKJfYJ4bPLsy92BcKmmav8raqOai8@e6KtpXzDw "Python 3.8 (pre-release) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 16 bytes ``` ƛ¦Þǔ;∑¦Ḣ:G/*⌈×*⁋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLGm8Kmw57HlDviiJHCpuG4ojpHLyrijIjDlyrigYsiLCIiLCJbWzEsMiwzXSxbMiw0LDddLFsyLDIsMiwyLDIsMiwyLDJdLFs5LDEwXSxbMSwxLDMsMl1dXG4zMCJd) Straightforward port of [my Jelly answer](https://codegolf.stackexchange.com/a/242782/100664), go see that explanation for a better idea of how it works. Jelly has some nicer builtins. ``` ƛ ; # Map each task to... ¦ # Cumulative sums (instants where a step will complete) Þǔ # Untruth (a boolean list with 1s at those indices) ∑ # Reduce the whole thing by addition ¦Ḣ # Get cumulative sums and remove the leading zero :G/ # Divide by the maximum * # Multiply by the input ⌈ # Get the ceiling ×*⁋ # Make a bar graph ``` [Answer] # [Python 3.8](https://docs.python.org/3.8/), 91 bytes ``` lambda L,X,t:int(sum((s:=0)+sum(t>=(s:=s+y)for y in x)for x in X)*L/sum(map(len,X))+.5)*'#' ``` [Try it online!](https://tio.run/##HY1RCoMwEESvstAPs7q0RikUwZ7AAwSsHynVNqAxJCno6VO3zMe8gQfj9vhZbX1zPk3tI816eb40dKQoNsZGEb6LEKFpSywY473lFYodp9XDDsbC9seNUWHeXdhbtBPzaEkhFucr5tkpS2wZtry271FIkhIbcJ5vJlGVBH1f0ZGB@pqOHC3LYSAwiOkH "Python 3.8 (pre-release) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/) with [numpy](https://numpy.org/), 76 bytes ``` lambda L,X,t:int(L*mean(t>=hstack(map(cumsum,X)))+.5)*'#' from numpy import* ``` [Try it online!](https://tio.run/##FcxBDoIwEEDRvaeYxAUdnBgKcUOCJ@AAJMiiIpVGp21Ku@D0FfMWf/f9Hldnm6y7R/4qfr4U9DRQbI2Noi95UVbEe7duUc0fwcqLOfGWmAZEvFxvWBbn4qSDY7CJ/Q6GvQuxzNoFMGAsBGXfi5AkJbbgw/@rRV0RjGNNh4nGhg5HZTVNBAYx/wA "Python 3 – Try It Online") `cumsum` transforms a list of step lengths into an array of the steps' finishing times, and `hstack` combines those arrays into one long array. The comparison produces 1 for finished steps and 0 for unfinished steps, and then `mean` gives the proportion of finished steps. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` E⌈EηΣι⁺·⁵∕×ΣEηΣE묛Ӆλ⊕ξ⊕ιθΣEηLλ ``` [Try it online!](https://tio.run/##VU3BCsIwFPuVHlt4ypx48jhBBJXBvJUeyvawhbbTrhvz62tXBJXweCEJSaukb3tpYqy9doFe5CPdrO1oM1dAmkQ1YwxIbcaBFusdkIOedIf0pi0OtPnPLtQAufaBHj3KgD4nqldrsFJ9Nk@u9WjRBezonLt/lWWNZfXJvp2p/ozuHhQ1H38fIy8L4LyEBAF8CwnpbwohRFxN5g0 "Charcoal – Try It Online") Link is to verbose version of code. Outputs a bar graph. Explanation: ``` η List of tasks E Map over elements ι Current list of subtasks Σ Take the sum ⌈ Take the maximum E Map over implicit range η List of tasks E Map over elements λ Current list of subtasks E Map over elements λ Current list of subtasks … Truncated to length ξ Innermost index ⊕ Incremented Σ Take the sum ¬› Is less then or equal to ι Outer value ⊕ Incremented Σ Take the sum Σ Take the sum × Multiplied by θ Desired maximum length ∕ Divided by η List of tasks E Map over elements λ Current list of subtasks L Take the length Σ Take the sum ⁺ Plus ·⁵ Literal number `0.5` Implicitly print as bar graph ``` 35 bytes for a version that outputs in real time: ``` RFφ⌈EηΣιP⁺·⁵∕×ΣEηΣE꬛Ӆκ⊕ν⊕ιθΣEηLκ ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` ÄṬSÄ÷Ṁ$×+.ḞṬ€G ``` [Try it online!](https://tio.run/##y0rNyan8//9wy8Oda4IPtxze/nBng8rh6dp6D3fMAwo9alrj/j862lDHSMc4VifaSMdExxxMo0CgiKWOoQGQMtQx1DEGCsQeXm5s8B8A "Jelly – Try It Online") A dyadic link that outputs a bar graph (sorta). I'm quite proud of `ÄṬSÄ` which generates the numbers before stretching. I'm also somewhat annoyed that the code to stretch the numbers is six bytes. I feel like there's got to be a better way to do that, but I'm not sure what. The below explanation uses `[[1,1],[2,1],[3,2],[4,1]]` and `16` as an example. ``` Ä Take the cumulative sums of each item Generating a list of lists of indices at which another task segment completes. For the example list, [[1,2],[2,3],[3,5],[4,5]] Ṭ Take the untruth of each item Turning each into a boolean list with 1s at the specified indices Each task is now a boolean list where 1s represent that a task will be represented at that instant For the example, [[1,1],[0,1,1],[0,0,1,0,1],[0,0,0,1,1]] S Reduce the list by vectorised addition The result becomes a single list where the number at each index Is the number of tasks completed at that instant [1,2,2,1,2] Ä Take the cumulative sum, getting the total tasks completed at that instant [1,3,5,6,8] --$ Run what's next on the result of the above ÷ Float divide the list by... Ṁ Its maximum Producing a list of floats between 0 and 1 [.125,.375,.625,.875,1] × Multiply the result of the above by the other input +.Ċ Round the results. [2,6,10,14,16] Ṭ€G Format into a grid ``` [Answer] # [R](https://www.r-project.org/), 85 bytes ``` \(L,x)barplot(sapply(max(u<-unlist(Map(cumsum,x))):1,\(i)(.5+mean(u<=i)*L)%/%1),ho=T) ``` [Try it on rdrr.io!](https://rdrr.io/snippets/embed/?code=f%3Dfunction(L%2Cx)barplot(sapply(max(u%3C-unlist(Map(cumsum%2Cx)))%3A1%2Cfunction(i)(.5%2Bmean(u%3C%3Di)*L)%25%2F%251)%2Cho%3DT)%0A%0Af(20%2Clist(c(2%2C2%2C2)%2Cc(3%2C3%2C3)%2C10))%0Af(8%2Clist(c(1%2C1)%2C2%3A1%2C3%3A2%2Cc(12%2C1)))%0Af(30%2Clist(c(1%2C2%2C3)%2Cc(2%2C4%2C7)%2Crep(2%2C8)%2C9%3A10%2Cc(1%2C1%2C3%2C2)))) with graphical output, but with older and longer function syntax. ]
[Question] [ A [magic square](https://en.wikipedia.org/wiki/Magic_square) is an \$ n \times n \$ square grid, such that the sum of the integers on each row and column are equal. Note that the definition which will be used in this challenge is different than the one used by Wikipedia, since * diagonal sums are not accounted for * the numbers are not required to be distinct or in the range \$ 1, 2, ..., n^2 \$ ## Task Write a program/function such that given an \$ n \times n \$ square, return *Truthy* if it is a *magic square*, and *Falsey* otherwise. There is a catch, however. The source code itself must also form a magic square, where each character in the source code corresponds to its *Unicode codepoint*. ## Rules/Clarifications * You may take input in any reasonable format (e.g. 2D array, flattened list, etc.) * The source code should be a list of \$ n \$ strings, each consisting of \$ n \$ characters, joined by newlines. * The unicode character should be in its *composed* representation. * [Here](https://tio.run/##fY4xDoJAEEX7PcVI464aorGmIMYYC0PUWOEWJKxxEliWnaXQK3gUL2AtB0NECm3s/k/e/Dfm4s6FnjcN5qawDuhCjFFZJVZBAHGG5Dj6lpxFw4dHPRQCToUFBNRv2CeXovatStIMtSIuJEuIVDuVKc0/SwKC4KvGUyl@IOV4TFXO88TwwqYToN5CnaU7kjCGP9C1fW/U26TohDNmLGrHvU24Wi9gvz2Eu@XAE01TP573qL6VrOwTa0sXWdQn9iHqxws) is a program to check if your program/function is a magic square This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes Executed code is the same as [this](https://codegolf.stackexchange.com/a/205702/64121) answer. I was extremely lucky all the required characters were in the 05AB1E codepage. ``` ø«O Ëq¶ /Öí ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8I5Dq/25DncXHtrGpX942uG1//9HRxuamesoKJhZAglTEGFpEKujEA2kYAIgKaAisCiUDVYGlgeLQvXBpMwsY2MB "05AB1E – Try It Online") [Verify it!](https://tio.run/##fY4xCsJAFET7PcU3jbsqUbFOEUTEQkTFKqYIZMUPyWazfy30CvZeQmzF2hwsxphCG8uBN/NGH@0@U6OyxFRnxgIdiTHKD5GR4EGQIFmOriFrUPP2VrWFgF1mAAHVG3bJxqhcI6M4QSWJi5BFRLKaSqTinyUBnvcVg0EofiBpeUCHlKeR5pmJe0CNhWpLXQqhC3@gU3Wv09hCUQuHTBtUljtzfzobw3q58VeTliPKsng8rwtWnPPnnfWLS3F7AQ "Python 3 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` §E;Z Z;E§ E§Z; ;Z§E ``` A monadic Link which yields `1` if the argument is a magic square as per the definition and `0` otherwise. Also works as a full program which prints the result (the first three helper links are actually unused). The sums of the diagonals of the Unicode characters in the code are also equal to the row and column sums (385). **[Try it online!](https://tio.run/##y0rNyan8///QclfrKK4oa9dDy7mAOMqayzoKKPb////oaEMzcx0FBTNLIGEKIiwNYrl0ooEUTAAkBVQEFoWywcrA8mBRqD6YlJllbCwA "Jelly – Try It Online")** ### How? ``` ;Z§E - Main Link: list of lists of numbers, M Z - transpose M ; - M concatenated with that § - sums E - all equal? ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes Just a port of the Jelly answer. ``` ø«OËq qø«OË Ëqø«O OËqø« «OËqø ``` [Try it online!](https://tio.run/##yy9OTMpM/f//8I5Dq/0PdxdyFUJZXEAOmMnlD2VxQVQc3vH/f3S0oZm5joKCmSWQMAURlgaxOgrRQAomAJICKgKLQtlgZWB5sChUH0zKzDI2FgA "05AB1E – Try It Online") ## Explanation ``` ø Transpose the input « Concatenate with the original input O Sum (vectorizes over sublists) Ë Are these sums all equal? q Exit the program (to create a garbage dump) Now we got a HUGE garbage dump over here. qø«OË Ëqø«O OËqø« «OËqø ``` ]
[Question] [ **Intro -** Nearest neighbour comparison between two arrays is something that can be done very efficiently when only 1 variable per array is involved, because it can be done by sorting and then performing a rolling comparison. However, for a 2 variable comparison this sort operation cannot be done anymore and another smart way has to be thought of. Hence the challenge: **Challenge -** The challenge is to write a code that can, for each row in array A, find a row in array B such that (A[i,1]-B[j,1])^2+(A[i,2]-B[j,2])^2 is minimal and that then stores the corresponding row number j. The perfect minimum (0) is a perfect match of A[i,1] with B[j,1] and of A[i,2] with B[j,2]. As a code example I have a very clunky loop written in R ``` N=nrow(SetA) for (i in 1:N){ #calculate vector with distance of row i to the entire SetB vec=with(SetB,(SetA[i,x]-x)^2+(SetA[i,y]-y)^2) #calculate minimum of that vector and store the index indexVec[i,ind:=which.min(vec)] } ``` **Some sidenotes -** If it matters (not sure it will) assume that both arrays have 10k rows. Ties can be decided at 'random' e.g. determined by processing sequence or whatever way is more convenient in your code. **Example in/out -** For clarity, here is the sample input ``` SetA=[1 3;2 4;3 5;4 6;5 7] SetB=[2 2.5; 4 3.1; 2 2.0; 3 3.0; 6 5.0;] ``` and the expected sample output ``` indexVec=[1;4;4;5;5] ``` where the values in indexVec indicate where the nearest neighbour of row i in SetA is located in SetB. Fastest code (as tested on my i5-4210U) wins. The testset will consist of 2 arrays of 10k rows and 2 columns filled with floating point numbers between -1E10 and +1E10. Of course seeded with the same seed to remove any unfairness. **Feel free to use whatever language, but I am also very interested in an optimized version of the R code above.** [Answer] ## C++, .0007 seconds Uses a simple grid to place all the points of B, then looks up the points of A starting at the grid point to which it maps. ``` #include <stdio.h> #include <stdlib.h> #include <thread> #include <sys/time.h> double mytime() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec * 1e-6; } typedef float vector[2]; #define T 4 // N must be a multiple of T #define N 10000 // Width of grid. Should be about sqrt(N) #define W 100 vector a[N]; vector b[N]; int min[N]; float dist(vector x, vector y) { float a = x[0]-y[0]; float b = x[1]-y[1]; return a*a+b*b; } int mindist_test(vector x, vector *y, int n) { float best = dist(x, y[0]); int bestidx = 0; for(int i = 1; i < n; i++) { float d = dist(x, y[i]); if(best > d) { best = d; bestidx = i; } } return bestidx; } typedef struct cell cell; struct cell { vector v; cell *next; }; cell *grid[W][W]; cell cells[N]; float minx, miny, scalex, scaley, scale, scale2; void build() { // Find bounds minx = b[0][0]; miny = b[0][1]; float maxx = b[0][0]; float maxy = b[0][1]; for(int i = 1; i < N; i++) { if(minx > b[i][0]) minx = b[i][0]; if(maxx < b[i][0]) maxx = b[i][0]; if(miny > b[i][1]) miny = b[i][1]; if(maxy < b[i][1]) maxy = b[i][1]; } scalex = (maxx - minx + .00001) / W; scaley = (maxy - miny + .00001) / W; scale = scalex < scaley ? scalex : scaley; scale2 = scale * scale; // Place B vectors in grid for(int i = 0; i < N; i++) { cells[i].v[0] = b[i][0]; cells[i].v[1] = b[i][1]; int x = int((b[i][0] - minx) / scalex); int y = int((b[i][1] - miny) / scaley); cells[i].next = grid[x][y]; grid[x][y] = &cells[i]; } } int find(vector v) { // Start checking at grid[x][y] int x = int((v[0] - minx) / scalex); int y = int((v[1] - miny) / scaley); float mindist = 1e30; cell *mincell; // Look in grid cells within radius r for(int r = 1; r < W; r++) { for(int i = x-r; i <= x+r; i++) { if(i < 0 || i >= W) continue; for(int j = y-r; j <= y+r; j++) { if(j < 0 || j >= W) continue; for(cell *c = grid[i][j]; c != NULL; c = c->next) { float d = dist(v, c->v); if(mindist > d) { mindist = d; mincell = c; } } } } // If we've found a point close enough, stop. // The next iterations' points are guaranteed to be at least distance r*scale away. if(mindist < (r*r)*scale2) break; } return mincell - cells; } void thr(int t) { int base = N/T*t; for(int i = 0; i < N/T; i++) { min[base+i] = find(a[base+i]); } } int main(int argc, char *argv[]) { // Initialize for(int i = 0; i < N; i++) { a[i][0] = rand() / (RAND_MAX/1000000.); a[i][1] = rand() / (RAND_MAX/1000000.); b[i][0] = rand() / (RAND_MAX/1000000.); b[i][1] = rand() / (RAND_MAX/1000000.); } // Run & time double start = mytime(); build(); std::thread* threads[T]; for(int t = 0; t < T; t++) { threads[t] = new std::thread(thr, t); } for(int t = 0; t < T; t++) { threads[t]->join(); } double stop = mytime(); printf("time: %f\n", stop - start); // Check results for(int i = 0; i < N; i++) { int j = min[i]; int k = mindist_test(a[i], b, N); if(dist(a[i], b[j]) != dist(a[i], b[k])) { printf("BAD %d: %d %f %f\n", i, j, dist(a[i], b[j]), dist(a[i], b[k])); } } } ``` Compile with ``` g++ -O3 -std=c++11 -stdlib=libc++ grid.cc -o grid ``` [Answer] # Mathematica 0.035230 secs ## Update The latest version required * **0.035230 sec for 10k rows of data** * 0.419461 sec for 100k rows * 4.975199 sec for 1 million rows --- ``` nf = Nearest[Thread[B -> Range[n]]] ``` The nearest function, `nf`, delivers a 100 fold speedup over the prior approach. This is due to the creation of a lookup table for positions: ``` r[m_]:= RandomReal[{-E^10,E^10},{m,2}] n = 10000; A = r[n]; B = r[n]; (nf = Nearest[Thread[B -> Range[n]]]; Flatten@(nf[#, 1][[1]] & /@ A);) // AbsoluteTiming ``` > > {0.035230, Null} > > > --- **Example** ``` n = 10; A = r[n] B = r[n] (nf = Nearest[Thread[B -> Range[n]]]; Flatten@(nf[#, 1][[1]] & /@ A)) ``` > > (\*A \*) > > {{3944.81, 10711.}, {-12978.5, -7807.64}, {-7309.13, 15.5648}, {-2695.33, 6309.87}, {14819.7, 21796.6}, {20681.7, -296.336}, {-7396.73, -9588.16}, {73.5495, -7730.14}, {-20361.8, -4616.41}, {21576.4, -18024.}} > > > (\*B \*) > > {{21382., -597.126}, {5872.82, 6305.16}, {-10502.4,2378.9}, {-5643.86, 19461.4}, {-4986.97, -2173.96}, {10024.5, 14230.6}, {6747.26, 6242.93}, {15714.1, -18345.4}, {-21971., -5052.04}, {-17088.2, 3853.11}} > > > (\*Output \*) > > {2, 9, 5, 2, 6, 1, 5, 5, 9, 8} > > > --- I'm including 2 earlier approaches to highlight the improvements in speed due to seemingly minor tweaks. ## Prior approach This takes about 3.5 seconds for arrays of {10^4,2}, This makes it 10 times slower than the above approach, but 10 times faster than my first, naive, implementation. The key improvement was to look for positions through one call. It also uses the built-in Nearest function (but doesn't exploit it nearly as well as the current version). ``` r[m_]:= RandomReal[{-E^10,E^10},{m,2}] n=10000; A=r[n]; B=r[n]; nf = Nearest[B]; Flatten@Position[B, #] & /@ (nf[#, 1][[1]] & /@ A); // AbsoluteTiming ``` > > {3.554101, Null} > > > --- ## First attempt This unoptimized version takes 40 seconds for 10k rows. ``` r:= RandomReal[{-E^10,E^10},{10^4,2}] nearness[{r1_,c1_},array_]:=Total[({r1,c1}-#)^2]&/@array nearestPosition[aArray_,bArray_]:=Position[z=nearness[#,bArray],Min[z]][[1,1]]&/@aArray ``` Test ``` A = r B = r nearestPosition[A, B]; // AbsoluteTiming ``` > > {40.141484, Null} > > > [Answer] # Python 3 ``` from scipy import spatial import numpy as np def nearest_neighbour(points_a, points_b): tree = spatial.cKDTree(points_b) return tree.query(points_a)[1] ``` **0.05 seconds for 10k rows of data**, 0.7 seconds for 100k rows, and 7.6 seconds for a million rows. Originally I wanted to implement the approach myself, but why do so, when NumPy and SciPy offer everything you want. The idea is to build a KD-tree of the points b. Using this KD-tree you can effectively search for the nearest points, since you can restrict the search space quite a bit. I'm not completely sure about the implementation of SciPy, but you can check out one algorithm at [Wikipedia](http://en.wikipedia.org/wiki/K-d_tree#Nearest_neighbour_search). The complexity of this should be about `O(N*log(N))` for computing the KD-tree (`N` is the number of entries) and `O(log(N))` for a single search on average. If `N = #a = #b`, the total complexity is `O(N*log(N))`, which is a lot better than the brute force approach with `Theta(N^2)` ## Tests The output of example in Michiel's post is `[0 3 3 4 4]` (Off by one because R). ``` a = np.array([[1, 3],[2, 4],[3, 5],[4, 6],[5, 7]]) b = np.array([[2, 2.5],[4, 3.1],[2, 2.0],[3, 3.0],[6, 5.0]]) print(nearest_neighbour(a, b)) ``` Testing it for `n = 10k`: ``` import time n = 10**4 points_a = np.random.rand(n, 2) points_b = np.random.rand(n, 2) start_time = time.time() result = nearest_neighbour(points_a, points_b) end_time = time.time() print("n = {:7d}, {:.3f} seconds".format(n, end_time - start_time)) ``` You can view the complete program at [Gist](https://gist.github.com/jakobkogler/97c2434b1dcc8344e0df). [Answer] **R** You can vectorize your operations for a bit more speed. If you need something faster, move to a different language lol. ``` # Original data SetA = matrix(c(1, 3, 2, 4, 3, 5, 4, 6, 5, 7), nrow = 2) SetB = matrix(c(2, 2.5, 4, 3.1, 2, 2.0, 3, 3.0, 6, 5.0), nrow = 2) # 10k random sample data SetA = matrix(sample(1:20, 20000, replace = T), nrow = 2) SetB = matrix(sample(1:20, 20000, replace = T), nrow = 2) apply(X = SetA, MARGIN = 2, FUN = function(z) which.min((SetB[1,]-z[1])^2 + (SetB[2,]-z[2])^2)) ``` Takes me ~2.6s to run 10k points. edit: Vectorized it a bit more. This version is another 0.3s faster than the solution above. ``` apply(X = SetA, MARGIN = 2, FUN = function(z) {which.min(colSums((z-SetB)^2))}) ``` [Answer] ## C++ with AVX, brute force, 0.013 seconds 10K isn't that big, right? Just plow through the O(n^2) algorithm using AVX instructions to do it really fast. I'm using single-precision floating point, I hope that is ok. Update: now with threads! ``` #include <stdio.h> #include <immintrin.h> #include <thread> #include <sys/time.h> double mytime() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec * 1e-6; } typedef float vector[2]; // for each 0<=i<4, finds y[j] closest to x[i] 0<=j<n. // puts the resulting j's in r[0..3]. void mindist(vector *xp, vector *yp, int n, int *r) { // Load 4 vectors from x __m256 x = _mm256_load_ps(&xp[0][0]); // Best distance & its index found so far, for the 4 x vectors. // Packed strangely in the 8 32-bit-float-sized slots. // 0: dist0 // 1: dist1 // 2: idx0 // 3: idx1 // 4: dist2 // 5: dist3 // 6: idx2 // 7: idx3 __m256 best = _mm256_set_ps(0, 0, 1e30, 1e30, 0, 0, 1e30, 1e30); // Indexes are floats, integer addition doesn't come until AVX2 __m256 idx = _mm256_set_ps(3,2,0,0,1,0,0,0); __m256 idxinc = _mm256_set_ps(4,4,0,0,4,4,0,0); // Process 4 y vectors at a time for(int i = 0; i < n; i += 4) { __m256 y = _mm256_load_ps(&yp[i][0]); for(int j = 0; j < 4; j++) { // Compute difference of vectors __m256 diff = _mm256_sub_ps(x, y); // Square each component __m256 square = _mm256_mul_ps(diff, diff); // Add pairs. Results are in floats 0,1,4,5 __m256 sum = _mm256_hadd_ps(square, square); // Set remaining slots using indexes sum = _mm256_blend_ps(sum, idx, 0b11001100); // Compare with best distance so far __m256 cmp = _mm256_cmp_ps(sum, best, _CMP_LT_OQ); // Duplicate comparison masks to index slots cmp = _mm256_permute_ps(cmp, 0b01000100); // Take new distance/index if it is smaller best = _mm256_blendv_ps(best, sum, cmp); // Shuffle b & idx vectors around. This trickery // puts all 4 b vectors in all 4 slots. if(j == 0 || j == 2) { // abcd -> cdab y = _mm256_permute2f128_pd(y, y, 0x01); idx = _mm256_permute2f128_pd(idx, idx, 0x01); } else { // abcd -> badc y = _mm256_permute_pd(y, 0b0101); idx = _mm256_permute_ps(idx, 0b10110000); } } idx = _mm256_add_ps(idx, idxinc); } // Extract results best = _mm256_cvtps_epi32(best); r[0] = _mm256_extract_epi32(best, 2); r[1] = _mm256_extract_epi32(best, 3); r[2] = _mm256_extract_epi32(best, 6); r[3] = _mm256_extract_epi32(best, 7); } // number of threads #define T 4 // N must be a multiple of 4*T #define N 10000 vector a[N] __attribute__((aligned(32))); vector b[N] __attribute__((aligned(32))); int min[N]; float dist(vector x, vector y) { float a = x[0]-y[0]; float b = x[1]-y[1]; return a*a+b*b; } int mindist_test(vector x, vector *y, int n) { float best = dist(x, y[0]); int bestidx = 0; for(int i = 1; i < n; i++) { float d = dist(x, y[i]); if(best > d) { best = d; bestidx = i; } } return bestidx; } void thr(int t) { for(int i = 0; i < N/T; i += 4) { mindist(&a[N/T*t+i], b, N, &min[N/T*t+i]); } } int main(int argc, char *argv[]) { // Initialize for(int i = 0; i < N; i++) { a[i][0] = rand() / (RAND_MAX/1000000.); a[i][1] = rand() / (RAND_MAX/1000000.); b[i][0] = rand() / (RAND_MAX/1000000.); b[i][1] = rand() / (RAND_MAX/1000000.); } // Run & time double start = mytime(); std::thread* threads[T]; for(int t = 0; t < T; t++) { threads[t] = new std::thread(thr, t); } for(int t = 0; t < T; t++) { threads[t]->join(); } double stop = mytime(); printf("time: %f\n", stop - start); // Check results for(int i = 0; i < N; i++) { int j = min[i]; int k = mindist_test(a[i], b, N); if(dist(a[i], b[j]) != dist(a[i], b[k])) { printf("BAD %d: %d %f %f\n", i, j, dist(a[i], b[j]), dist(a[i], b[k])); } } } ``` Compiled on my mac with ``` clang++ -O3 -mavx -std=c++11 -stdlib=libc++ avx4.cc -o avx4 ``` [Answer] ## R ``` N=nrow(SetA) for (i in 1:N){ vec=with(SetB,(SetA[i,x]-x)^2+(SetA[i,y]-y)^2) indexVec[i,ind:=which.min(vec)] } ``` **18 seconds for 10k rows** I am quite sure that it should be possible to make this much more efficient [Answer] ## C++11 (Naive approach with O(N^2) complexity. With a kd-tree it could probably be improved a lot. I'll work on it in the future) Okay, this C++ code should work a lot better than the matlab code posted below. In my computer it runs in ~0.5s for the 10k values. I've compiled it in VS, but it should work in linux, although I don't know the command line code to compile it properly, I guess it will need `-std=c++11` and maybe `-pthread` for the threading. As for the loading from file, I would need the format of the loaded file to prepare it for you. As it is right now, it creates a rng and fills the two arrays with random floats. ``` #include <chrono> #include <iostream> #include <limits> #include <thread> #include <random> #define ROWS 10000 #define sqdiff(a,b) (((b)-(a))*((b)-(a))) void NN(float a[][2], float b[][2], int c[], int length) { for (int i = 0; i < length; ++i) { int k = 0; float m = std::numeric_limits<float>::infinity(); float x = a[i][0]; float y = a[i][1]; for (int j = 0; j < ROWS; j += 4) { { float d = sqdiff(x, b[j][0]) + sqdiff(y, b[j][1]); if (d < m) k = j; } { float d = sqdiff(x, b[j+1][0]) + sqdiff(y, b[j+1][1]); if (d < m) k = j; } { float d = sqdiff(x, b[j+2][0]) + sqdiff(y, b[j+2][1]); if (d < m) k = j; } { float d = sqdiff(x, b[j+3][0]) + sqdiff(y, b[j+3][1]); if (d < m) k = j; } } c[i] = k; } } void InitializeRandomArray(float* a, int length) { std::default_random_engine generator; std::uniform_real_distribution<float> distribution; for (int i = 0; i < length; ++i) { a[i] = distribution(generator); } } int main(int argc, char** argv) { float a[ROWS][2]; float b[ROWS][2]; int c[ROWS]; std::thread* threads[4]; // Initialization InitializeRandomArray((float*)a, ROWS*2); InitializeRandomArray((float*)b, ROWS*2); // Time counter std::chrono::time_point<std::chrono::system_clock> start, end; start = std::chrono::system_clock::now(); // Computation for (int t = 0; t < 4; ++t) { threads[t] = new std::thread(NN, &(a[ROWS/4*t]), b, &(c[ROWS/4*t]), ROWS/4); } // Thread joining for (int t = 0; t < 4; ++t) { threads[t]->join(); delete threads[t]; } // Output of time used end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end - start; std::cout << "elapsed time: " << elapsed_seconds.count() << "s" << std::endl; return 0; } ``` --- ## Matlab This version runs as slow as a turtle, it took about 6s for 1k arrays in octave. In matlab i believe it may run faster, but can't check it right now as I don't have it installed in this computer. ``` function [c] = NN(a, b) c = zeros(size(a,1),1); for i=1:size(a,1) [_,c(i)] = min(sum((b-a(i,:)).^2, 2)); end end ``` I'm sure this can be made very optimized in C but I lack the time to implement it right now. ]
[Question] [ Given two inputs, a distance \$d\$ and a number \$n\$ output a list of \$n\$ random colors which each have distance \$d\$ from the previous. ## Background A [random walk](https://en.wikipedia.org/wiki/Random_walk) is a path which is defined by choosing a random direction and (usually) fixed distance to go at each step. We will be taking a random walk through the RGB color space using [Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance) as our metric. ## The challenge For this challenge you will take two inputs, \$n\$ and \$d\$. Let \$n\$ be the number of colors to output, this will always be an integer \$1 \leq n\$, and \$d\$ be the distance between consecutive elements, which will always be \$0 \leq d \leq 128\$. You may additionally assume that \$d\$ is an integer. For each consecutive pair of elements \$(r\_1, g\_1, b\_1), (r\_2, g\_2, b\_2)\$ of the \$n\$ element sequence output, it must be the case that all values are between 0 and 255 inclusive (or \$[0,256)\$ for floats), and the distance between elements must be within 1 of d, that is \$|\sqrt{(r\_1-r\_2)^2+(g\_1-g\_2)^2+(b\_1-b\_2)^2} - d| < 1\$. This should allow one to restrict their output to integers if they so choose. The walk need not be uniform, but it does need to be random. Specifically, there should be a non-zero chance of each step going in any direction which stays in bounds (within a distance 1 error tolerance). The starting point of the walk should be random as well. Standard i/o rules apply, input and output can be in any reasonable format. Graphical output is allowed (and encouraged, though I doubt it will be golfy to do so) so long as the order of the sequence is clear. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. ## Test cases For these test cases input is in the order \$n,d\$ and output is (r, g, b) as integers. These are some possible results. ``` 5, 5 -> (81, 60, 243), (81, 57, 239), (76, 60, 240), (80, 62, 241), (84, 60, 243) 4, 10 -> (163, 89, 77), (162, 83, 85), (166, 75, 79), (166, 82, 87) 4, 50 -> (212, 36, 232), (247, 1, 239), (220, 44, 243), (217, 81, 209) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 96 bytes ``` (d=#2;r={0,255};NestList[⌊RandomPoint[Sphere[#,d],1,{r,r,r}][[1]]⌋&,RandomInteger[r,3],#1])& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7XyPFVtnIusi22kDHyNS01tovtbjEJ7O4JPpRT1dQYl5Kfm5AfmZeSXRwQUZqUWq0sk5KrI6hTnWRDhDWxkZHG8bGPurpVtOBqPXMK0lNTy2KLtIxjtVRNozVVPsfUATU7pAWbapjGvsfAA "Wolfram Language (Mathematica) – Try It Online") Graphical output is possible with Mathematica desktop. If the above function named `g`: [![enter image description here](https://i.stack.imgur.com/s92Ve.jpg)](https://i.stack.imgur.com/s92Ve.jpg) And just for fun: [![enter image description here](https://i.stack.imgur.com/lz8U3.jpg)](https://i.stack.imgur.com/lz8U3.jpg) [Answer] # [JavaScript (V8)](https://v8.dev/), 105 bytes Expects `(n)(d)`. Prints tuples of 3 floats. ``` n=>d=>{for(b=[m=Math,0,0];~~(m.hypot(...b.map((v,i)=>v-=a[i]=m.random()*256,a=[]))-d)||print(b=a)|--n;);} ``` [Try it online!](https://tio.run/##ZYxBCsIwEADvvsLjriQhihUhbH/gC0oPW0tohKQhhoBY@/VY8CjMaQbmwYWf9@RiluVaLdVA7Ujt284JBuo83ThPQgvdm3UFr6ZXnDMopQblOQIU4ZDaIok715NXicM4e8DDqbkIpq5HlCMuS0wu5O3IuEgZDJpPtdDghtn/GpqdhTPCUf@pRmP9Ag "JavaScript (V8) – Try It Online") ### Graphical output This snippet generates a graphical rendering of `f(4)(50)`. ``` f= n=>d=>{for(b=[m=Math,0,0];~~(m.hypot(...b.map((v,i)=>v-=a[i]=m.random()*256,a=[]))-d)||print(b=a)|--n;);} i = 0; print = ([r, g, b]) => document.getElementsByTagName("div")[i++].style.backgroundColor = `rgb(${r},${g},${b})`; f(4)(50) ``` ``` div { float: left; width: 32px; height: 32px; margin-right: 8px; } ``` ``` <div></div><div></div><div></div><div></div> ``` ### Commented ``` n => // outer function taking n d => { // inner function taking d for( // main loop: b = [ // initialize b[]: m = Math, // m = alias for Math 0, // by inserting this NaN'ish value into 0 // the initial b[], we force the first ]; // random RGB tuple to be accepted ~~( // force to integer: m.hypot(... // compute the Euclidean distance: b.map((v, i) => // for each value v at index i in b[]: v -= // subtract a[i] from v a[i] = // where a[i] is set to m.random() // a random float in [0, 256[ * 256, // a = [] // start with a[] = [] ) // end of map() ) - d // subtract d from the Euclidean distance ) || // if the result is within ]-1,1[: print(b = a) // print a[], update b[] to a[] | --n; // and decrement n (stop if it's 0) ); // end of loop } // ``` [Answer] # [Python](https://www.python.org), ~~123~~ ~~107~~ ~~111~~ 108 bytes *-16 bytes from @xnor by using math.dist +4 bytes from @Arnauld from correctly meeting the spec -3 bytes from @The Thonnu* ``` import os,math def f(n,d,r=os.urandom): X=r(3) while n: if-1<math.dist(x:=r(3),X)-d<1:print(*x);X=x;n-=1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY5LCsMgGIT3nsKlFg1ICRQT7-E2YEQhPtA_xJ6lm2yaO_U2fYQuZ_iGbx5HvoNLcd-fK1h-ey0-5FQAp8rCBA6Z2WJLIjOsqFS7tUzRpEAlwloVcqUIb84vM46fBnvLxfiddcZXIE3-EKYpN6OQufgI5NLooFUbIlfidB6W9KynZ_gfeQM) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 44 bytes ``` NθNηW⊙Φ⊟Eθ⊞OυE³‽²⁵⁶λ‹¹↔⁻η₂ΣEκX⁻μ§§υλν²≔⟦⟧υIυ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY_BSgNBDIbvPkXoKQNT0JaK0NMiCAWrS3ssPcxuR2dwdmZ3MrH6LF56qOgr-RC-g7OuBQMh_D_Jl-TtszYq1kG5w-Gd08P46ut74VtOd9xUOmIn5mf_tcl6b6zTgIV_xRvrUnbL0OJStdhJKJnMfaujSiEiS-jtqYSV8rvQ4GR2KfqQ4HLeaiK8kFBUFBwnjUvrmdBIWHesol6FkHDNzS_7KbPDPi8bmpo8lhZ-p1_wVHmg-h4_EaeAgsg-etxsJXC-vozWJ7xWlJCFmB-pqunv9Y_NaPzsRtvjFGbng_UD) Link is to verbose version of code. Explanation: Simply generates `n` sets of random colours until it finds a set that meets the distance criterion, which it then outputs. Although that algorithm finishes with 100% probability, it's inordinately slow and unusable for `n>3`, so here's a 52-byte alternative program that randomly generates each colour in turn until it finds one that meets the distance criterion: ``` NθNηW‹Lυθ«⊞υE³‽²⁵⁶¿∧⊖Lυ‹¹↔⁻η₂ΣE§υ±²X⁻κ§§υ±¹λ²≔⊟υι»Iυ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZZDBSgMxFEVx2fmKUDcvkIKtVgpdDbop2DK0S3GRmXmdBDPJzCSxgvglbrqo6Df5NSbtgEKzeHDDvefd5OO7ELwrDFf7_ad329Hs5-JyoRvvVr7OsYOWzpP_WgS9E1IhgQe0NgxdOQGeMtJSSt6SQeZt0IwseQPXjKy5Lk0Nk-ktpSE7kFsCqS7hHosOa9QOyz9IoBypY0bS3BrlHcJSam9BMLJpPe9wbYyDja8h8lO30CW-xnUrrHhwTyIjM7tQ9RR8Dqjede4eR7eKI-T6Q1JrZaUhM83xWTK0fk-yTmoHd9y6WHN-sHlh-x_7ehyOXtTw6XBDplenq18) Link is to verbose version of code. ]
[Question] [ You've [gotten out of Earth's gravity well](https://codegolf.stackexchange.com/q/252264/114332) - good for you! However, you're feeling a bit uncomfortable in zero-gravity, and you want to replicate 1 \$g\$ of force in a centrifuge. Use the [equation for force in a centrifuge](https://en.wikipedia.org/wiki/Centrifuge#Mathematical_description): $$\text{RCF} = \frac{r\_\text{m} \, \left(\frac{2 \pi N\_\text{RPM}}{60}\right)^2}{g}$$ Where * \$\text{RCF}\$ is "relative centrifugal force", or the force relative to 1 \$g\$; in this case we want this to be \$1\$. * \$r\_\text{m}\$ is the radius of the centrifuge in meters. You can take this, or a similar quantity - for example, taking it in millimeters. * \$N\_\text{RPM}\$ is the rotational speed in revolutions per minute. You're going to output this. * \$g\$ is the [local gravitational field of Earth](https://en.wikipedia.org/wiki/Gravity_of_Earth) - for this challenge, use the standard value of \$9.80665\;\text{m}/\text{s}^2\$. In alternate form, when \$\text{RCF} = 1\$: $$N\_\text{RPM} = \dfrac{60\sqrt{\dfrac{g}{r\_\text{m}}}}{2\pi}.$$ To clarify: take the radius of the centrifuge, output rotational speed in RPMs, with precision to 6 significant digits. Scoring is standard for [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Test cases (calculated using [SpinCalc](https://www.artificial-gravity.com/sw/SpinCalc/)): ``` 1 -> 29.904167719726267 10 -> 9.456528152601877 50 -> 4.229087956071661 87 -> 3.206063305621029 100 -> 2.9904167719726273 103 -> 2.946545199338184 167 -> 2.314053973112157 200 -> 2.1145439780358304 224 -> 1.9980562507828685 250 -> 1.8913056305203755 264 -> 1.8404742955585696 300 -> 1.726517928287568 328 -> 1.651181438643768 400 -> 1.4952083859863137 409 -> 1.4786659280153986 1000 -> 0.9456528152601877 2000 -> 0.6686775183186282 10000 -> 0.2990416771972627 ``` [Answer] # [Python](https://www.python.org), 24 bytes ``` lambda r:29.904167/r**.5 ``` ## [Attempt This Online!](https://ato.pxeger.com/run?1=XZJNbtswEIWBLnkKQSspsFXODOeHAdxVb9F04aARKkCxDFtd5CzZGCjaM_QsPU2HlhygWQgU5uN7M3zk6-_jy_x9Olx-9ruHXz_mfmt_xv3z47d9dbrH3OWYQPTj6e6u4wX__fB5fjrPu7quodp-qt42KWRFQdEAsYDcJRZGA0aJYKqBr_XUIeZomlmigggE01KnDqNEIYosCBGz-1wF2OX_Oig5oZUk4cSQM5GBpeC7FkCQIlNWAkBgDXjzAkicHFgkNoopIKZCwLtYac1RDU2MAy4DQ2cZylT-YSRlJ7JqLMWkCTMzG0uWQHHV-KQMmtG9lMUCoS3Ay2CQyCSROkg3Rcpub2ScTQhIneSVqImwe0XwM5mUZK6i6AG8CxnfkIh5ZgxGYOJzXFUrw3eR-m2GYap21ZdxOM_N8_7Y9OO0nzdjdz6Ow9zURVe3bdtPp2qshkNVXsENPhzq9msoaNhMBQ7Tfaiq42k4zI2XNn0ztJv947kpP9upbZfHdLks6z8) ## Explanation The expression we're trying to calculate is $$N\_\text{RPM} = \dfrac{60\sqrt{\dfrac{g}{r\_\text{m}}}}{2\pi}.$$ If we rearrange terms, we can turn this into $$N\_\text{RPM} = \dfrac{60\dfrac{\sqrt{g}}{\sqrt{r\_\text{m}}}}{2\pi} = \dfrac{60\sqrt{g}}{2\pi\sqrt{r\_\text{m}}} = (\dfrac{60\sqrt{g}}{2\pi})\frac{1}{\sqrt{r\_\text{m}}}$$ Since we know \$g = 9.80665\$ (it's constant), we can calculate the value of the \$(\dfrac{60\sqrt{g}}{2\pi})\$ term, getting approximately \$29.904167\$. In other words, $$N\_\text{RPM} \approx 29.904167\frac{1}{\sqrt{r\_\text{m}}}$$ [Answer] ## [Python](https://python.org), ~~53~~ ~~52~~ ~~41~~ 39 bytes ``` lambda a:30*(9.80665/a)**0.5/3.14519265 ``` [Try it online!](https://tio.run/##K6gsycjPM/5fYRvzPycxNyklUSHRythAS8NSz8LAzMxUP1FTS8tAz1TfWM/QxNTQ0sjM9H9BUWZeiUaFhqGmJhecbYDEMQVy/gMA "Python 3 – Try It Online") * -2 bytes thanks to The Thonnu [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), ~~16~~ ~~15~~ 13 bytes ``` 8825.985÷½÷ØP ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FhstLIxM9SwtTA9vP7T38PbDMwKWFCclF0NlYaoA) This is my first Jelly answer, so it can almost certainly be golfed. * -1 byte thanks to MehanAlavi [Answer] # [Go](https://go.dev), 64 bytes ``` import."math" func f(r float64)float64{return 29.904167/Sqrt(r)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ddJNatwwFAdw6HJOYWY1htR933ra9QiFnsCEOB2a8aTGswo5STZDoYfoUdoT9BiVJSejKXRhBOan_3t60sv3--P552N_-7W_v2sO_X7c7A-Px2nutsNh3v44zcN7__Xx9d-hn79sN8NpvG2G3dQMD8d-NmnX9Wm6m0_T2FDsIgha-PD52zTvpva55Px-9ydvXcrs2uZp82naj_PDuMObFIftzWVnwBjIyEJ7QZAVJBY7UVNyVDJAD5XSrHRR0hFF8BDVIKAZXpSHRXlIijsCA2MGNUKgWFdcSy5p1MWr1gLXkAvkAsVUFGNkdnSpnOW6acmOUUA5BkYk1OoQVArTWhhRVJJzYHWGKpBIMiRJEFOHvpxCITi5uVawzIXyYLDziMt500fAQWtoJdFKogtIEIqq6mrRLpBLjwwlMY1EMURKhYOaV448O_LskkJHYTfhUDspebLmSUytObtGN0YONYwFxgKDm2kqDJhm6XZ1fa_3t2RCupf_vRqCt4kXaubpphWd0S0d6jr1LbZg-udltJv1wZ_PZf0L) [Answer] # [Raku](https://raku.org/), 16 bytes ``` 29.904167/*.sqrt ``` [Try it online!](https://tio.run/##HYu9DoMwEINfxUKIoQNcLtdAxM@roA5kompJWBDqs4ejg@XPsv1d4ury@0AVMGb2tScxrm0eddrinnuk14GinDFOOAPK@VcgfCIGA0N4ErpWgVQW@gMrMwtYK3YCq9lyB1EX8veW7hH9iaZ8AQ "Perl 6 – Try It Online") I searched in vain for some short combination of Unicode characters whose numerical values could be combined in some way to get a number very close to the constant factor here. Oh well! [Answer] # [Factor](https://factorcode.org/), 21 bytes ``` [ -.5 ^ 29.904167 * ] ``` [Try it online!](https://tio.run/##bdLLSsNQEAbgfZ/iuBUa5n5RcCtu3IgrUSilRRfW2saFiM9eT5u0iWIggZCPmf/MZDmbt2@b3f3dze31RXmdtc/N8mM1b1/eVtvDa1lvFm37ud68rNqyXbx/LFbzxbZcTiZfk1Iv3D/KWZleFcomQdDcMZ2MzDsBJ5GNqCkFKhlgeAd0ANIQJYSnGjia4QGEnwA3BAbGDGqEQNm3gFOIJn@FcO4Fj4SYimImc2BIB8wHwCignM6IhNqlpHEPRFGpIIA1GLoSRHIUWFPEPqKCB4WFdkJhEJG4P0W9Cdi1FzaqEQLiQqmqoZZ2EAyjGvWEip5Ue7hadIBiAPUzBgqHCXsPZFxBsrYPDs0wRvZe5Eh4mGntAVhnEnacOPQC6jz/2SqNhVnUjSgGY1hNe6oBR0F/1jb53j2UaaPlafivynl53L3O1qXZ/QA "Factor – Try It Online") Port of 97.100.97.109's [Python answer](https://codegolf.stackexchange.com/a/252634/97916). [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes ``` 29.9041677?√/ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiMjkuOTA0MTY3Nz/iiJovIiwiIiwiMVxuMTBcbjUwIl0=) [Answer] # x86 32-bit machine code, 16 bytes ``` 68 98 90 5F 44 D9 04 24 D8 74 24 08 D9 FA 58 C3 ``` [Try it online!](https://tio.run/##ZVJNj5swED3jXzGlioQDQQ4fWZJsetpjq1bRSq2UzYHYhlgidgokJYry10vHdLdq0wPDmzfPM48xfFJy3vfvlebVSUh4bFqhTLj/QP6hKrW752qlS8uRyugShDntKgmFV1Qmb0HTJZyNEiC18OiS5M0BPFi7HgnLyuzyCgpSLJxwd2klsG6WESdssCG2yOZJGKXzKHlgbJ5OszROiVNUAp6@fl4/wZfnNWxkc9wiKdT5jgUfMltpvtctcY7mCDLviFPLlqCTBaEuoBuidAuHXGnPgrwueQB8n9cwHmNypuRKHG5004Ktt3yzhRVcpwFMWQApPtmDxcyGGMMM08imUZRgsIpohii2XBxlASQWJWw@HGODmv3G7LYkjh3T4YwJzrjgmyH3Y69wG57vd/AI04wSxzniztvCc0epglE4zT4WL9oNrMFuG@DuB0DxA/8oX/SnnO@VlsCNkAvX1rrXAcLA9U0HIxZ9w1aXleeddKNKLcWwkjEt6Kbz/S1d3uDV0n8KtPhuBfc0LvxvK@CNFNj7bujgurNFvJhTra2dG@n7n7yo8rLpJ4c4woA/zQrPyuoX "C (gcc) – Try It Online") Following the `cdecl` calling convention, this takes \$r\_{\mathrm{m}}\$ on the stack and returns \$N\_{\mathrm{RPM}}\$ on the FPU register stack. In assembly: ``` f: .byte 0x68 # Push a 4-byte value onto the stack: .single 894.259247009518535 # this value, which equals (60/2π)²·g. fld DWORD PTR [esp] # Put that value onto the FPU register stack. fdiv DWORD PTR [esp + 8] # Divide it by the value given. fsqrt # Take the square root. pop eax # Pop the value added to the stack. ret # Return. ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 13 bytes ``` 29.9041677%%: ``` [Try it online!](https://ngn.codeberg.page/k#eJxl0TtWw1AMBNA+q0iTEqPRd5SCjXBos/8loGeSOEDh6nr0e7er9tbiyKrL5Xo63T7xdX4/v32cD0CXpmYtlLv25pGhRGgKWAvjgb6ptrA6UgqZGGTd0TaVlDSTSIVo72UfUd36V9eyne1gz/BAtxlBX5r1VINLWJcBilhD6UtpwMNHKRY0WWFVvzOmM9dMIUVlMhY/d8LGxpp5PhWr2DmPNF28XDsiGNk5bHKkZ5lAtU7piuRS5VPHQLgx3WpXf8l6T0sao5kGq5374GJmTGnB7M78OegjLnOyf0+lr57JuXeABuYMeM8fP+ifN/kGRsh0oA==) Dead simple. Doesn't display correctly with all numbers correct up to all precision, but that isn't a requirement anyway. Explanation: ``` 29.9041677%%: Main program. Takes implicit input : Takes input from the right side % Square root % Divide with 29.9041677 Literal number "29.9041677" ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes ``` I∕₂∕⁸⁸²⁵·⁹⁸⁵N≕math.pi ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwyWzLDMlVSO4sDSxKDUoPx8uYmFhZKpnaWGqo@CZV1Ba4leam5RapKGpqamj4J5aEpZYlJmYlJOqoZSbWJKhV5CpBJTRtP7/39DA4L9uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Calculates the answer as accurately as possible. Explanation: The constant `8825.985` arises from the following calculation: $$ \frac{60\sqrt{\frac{g}{r\_\text{m}}}}{2\pi}=\frac{30\sqrt{\frac{g}{r\_\text{m}}}}\pi=\frac{\sqrt{\frac{900g}{r\_\text{m}}}}\pi $$ ``` ⁸⁸²⁵·⁹⁸⁵ Literal number `8825.985` ∕ Divided by N Input number ₂ Take the square root ∕ Divided by ≕math.pi Python variable `math.pi` I Cast to string Implicitly print ``` 13 bytes by porting @adam's approximation: ``` I∕²⁹·⁹⁰⁴¹⁶⁷₂N ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwyWzLDMlVcPIUs/SwMTQzFxHIbiwNLEoNSg/v0TDM6@gtMSvNDcptUhDEwSs//83NDD4r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` tz•1Íãǝ•*6°/ ``` Port of [*@97.100.97.109*'s Python answer](https://codegolf.stackexchange.com/a/252634/52210). [Try it online](https://tio.run/##yy9OTMpM/f@/pOpRwyLDw72HFx@fC2RpmR3aoP//v6EBEAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/kqpHDYsMD/ceXnx8LpClZXZog/5/nf/RhjqGBjqmBjoW5kCGARAb6xiamesYAdlGRiY6RkApIzMTHWMg39jIQscESJsYWILUGoAUGYBZBrEA). A port of [the Jelly answer](https://codegolf.stackexchange.com/a/252624/52210) would be 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage) longer: ``` •‡»µ•₄/I/tžq/ ``` [Try it online](https://tio.run/##yy9OTMpM/f//UcOiRw0LD@0@tBXEamrR99QvObqvUP//f0MDIAAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/Rw2LHjUsPLT70FYQq6lFv1K/5Oi@Qv3/Ov@jDXUMDXRMDXQszIEMAyA21jE0M9cxArKNjEx0jIBSRmYmOsZAvrGRhY4JkDYxsASpNQApMgCzDGIB). **Explanation:** ``` t # Take the square root of the (implicit) input z # Calculate 1 divided by this value •1Íãǝ•* # Multiply it by compressed integer 29904167 6°/ # Divide it by 1000000 (6**10) # (after which the result is output implicitly) •‡»µ• # Push compressed integer 8825985 ₄/ # Divide it by 1000: 8825.985 I/ # Divide it by the input t # Take the square root of that žq/ # Divide it by PI (3.141592653589793) # (after which the result is output implicitly) ``` [See this 05AB1E answer of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•1Íãǝ•` is `29904167` and `•‡»µ•` is `8825985`. [Answer] # [Japt](https://github.com/ETHproductions/japt), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Port of the [Python solution](https://codegolf.stackexchange.com/a/252634/58974). ``` 29.904#§/U¬ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=MjkuOTA0I6cvVaw&input=MTAwMDA) ]
[Question] [ **(2 Jan 2018) Because of the winning criteria I am going to accept the Jelly answer, but I am also giving upvotes to all other answers which all use astounding methods as well** ## Introduction There are lots of challenges asking for a shortest program to calculate mathematical constants. I saw some with restrictions like banning the literals 3.14 and π etc. However, there seems no such challenges using the number of distinct characters as one of the criteria. ## The Challenge ~~Make a Plain PIE using the fewest kinds and least amount of ingredients but still yummy enough~~ Write a code that calculates π\*e to at least 10 decimal places, that uses as *FEW* distinct characters (and de facto numeric literal characters) and as short as possible. This challenge is not banning numeric literals; instead they are discouraged. Numeric literals are *seasonings* ;) ## Requirements * The code must be a full program receiving no inputs and outputting the result, or a function which can be called with no arguments either outputting or returning the result. Lambdas are allowed. * The result must start with `8.5397342226` and must be in a *numeric type*. There should only be one output/return in the main program/function. Sub-functions are allowed. ## Restrictions * String-to-number conversion functions *that trivially turn the string literal to a number it represents* are not allowed unless explicitly declared and implemented within the code. Also, *NO implicit conversions from strings to numbers*. + eg. `eval`, `Number()`, `parseInt()` and `"string" * 1` + Character-code functions and length functions like `ord`, `String.charCodeAt(n)` and `String.length` are allowed because they do not trivially convert the string into the corresponding number. * Use of the following built-ins are not allowed: + Mathematical constants, or any built-in functions that evaluates to those constants directly - eg. `Math.PI` in JS, `žs` in 05AB1E (because it evaluates to π directly) + Trigonometric functions and the exponential function, unless explicitly defined and implemented in the code. - eg. `Math.atan` and `Math.exp` in JS - Built-in power functions and exponentiation operators (eg. \*\* or ^) are allowed, given that they receive 2 arguments/operands (WLOG `a` and `b`) and returns ab * The length of each run of numeric literal used must not be longer than 5 (eg. `12345` allowed (but not encouraged), but `123456` is not allowed). * Standard loopholes apply. ## Scoring * The scoring is divided into three parts: + **Distinctness**: Scored by counting the number of distinct characters used. Uppercase and lowercase are counted separately. However, the following characters must each be counted as 10 characters: - Hexadecimal digits: `0123456789abcdefABCDEF` - Decimal points: `.` - Any other single characters that may be used as numeric literals (applicable in golfing languages) + **Size**: Scored by the length of the code in bytes. + **Accuracy**: Scored by the number of correct digits counting from the decimal point. Any digits after the first wrong digit are not counted. For fairness, a maximum of 15 digits are counted. The value of π\*e according to WolframAlpha is `8.539734222673567(06546...)`. * The total score is calculated by `(Distinctness * Size) / Accuracy` ## Winning Criteria The answer with the lowest score wins. If tied then the candidate answer which is posted earlier wins. For non-golfing languages, the score can be calculated using the following snippet (For some golfing languages, the snippet does not work since this checks for UTF-8 length of the code only): ``` $(document).ready(() => { $("#calculate").on("click", () => { var count = {}; var distinct = 0; var nonnums = 0; var numerals = 0; var length = 0; for (const c of [...$("#code").val()]) { count[c]++; if (c.charCodeAt(0) <= 0x7F) length += 1; else if (c.charCodeAt(0) <= 0x3FF) length += 2; else if (c.charCodeAt(0) >= 0xD800 && c.charCodeAt(0) <= 0xDFFF) length += 4; else length += 3; } for (const c in count) { if ("0123456789abcdefABCDEF.".indexOf(c) == -1) { nonnums += 1; distinct += 1; } else { numerals += 1; distinct += 10; } } var output = $("#output").val(); var match = /^8\.(5397342226(7(3(5(67?)?)?)?)?)/.exec(output); if (match == null) $("#result").html("The result does not have 10-digit accuracy!"); else { var accuracy = match[1].length; $("#result").html(` Size : ${length} bytes<br> Distinctness: ${distinct} (Numerals: ${numerals}, Non-numerals: ${nonnums})<br> Accuracy : ${accuracy} decimal places<br> Score : ${(distinct * length / accuracy).toFixed(2)} `); } }); }); ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h2>Calculator for Non-esoteric Programming Languages (BASIC-like, C-like, Python, Ruby, etc.)</h2> Code: <br><textarea cols=50 rows=10 id="code"></textarea><br> Output: <input id="output"><br> <input type="button" id="calculate" value="Calculate Score"> <pre id="result"></pre> ``` ## Example **Submission** # JavaScript(ES6), S=141, D=49, A=12, 575.75pt ``` (t=()=>{for(f=o=9/9;++o<9999;)f+=o**-(9>>9/9);return (f*(9*9+9))**(9/9/(9>>9/9))},u=()=>{for(f=o=r=9/9;++o<99;){f+=r;r/=o}return f})=>t()*u() ``` Output: `8.53973422267302` **Scoring** ``` Size : 141 bytes Distinctness: 49 (Numerals: 3 (use of "9", "e" and "f")), Non-numerals: 19) Accuracy : 12 decimal places Score : 575.75 ``` [Answer] # Mathematica, (18\*226)/15 = 271 only 1s ``` N[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+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+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+1+1+1+1+1+1+1+1+1+1+1+1] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y/aUBsN6mugEJjC2ljkUZRiMQ@JgcNowmaACU00oINTDwTG/g8oyswrcUj7DwA "Wolfram Language (Mathematica) – Try It Online") # Mathematica, 244 1s & 2s ``` N[2+2+2+2+1/(1+1/(1+1/(1+2+2+1/(1+1/(1+2+1/(1+1/(2+2+1/(12+1/(1+2+1/(2+1/(1+1/(1+2+2+1/(2+1/(12+1/(1+1/(1+1)))))))))))))))),12+2+2] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y/aSBsCDfU1DJEIVCEEGyZuhCRhhKkPRRGE0EQDOoZgi2P/BxRl5pU4pP0HAA "Wolfram Language (Mathematica) – Try It Online") [Answer] # Mathematica, 257.6 ``` N[2Integrate[Sqrt[1-n^2],{n,-1,1}],22]Sum[1/n!,{n,0,22}] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y/ayDOvJDW9KLEkNTq4sKgk2lA3L84oVqc6T0fXUMewNlbHyCg2uDQ32lA/TxEkagAUqI39H1CUmVfikPYfAA "Wolfram Language (Mathematica) – Try It Online") # Mathematica, 276 this is accurate to **4095 digits** ``` N[2Integrate[Sqrt[1-n^2],{n,-1,1}],2^12]Sum[1/n!,{n,0,2^12}] ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y/ayDOvJDW9KLEkNTq4sKgk2lA3L84oVqc6T0fXUMewNlbHKM7QKDa4NDfaUD9PESRuABaqjf0fUJSZV@KQ9h8A "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Imperative Tampio](https://github.com/fergusq/tampio), 2206.46 ``` K:lla on h:t.K:n z on riippuen siitä,onko sen h:iden määrä nolla,joko nolla tai sen ensimmäinen h lisättynä uuden K:n,jonka h:t ovat sen h:t toisesta alkaen eikä muuta,z:aan jaettuna kymmenellä.Kun iso sivu avautuu,se näyttää uuden K:n,jonka h:ita ovat kolme lisättynä viiteen,viisi,kolme,neljä lisättynä viiteen,7,kolme,neljä,kaksi,kaksi,kaksi,kuusi,7,kolme,viisi ja 7 eikä muuta,z:n. ``` > > K:lla **on** h:t.K:n z **on** **riippuen** **siitä**,**onko** sen h:iden määrä `nolla`,**joko** `nolla` **tai** sen `ensimmäinen` h **lisättynä** **uuden** K:n,**jonka** h:t **ovat** sen h:t `toisesta` **alkaen** **eikä** **muuta**,z:aan **jaettuna** `kymmenellä`.**Kun** iso sivu *avautuu*,se *näyttää* **uuden** K:n,**jonka** h:ita **ovat** `kolme` **lisättynä** `viiteen`,`viisi`,`kolme`,`neljä` **lisättynä** `viiteen`,`7`,`kolme`,`neljä`,`kaksi`,`kaksi`,`kaksi`,`kuusi`,`7`,`kolme`,`viisi` **ja** `7` **eikä** **muuta**,z:n. > > > [Online version](http://iikka.kapsi.fi/tampio/pie.html) Tampio has an advantage that number literals can be written using letters instead of digits. I also noticed that the interpreter thinks that one-letter words are nouns, so I can use them as identifiers. Of course, this language is so verbose that it won't help it to win any challenge. Ungolfed: > > Listalla **on** alkiot. > > > Listan lukuarvo **on** > **riippuen** **siitä**, **onko** sen alkioiden määrä `nolla`, > > > * **joko** `nolla` > * **tai** sen `ensimmäinen` alkio **lisättynä** **uuden** listan, **jonka** alkiot **ovat** sen alkiot `toisesta` **alkaen** **eikä** **muuta**, lukuarvoon **jaettuna** `kymmenellä`. > > > **Kun** nykyinen sivu *avautuu*, > > > * se *näyttää* **uuden** listan, **jonka** alkioita **ovat** `8`,`5`,`3`,`9`,`7`,`3`,`4`,`2`,`2`,`2`,`6`,`7`,`3`,`5` **ja** `7` **eikä** **muuta**, lukuarvon. > > > [Answer] # APL, 6×124÷15 = 49.6 points ``` zz+zz+zz+zz+÷z+÷z+÷z+zz+zz+÷z+÷z+zz+÷z+÷zz+zz+÷zz+zz+zz+zz+zz+zz+÷z+zz+÷zz+÷z+÷z+zz+zz+÷zz+÷zz+zz+zz+zz+zz+zz+÷z+÷zz←z+z←⍴⍴⍬ ``` [Try it online!](https://ngn.github.io/apl/web/) (Paste in the code then hit Ctrl+Enter.) Assigns `1` to `z`, then abbreviates `z+z` to `zz`, and then approximates the [continued fraction of `πe`](https://www.wolframalpha.com/input/?i=continued+fraction+of+pi+*+e) as `8+1/(1+1/(1+1/(5+1/(1+1/(3+1/(1+1/(4+1/(10+1/(3+1/(2+1/(1+1/(5+1/(2+1/(12+1/(1+1/2)))))))))))))))` (inspired by Jenny\_mathy’s Mathematica answer). `1` is computed as `⍴⍴⍬`: the dimensions vector (`1`) of the dimensions vector (`0`) of the empty vector (`⍬`). Because of APL’s `÷` reciprocal operator and right-to-left grouping rules, this representation doesn’t even need parentheses. We use 6 distinct non-numeric symbols: `z+÷←⍴⍬` --- This code should work in any APL dialect; the only important thing is that there is one where * the answer is printed to 15 figures by default; * the glyphs are encoded as one byte each (i.e. source code is in some custom APL codepage, not UTF-8). Graham reports that [APL+Win](http://www.apl2000.com/) fits the bill. [Answer] # [Desmos](https://www.desmos.com/), 199 bytes, Score = 199\*(3\*10+22)/11 = 940.73 ``` h=g(\left\{\right\}+\left\{\right\})\int_{-\left\{\right\}}^{\left\{\right\}}\sqrt{\left\{\right\}-x^{\left\{\right\}+\left\{\right\}}}dx \int_{\left\{\right\}}^{g}\left\{\right\}/xdx~\left\{\right\} ``` [Try it on Desmos!](https://www.desmos.com/calculator/rs5sev9wif) Stores the result in variable `h`. Calculates the exact values of \$\pi\$ and \$e\$ using integrals, and multiplies them together. This should theoretically yield a perfect score of 0, but Desmos only displays values to a precision of 11 decimal digits. Also, this code does not use the characters `0123456789`, instead opting for strings of `\left\{\right\}`, which are condition-less piecewise functions that evaluate to 1. Equivalent equations: \$h=2g\int\_{-1}^{1}\sqrt{1-x^2}dx\$ (\$e\$ \* area of circle with radius 1) \$\int\_{1}^{g}\frac{1}{x}dx\sim1\$ (\$e\$ is the unique positive real value of \$c\$ such that \$\int\_{1}^{c}\frac{1}{x}dx=1\$; the \$\sim\$ tells Desmos that the equation is a regression, and therefore needs to solve for g) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 × 38 ÷ 10 = 41.8 ``` “Þẹjuụ’÷ȷ10 ``` [Try it online!](https://tio.run/##AR8A4P9qZWxsef//4oCcw57hurlqdeG7peKAmcO3yLcxMP// "Jelly – Try It Online") # Explanation ``` “Þẹjuụ’÷ȷ10 Main Link “Þẹjuụ’ 85397342226 ÷ Divided by ȷ10 1e10 ``` [Answer] # [Swift](https://swift.org), ~~116 \* 39 / 14 ≈ 323.14~~ 114 \* 39 / 14 ≈ 317.57 ``` print(2+2+2+2+1/(1+1/(1+1/(2+2+1+1/(1+1/(2+1+1/(1+1/(2+2+1/(12+1/(2+1+1/(2+1/(1+1/(2+2+1+1/(2+1/12.2)))))))))))))) ``` [Try it online!](https://tio.run/##Ky7PTCsx@f@/oCgzr0TDSBsCDfU1DOEEWACJhyYDZBshSRhh6gMJGRrpGWmigP//AQ) Uses a continued fraction to approximate π\*e to 14 decimal places [Answer] # [Pyt](https://github.com/mudkip201/pyt), ~~22\*73/11=146~~ ~~22\*72/11=144~~ ~~23\*53/11~~ 22\*39/11=78 ``` 1⁺1⁺⁺⁺⁺⁺^ř⁻Đ!⇹1⁺*⁺‼/Ʃ1⁺*1⁺⁺1⁺⁺⁺⁺*ř⁻!⅟Ʃ* ``` Uses approximations for π and e, respectively. Per the codepage (which is in the interpreter2 file), each character is one byte. Explanation (stuff in brackets is what is used from the stack): ``` 1⁺1⁺⁺⁺⁺⁺^ř⁻Đ!⇹1⁺*⁺‼/Ʃ1⁺* makes π 1⁺1⁺⁺⁺⁺⁺^ makes 64 (64)ř makes a list [1,2,...,64] ([1,...,64])⁻ subtracts one from each element in the list ([0,...,63])Đ duplicates list (on top of stack twice) ([0,...,63])! performs element-wise factorial ([...],[...])⇹ swaps top two items on the stack ([...])1⁺*⁺ doubles all values in list and adds one ([...])‼ element-wise double factorial ([...],[...])/ divides element-wise ([...])Ʃ sums all elements in the list (approximately π/2) (π/2)1⁺* doubles (yields π) 1⁺⁺1⁺⁺⁺⁺*ř⁻!⅟Ʃ 1⁺⁺1⁺⁺⁺⁺* makes 15 ř⁻ makes a list [0,1,...,14] ! Takes the factorial of each element in the list ⅟ Finds the multiplicative inverse of each element Ʃ Sums the list (e) (π,e)* multiplies (implicit print) ``` [Try it online!](https://tio.run/##K6gs@f/f8FHjLhBGRnFHZz5q3H1kguKj9p0gOS2QcMMe/WMrwTyochRdWmAtio9a5x9bqfX/PwA) ]
[Question] [ Your task today is to create a HTML page. This page, when opened in a browser, behaves as if the browser has a problem (hanging, crashing, network error, virus, etc.) * You **can** use all the HTML(5), CSS(3) and JavaScript features you want. * You **can't** use Flash or other plugins. * You **can't** provoke a real problem in the browser (for example, you can't make the browser hang with an infinite loop, or crash with a bug exploit, etc.), just make it *look like* there is a problem. Please post your source code and provide an URL to view your page, and precise on which browsers / devices it works (if specific). I recommend <http://www.c99.nl/> to host your page easily. This is a popularity contest, so the most upvoted answer wins! Thanks, and have fun! [Answer] ``` <html> <head> <title>Connecting...</title> </head> <body style="margin: 0px; overflow:hidden;"> <div style="position: relative;"> <div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; cursor:wait;"></div> <iframe src="http://www.wikipedia.com/" width="100%" height="100%" style="border: 0px;"> </iframe> </div> </body> </html> ``` <http://c99.nl/f/64943.html> [Answer] # Zombie Error <https://dl.dropboxusercontent.com/u/141246873/ZombieError/index.html> Note: It might take a few seconds to load due to the image file. The webpage consists of the below html, css and javascript as well as an image file zombie.png (graphics by Clint Bellanger [licensed CC-BY 3.0](https://creativecommons.org/licenses/by/3.0/)). Tested in google chrome v36, but I expect it will work in most browsers. ### Update: 26th Jul: Now removes zombies once they walk off the screen 28th Jul: You can now click on the zombies to blast them off the website HTML: ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Zombie Error</title> <link rel="stylesheet" href="app.css" type="text/css" /> <script src="zombie.js"></script> </head> <body style="margin: 0px;"> <div style="position: relative;"> <div style="margin: 0 auto; width:100%; height:100%;"> <iframe src="https://godaddy.com/" style="width: 100%; height: 100%; margin: 0; border-width: 0px;"></iframe> </div> </div> </body> </html> ``` CSS: ``` body { font-family: 'Segoe UI', sans-serif; } span { font-style: italic; } .zombie{ width: 78px; height: 78px; background-image: url('https://dl.dropboxusercontent.com/u/141246873/ZombieError/zombie.png'); background-position: left; background-position-x: 0px; background-position-y: 0px; position: absolute; left: 10px; top: 10px; } body{ overflow: hidden; } ``` Javascript: ``` var directionWest = 0; var directionNorth = 6; var directionEast = 4; var directionSouth = 2; var stateWalking = 0; var stateDying = 1; var stateDead = 2; var animWalk = { speed: 0.15, numFrames: 8, frames: [4, 5, 6, 7, 8, 9, 10, 11] } var animDying = { speed: 0.10, numFrames: 8, frames: [28, 29, 30, 31, 32, 33, 34, 35] } var spriteWidth = 128; var spriteHeight = 128; var spriteOffsetX = 25; var spriteOffsetY = 25; var spritesheetWidth = 4608; function Zombie(_id, _x, _y, _direction) { this.direction = _direction this.id = _id; this.pos = { x: _x, y: _y } this.anim = animWalk; this.animFrame = 0; this.animDelta = 0; this.speed = 30; this.state = stateWalking; this.corpseDelta = 0; return this; } Zombie.prototype.Update = function (delta) { if (this.state == stateDead) return; //update the animation frame this.animDelta += delta; if (this.animDelta >= this.anim.speed) { this.animDelta -= this.anim.speed; this.animFrame++; if (this.animFrame >= this.anim.numFrames) this.animFrame = 0; } //background-position-x var div = document.getElementById(this.id); div.style.backgroundPositionX = ((spritesheetWidth - (spriteWidth * this.anim.frames[this.animFrame])) - spriteOffsetX) + "px"; div.style.backgroundPositionY = ((spriteHeight * this.direction) - spriteOffsetY) + "px"; if (this.state == stateWalking) { //update position if (this.direction == directionEast) this.pos.x += (this.speed * delta); if (this.direction == directionWest) this.pos.x -= (this.speed * delta); if (this.direction == directionNorth) this.pos.y -= (this.speed * delta); if (this.direction == directionSouth) this.pos.y += (this.speed * delta); div.style.left = Math.floor(this.pos.x) + "px"; div.style.top = Math.floor(this.pos.y) + "px"; } else if (this.state == stateDying && this.animFrame == (this.anim.numFrames - 1)) { this.state = stateDead; } } var zombies = [] var nextZombieID = 0; function GetZombie(zombieID) { return zombies.filter(function (z) { return z.id == zombieID })[0]; } function ZombieClick(div) { var zombie = GetZombie(div.srcElement.id); if (zombie.state == stateWalking) { zombie.state = stateDying; zombie.animFrame = 0; zombie.animDelta = 0; zombie.anim = animDying; } } function NewZombie() { var x = 0; var y = 0; var direction = 0; var rand = Math.random(); if (rand < 0.25) { //spawn from left of screen x = spriteWidth * -1; y = (Math.random() * screen.height) - spriteHeight; direction = directionEast; } else if (rand < 0.5) { //spawn from right of screen x = screen.width; y = (Math.random() * screen.height) - spriteHeight; direction = directionWest; } else if (rand < 0.75) { //spawn from top of screen x = (Math.random() * screen.width) - spriteWidth; y = spriteWidth * -1; direction = directionSouth; } else { //spawn from bottom x = (Math.random() * screen.width) - spriteWidth; y = screen.height; direction = directionNorth; } //generate an id var id = nextZombieID; nextZombieID++; //create a div var div = document.createElement("div"); div.id = id; div.classList.add("zombie"); div.onclick = ZombieClick; document.body.appendChild(div); //create a zombie zombies.push(new Zombie(id, x, y, direction)); } var spawnRate = 1; var spawnDelta = 0; function spawnZombies(delta) { spawnDelta += delta; if (spawnDelta >= spawnRate) { spawnDelta -= spawnRate; NewZombie(); } } var corpseDuration = 3; function cleanupZombies(delta) { for (var i = zombies.length - 1; i >= 0 ; i--) { //if the zombie has walked off the screen, remove them if (zombies[i].pos.x < (spriteWidth * -2) || zombies[i].pos.x > screen.width + spriteWidth || zombies[i].pos.y < (spriteHeight * -2) || zombies[i].pos.y > screen.height + spriteHeight) { var element = document.getElementById(zombies[i].id); element.parentNode.removeChild(element); zombies.splice(i, 1); } } for (var i = zombies.length - 1; i >= 0 ; i--) { //if the zombie has died, remove their corpse after some time if (zombies[i].state == stateDead) { zombies[i].corpseDelta += delta; if (zombies[i].corpseDelta > corpseDuration) { var element = document.getElementById(zombies[i].id); element.parentNode.removeChild(element); zombies.splice(i, 1); } } } } var started = false; var main = function () { var now = Date.now(); var delta = now - then; if (started) { cleanupZombies(delta / 1000); spawnZombies(delta / 1000); for (var i in zombies) zombies[i].Update(delta / 1000); } then = now; setTimeout(main, 30); }; var then = Date.now(); setTimeout(main, 30); setTimeout(function () { alert("Error 8102: Unexpected zombie attack. Please stand by..."); started = true; }, 2000) ``` [Answer] ## Better don't mess with Bond villains [Enter Blofelds secret ambush...](http://c99.nl/f/64447.html) And in case you want to see the code: [jsfiddle](http://jsfiddle.net/5Gd4T/1/) > > After 3 seconds there will pop up a message, that the script isn't responding, but that's only an alert popup and not a real message from a hanging page. After 15 seconds there will be additional greetings from Blofeld. > > > [Answer] Redirect to `about:crash`, which shows the default crash screen on Chrome [won't work on modern versions of Chrome, Firefox, or other browsers]: ![enter image description here](https://i.stack.imgur.com/DjdCX.png) ``` <meta http-equiv="refresh" content="0; url=about:crash"> ``` It probably doesn't qualify as a "full HTML page", but it will be rendered correctly by Chrome. To try it, type this into the Chrome address bar: ``` data:text/html;base64,PG1ldGEgaHR0cC1lcXVpdj0icmVmcmVzaCIgY29udGVudD0iMDsgdXJsPWFib3V0OmNyYXNoIj4= ``` *I couldn't test this answer because I don't have a Chrome install handy, please remove this notice once you test it.* [Answer] # [Glitchy scroll](http://c99.nl/f/44808.html) No, that's not bad image compression. Unintended side effect from something else I was trying. Try it out with the link in the title; The page starts looking weird while you scroll, and the scroll should become very jittery after a while. I think you need font smoothing of some sort activated, but everyone has this nowadays, right? The screenshot is from Chrome on OS X. ![Imgur](https://i.stack.imgur.com/HxLSC.png) ### The jQuery code: ``` $( window ).scroll(function() { $('#main').clone().prependTo('body'); }); ``` [Answer] # HTML + CSS + JavaScript/jQuery/jQuery UI This simulates a Windows error dialog. (It drags, too!) Like all good error messages, it fulfills two main requirements: 1. It displays a cryptic error message meaning nothing to all but a few. 2. The buttons seem to do nothing when clicked except show the `wait` cursor. See it in action at <http://codepen.io/anon/pen/onbAi>. (JSFiddle was not loading jQuery UI well.) It should display reasonably well on all browsers. ``` <!DOCTYPE html><html> <head><style> body { font: 11px sans-serif; } #window { background-color: #ECE9D8; padding: 3px; width: 574px; margin: 20px auto 0 auto; -moz-user-select: -moz-none; -khtml-user-select: none; -webkit-user-select: none; -ms-user-select: none; user-select: none; } header { background-color: #1E74EF; background-image: -moz-linear-gradient(left, #003ac9 0%, #4492e5 100%); background-image: -webkit-linear-gradient(left, #003ac9 0%, #4492e5 100%); background-image: linear-gradient(to right, #003ac9 0%, #4492e5 100%); clear: both; padding: 3px; } p { margin-left: 60px; } h1 { font: bold 13px sans-serif; color: white; margin: 1px; } button { background-color: #ECE9D8; outline: none; cursor: inherit; } #close { float: right; font-size: 16px; font-weight: bold; padding: 0 2px; margin: 0; text-align: center; height: 18px; line-height: 16px; } #ok { width: 75px; height: 23px; margin: 0 auto; margin-bottom: 13px; display: block; } </style></head><body> <div id="window"> <header> <button id="close" title="Close">×</button> <h1><span id="browser"></span>Application Error</h1> </header> <p>The instruction at "</span>" referenced memory at "<span class="hex"></span>". The memory could not be "read".</p> <p>Click on OK to terminate the program</p> <button id="ok">OK</button> </div> <script src='//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'></script> <script src='//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js'></script> $('#window').draggable({handle:'header'}); function randomHex(){ return '0x'+(Math.floor(Math.random()*0xffffffff)).toString(16); } $('.hex').each(function(){ $(this).text(randomHex()); }); var reg = /(opera|chrome|safari|firefox|msie)/i, browser = navigator.userAgent.match(reg)[0].toLowerCase(); if(!browser){ browser = 'firefox'; } else if(browser == 'msie'){ browser = 'ie'; } $('#browser').text(browser + '.exe - '); $('button').click(function(){ $('html, body').css('cursor','wait'); }); </script> </body></html> ``` [Answer] ``` data:text/html, <meta http-equiv="refresh" content="0"><script>document.write("Error Code : " + (Math.floor(Math.random() * 10000) % 1000) + ". Description: Network connection error.")</script> ``` The error code keeps changing, and the computer goes noisy. [Answer] Simulates an lagging loading spinner <http://c99.nl/f/104794.html> Sourcecode: <http://jsfiddle.net/3QURA/2/> HTML: ``` <div id="loader" style=""> <br/> <div id="spinner">&nbsp;</div> <br/> <br/> Loading... </div> ``` CSS: ``` body,html { width:100%; height:100%; margin:0; color:white; } #spinner { background:transparent; width:100px; height:100px; left:calc(50% - 100px / 2); position:relative; -webkit-animation: load infinite 1s; -webkit-border-radius: 100%; border-right:white 8px solid; } @-webkit-keyframes load { 0% { -webkit-transform:rotate(0deg) } 100% { -webkit-transform:rotate(360deg) } } .paused { -webkit-animation-play-state:paused; } #loader { font-family:Helvetica Light, Helvetica Neue, Helvetica, Arial, sans-serif; left:0%; position:fixed; text-align:center; background:rgba(55,55,55,0.5); width:100%; height:100%; } ``` JavaScript and jQuery: ``` window.setInterval(update, 1000/2); function update() { window.setTimeout(function () { $("#spinner").addClass("paused"); },1000); window.setTimeout(function () { $("#spinner").removeClass("paused"); },1200); } ``` [Answer] ## [Chrome Crash Page](http://jsbin.com/serofe/1) Actual Link: **chrome://crash/** **HTML** ``` <!DOCTYPE html> <html> <head> <script src="//cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script> <meta charset="utf-8"> <title>JS Bin</title> </head> <body> <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEIAAABCCAQAAABJXchjAAAAjklEQVR4Xu3ZgQbAIAAG4d7/pbeJxJCOWf26DozSh0RWrg0aAESIEEEtxJ6E6ICZUXrTc7MQZID5pyFEiPiwAMQPNYiIpyBEAwIoWBOEAACwJhHhmfCeEEH17++DEPwRlI/giRAhoow7ANE2gchkBN8c4GMQNI6JRHhjiqitAOyEWPsXqkq2QSxNhAgR4269KKbHaOQ5OgAAAABJRU5ErkJggg==" alt="Crash"> <div>Aw, Shit!</div> <p>This page is really fucked up, run for the hills.</p> <button>Reload</button> <p>If it doesn't work, it's all your fault.</p> </body> </html> ``` **CSS** ``` html, button { user-select: none; cursor: wait; font-family: Calibri, Sans-serif; text-align: center; } body { padding-top: 120px; background: #212e3d; font-size: 80%; color: white; } button { font-family: Calibri, Sans-serif; padding: 5px 10px; } div { font-size: 140%; } ``` [Answer] I've tested this on my smartphone. I can't get it to load properly on c99.nl, though. Must be that obscure. It makes your browser look possessed with some sort of obscure virus affecting the loading bar. ``` <!DOCTYPE html> <script> window.location.href = document.location.href; </script> <title>Redirecting...</title> <h3>Redirecting...</h3> ``` ## Notes: 1. This can easily be tested locally by copying it into a plain text file, and the name or place doesn't matter beyond file extension. It is valid HTML5 + JavaScript (you can see for yourself [here](http://validator.w3.org/check)...only warning is missing `<meta charset=utf-8 />`). 2. Make sure that if you test it, especially on a mobile device, stop the loading loop first (same as cancelling a page load) before you exit, or it ***may crash***. (I learned this the hard way...) > > In case you hadn't noticed, it's continually redirecting to the same page. `window.location.href` and `document.location.href` are synonymous, so it's assigning the current location to its synonym. It could look like server lag or a browser hang, depending on the browser and largely it's caching mechanism. > > That last line is just for theme. > > > > > ]
[Question] [ **This question already has answers here**: [Golf the Subset-Sum Problem](/questions/8655/golf-the-subset-sum-problem) (15 answers) Closed 10 years ago. Given an integer array. You have to check whether it is possible to divide the array in two parts such that the sum of elements of one part is equal to the sum of the element of the other part.If it is possible print "YES" otherwise "NO". **Sample Input** ``` 4 3 5 5 3 ``` **Sample Output** ``` YES ``` **Explanation** ``` Array can be divided in two parts {4,3,3} and {5,5} ``` **Sample Input** ``` 1 3 ``` **Sample Output** ``` NO ``` **Sample Input** ``` 5 5 ``` **Sample Output** ``` YES ``` [Answer] # Ruby 98 ``` f=->a{s=a.inject :+;(1..a.count).any?{|i|a.combination(i).any?{|r|r.inject(:+)*2==s}}?'Yes':'No'} ``` [Answer] # Prolog Without proper output (**92** chars) ``` s(A):-s(A,0,0). s([],B,B). s([H|T],B,C):-D is B+H,s(T,D,C). s([H|T],B,C):-D is C+H,s(T,B,D). ``` With proper output (**121** chars) ``` s(A):-(s(A,0,0),print('YES'),!;print('NO')). s([],B,B). s([H|T],B,C):-D is B+H,s(T,D,C). s([H|T],B,C):-D is C+H,s(T,B,D). ``` To query the rules: ``` s([4,3,5,5,3]) s([1,3]) ``` [Answer] # Ruby with ActiveSupport 74 ``` p (1..a.size).any?{|b|a.combination(b).any?{|c|c.sum*2==a.sum}}?'YES':'NO' ``` # Ruby 88 ``` p (1..a.size).any?{|b|a.combination(b).any?{|c|c.reduce(:+)*2==a.reduce(:+)}}?'YES':'NO' ``` [Answer] # Mathematica 59 With spaces for readability, ``` f@a_ := If[Select[Subsets@a, Tr@# == Tr@a/2 &] == {}, "NO\n", "YES\n"] ``` **The Logic** If there exists no subset of the input integer array, `a`, having, as its total, one-half of the total of `a`, then NO. Else, YES. --- **Examples** ``` f[{4, 3, 5, 5, 3}] ``` > > YES > > > --- ``` f[{4, 3, 5}] ``` > > NO > > > [Answer] # Haskell - 113 (30 chars for imports) ``` import Control.Monad(filterM) f x|t="YES" |1>0="NO"where t=or$map(==(sum x)/2)$map(sum)$filterM(\_->[0>1,1>0])x ``` Query by calling f on a list: ``` *Main> f [4,3,5,5,3] "YES" *Main> f [1,3] "NO" *Main> f [5,5] "YES" ``` This is my first attempt at golfing in Haskell, if anyone has any tips for shortening my code they are welcomed. [Answer] ## MATLAB ~~75~~ 64 Quite happy with this. Too bad the function names are so much characters. ``` @(x)['NO '+[11,-10,51]*ismember(sum(x)/2,cumsum(perms(x),2)) ''] ``` [Answer] # Javascript Only works in browsers with ECMAScript 6 support (Firefox works). Defines a function that can be called with a list of integers, the target sum value, and the length of the list. ## 53 characters (sans formatting and specific criteria) ``` q=(l,s,i)=>--i>=0&&(q(l,s,i)||l[i]==s||q(l,s-l[i],i)) ``` This will work with both positive and negative floating point numbers as well, not just integers. It can also find whether the list at any point can sum to any arbitrary sum, which is much more general than the problem requires. ## 106 Characters (with formatting and starting criteria) ``` q=(l,i,s)=>--i>=0&&(q(l,i,s)||l[i]==s||q(l,i,s-l[i]));f=l=>q(l,l.length,l.reduce((a,b)=>a+b)/2)?'YES':'NO' ``` Fully half of the code here is just boilerplate required to limit the solution to this specific case, and format the output according to the criteria. A non recursive solution that builds the table from the bottom is more efficient but also takes more characters. [Answer] ## GolfScript ~~64~~ 47 ``` ~:x[[]]{{+}+1$%+}@/(;{{+}*2*x{+}*=},'YES''NO'if ``` Explanation: Find a subset (using [this](https://codegolf.stackexchange.com/a/9048/11218) subset method) whose sum is exactly half of the total sum of the input. Previous solution: ``` ~].,.))2?,{2base}%\{\,=}+,\`{]zip{~\2*(*}%}+%{{+}*!},'YES''NO'if ``` Explanation: This uses `base` to count and find every possible array of length `n` comprised of only `1`s and `0`s. Then it uses this array to negate or do nothing to elements of the initial array. For example, for input `[1 2 3]`, we would have `[1 2 3][1 2 -3][1 -2 3][1 -2 -3][-1 2 3][-1 2 -3][-1 -2 3][-1 -2 -3]`. The program then returns 'YES' if and only if the sum of the elements of any of these arrays is 0. Negating some subset of the array, then adding all the elements and checking if it equals 0 is clearly equivalent to checking for a 2-part partition. I'm sure this implementation can be improved upon, but I think the idea is there. [Answer] ### GolfScript, 34 characters ``` ~]1,\{2*{1$+}+%}/)2/?)!"YES NO"n/= ``` The code basically calculates the totals of all possible subsets and then searches for (half of) the overall total in this list. (Actualy the code calculates doubles all the subset sums and searches for the list's total in order to not conflict with integer division.) You can see the example running [online](http://golfscript.apphb.com/?c=OyI0IDMgNSA1IDMiCn5dMSxcezIqezEkK30rJX0vKTIvPykhIllFUwpOTyJuLz0K&run=true). ``` > 4 3 5 5 3 YES > 4 5 5 5 3 NO ``` [Answer] ## C#, 169 bytes It enumerates through a series of arrays of the same length as the input. Each array contains a list of +1 and -1 values which are multiplied against each corresponding input value. If the sum of the multiplied arrays is zero, then some numbers sum to the same as the rest of the numbers. For the sake of golfing the +1/-1 array is actually +2/0 and 1 subtracted from it when used. Example: ``` input = n = { 4, 3, 5, 5, 3 } polarity = p = { +1, +1, -1, -1, +1 } n*p = { +4, +3, -5, -5, +3 } result = x = Sum(n*p) == 0 ``` Code: ``` bool S(int[]n){ int i=0,l=n.Length,s; var x=false; var p=new int[l+1]; while(i>=0){ s=0; for(i=l;i-->0;) s+=n[i]*(p[i]-1); x|=s==0; for(i=l;p[i]<1&&i-->0;) p[i]=2-p[i]; } return x; } ``` Test: ``` Console.WriteLine(S(new[]{4,3,5,5,3})); True Console.WriteLine(S(new[]{1,3})); False Console.WriteLine(S(new[]{2})); False Console.WriteLine(S(new[]{0})); True // Presuming Sum{0} == Sum{} ``` [Answer] # C++ — ~~294~~ 275 Not very compact, but you don't often see C++ in code challenges! ### Features * can get NO result in O(1) time for many inputs * uses no external algorithms for generating subsets, all in code * C++ was used for easy vector creation ### Code ``` #include <iostream> #include <vector> using namespace std;int main(){vector<int>v;int s,e,w,g,t;for(s=0;cin>>e;s+=e)v.push_back(e);if(!(s&1)){s/=2;w=v.size();for(e=0;e<1<<w;e++){for(g=0,t=0;g<w;g++)if(e&1<<g)t+=v[g];if(t==s){cout<<"YES\n";return 0;}}}cout<<"NO\n";return 1;} ``` ### To compile ``` g++ -o partition partition.cpp ``` ### Examples ``` $ echo 4 3 5 5 3 | ./partition YES $ echo {1..28} | ./partition YES # after a slight delay $ echo 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 29 | ./partition NO # after a long delay $ echo {1..29} | ./partition NO # immediately ``` ### Limitations * upper limit is 29 elements, could use `unsigned long long int` to extend to 61 or 62 elements, but the basic idea is the same ]
[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/6351/edit). Closed 7 years ago. [Improve this question](/posts/6351/edit) ## How could we generate shapes or images using binary? I got to messing around trying to create something that looked matrix like and got to thinking, wouldn't a great CodeGolf be to see who can make the best shortest code to generate a binary image? Please advise me of any rules I should add. ### Rules: * Create a binary image art of a Meme using 40 chars wide by 20 chars tall. * Shortest code out of top 3 voted images wins. ### Example Output: ``` 00000000000000000000000000000000000000000 00000000000000000000000000000000000000000 00000000000000000000000000000000000000000 00000000000000000000000000000000000000000 00000000000000000000000000000000000000000 00000000000000000000000000000000000000000 00000000000000000000000000000000000000000 00000000000000000000000000000000000000000 00000000001111000000000000011110000000000 00000000111111110000000001111111100000000 00000011110000111100001111000001111000000 00000011110000111100001111000001111000000 00000011110000111100001111000001111000000 00000011110000001111111100000001111000000 00000011110000000011110000000001111000000 00000011110000000000000000000001111000000 00000011110000000000000000000001111000000 00001111000000000000000000000000011110000 00111100000000000000000000000000000111100 11110000000000000000000000000000000001111 ``` [Answer] ## YO DAWG, I HERD YOU LIKE ... (Python - 151) ``` a,b,c,d,e=9663681096,78383190025,559419527177,9663713289,628289966664 print'%040o\n'*20%tuple(map(lambda x:(x|x<<48|x<<96)>>21,[0,a,b,c]+[d]*5+[e])*2) ``` Output: ``` 0000000000000000000000000000000000000000 0001100000111100000110000011110000011000 0011100001100110001110000110011000111000 0101100001100110010110000110011001011000 0001100001100110000110000110011000011000 0001100001100110000110000110011000011000 0001100001100110000110000110011000011000 0001100001100110000110000110011000011000 0001100001100110000110000110011000011000 0111111000111100011111100011110001111110 0000000000000000000000000000000000000000 0001100000111100000110000011110000011000 0011100001100110001110000110011000111000 0101100001100110010110000110011001011000 0001100001100110000110000110011000011000 0001100001100110000110000110011000011000 0001100001100110000110000110011000011000 0001100001100110000110000110011000011000 0001100001100110000110000110011000011000 0111111000111100011111100011110001111110 ``` [Answer] # QBASIC - 1157 Characters Ok, this one isn't that short, but definitely qualifies for the meme factor. ``` CLS l$="1" FOR i=1 TO 20 s$="" FOR j=1 TO 40 s$=s$+"0" NEXT ?s$ NEXT A=20 C=16 D=12 E=27 FOR i=2 TO 6 b=ABS(4-i) LOCATE i,8-i:?1$ LOCATE i,4+i:?1$ LOCATE 4,b+5:?1$ LOCATE i,22:?1$ LOCATE i,13:?1$ LOCATE 6,11+i:?1$ LOCATE 6,A+i:?1$ LOCATE 10-b,3+i:?1$ LOCATE D-b,7:?1$ LOCATE 6+i,13:?1$ LOCATE 8,11+i:?1$ LOCATE 6+i,17:?1$ LOCATE D,11+i:?1$ LOCATE 6+i,22:?1$ LOCATE 6+i,26:?1$ LOCATE D,A+i:?1$ LOCATE 6+i,29:?1$ LOCATE 8,E+i:?1$ LOCATE 10,E+i:?1$ LOCATE 9,34:?1$ LOCATE 6+i,E+i:?1$ LOCATE D+i,5:?1$ LOCATE 14,b+6:?1$ LOCATE C,b+6:?1$ LOCATE 18,b+6:?1$ LOCATE 15+b,9:?1$ LOCATE D+i,17-i:?1$ LOCATE D+i,13+i:?1$ LOCATE C,b+14:?1$ LOCATE 14,A+i:?1$ LOCATE C,A+i:?1$ LOCATE 18,A+i:?1$ LOCATE C-b,22:?1$ LOCATE C+b,26:?1$ LOCATE 14,E+i:?1$ LOCATE C,30+b:?1$ LOCATE 18,E+i:?1$ LOCATE D+i,29:?1$ NEXT ``` Here's a screen shot for the odd person who doesn't have QBasic installed. ![enter image description here](https://i.stack.imgur.com/X8RUv.png) [Answer] ## New\*\*\* Can't Triforce (Perl, 85 chars) ``` map{$j=$_<10;$_=sprintf"%010d",1x($_%10+1);s/1(.*)/$&$1$`0/;say$_.($j?0 x20:$_)}0..19 ``` output: ``` 0000000001000000000000000000000000000000 0000000011100000000000000000000000000000 0000000111110000000000000000000000000000 0000001111111000000000000000000000000000 0000011111111100000000000000000000000000 0000111111111110000000000000000000000000 0001111111111111000000000000000000000000 0011111111111111100000000000000000000000 0111111111111111110000000000000000000000 1111111111111111111000000000000000000000 0000000001000000000000000000010000000000 0000000011100000000000000000111000000000 0000000111110000000000000001111100000000 0000001111111000000000000011111110000000 0000011111111100000000000111111111000000 0000111111111110000000001111111111100000 0001111111111111000000011111111111110000 0011111111111111100000111111111111111000 0111111111111111110001111111111111111100 1111111111111111111011111111111111111110 ``` [Answer] ## The Weight Lifter *or* The Keyboard Player *or* ... (188 characters) Not really too sure if this fits the `meme` requirement, but it is not *too* long I hope... ``` from math import*;r=range;q=r(20) s=[["1"for x in q*2]for x in q];s[14][2:38]=["0"]*36 for j in r(18,21): for i in q:v=int(j+7*sin(i/7.0*pi));s[i][v]=s[i][40-v]="0" for l in s:print''.join(l) ``` > > Output: > > > ![The weight lifter](https://i.stack.imgur.com/K3kDR.png) [Answer] **The Mandelbrot set written in 194 characters of coffeescript on node.js:** ![ascii_mandel.png](https://i.stack.imgur.com/44RZ4.png) ``` m=(x,y)-> a=x b=y z=0 for i in [0..9] return 0 if z > 4 l=y*y z=x*x+l y=2*x*y+b x=x*x-l+a 1 console.log (m x,y for x in [-1.5..0.5] by 2/39).join '' for y in [-1.3..1.3] by 2.6/19 ``` [Answer] I could make no sense out of that knowyourmeme site. So here's a riff on your first reference: something matrix like. ## Postscript ~~(287)~~ (310) *Edit:* Better output (more 'ones', less apparent *waves*). Run with `gs -dNODISPLAY -q -- matrix.ps 60`. Replace `60` with the number of columns to generate. ``` %! << 0{(1)print} 1{(0)print} 10{()=} /#{load exec} /rho ARGUMENTS 0 get cvi /enn 0 /set{[rho{rand rand 30 mod 2 idiv 3 mul neg bitshift}repeat]} /lin{[exch{dup 2 idiv exch 2 mod #}forall]10 #} /zer{/enn enn 1 add def enn 6 mod 0 eq{dup 0 exch{add}forall rho 1.1 exp lt{pop set}if}if} >>begin set{lin zer}loop ``` It generates infinite output like this, mostly ones with vertical zero "signals": ``` 011001110110110001100101111110011111001101101111110111011101 010011111101100011110110110111010101001101111111111110011101 111111110111110001111100010110110011011101111111110110011101 110110111111110011111011110110111110111111101111110111111101 010101111111110101101100011100100110001101101111111110011101 110101111111101101101010011110101111001101111111110111111111 011111111111101001100111011100000011111101101111110111011011 010111111111111101101100111110100001101111111111111110011101 010100111111101001111011011111011001111111111111111110111001 011111111111101011110100011101001101101111111111110110111111 111100111111111101111100011111110001101111101111111111011011 111100111111101011110001011101111101101111111111111111111101 111101111111111001111001011111010101111101101111111110111111 011110111111111001100101011111011101111111101111111111111101 011101111111111101110001111111011101111111111111111111011101 111101111111111111110111111111111111111111111111110110011111 011101111111101011100111011111110101111111101111111111111111 011100111111111101111011111111111111111101101111110111011101 011111111111101111110111111111010111111111111111111111111111 011100111111111011110101111111111101111111111111111111011111 011101111111111111110101111111110111111111111111111111011111 111111111111111101111111111111111111111111111111111111011111 111111111111101101111101111111111111111111111111111111011111 111111111111101111111111111111111111111111111111111111011111 111111111111101111111111111111111111111111111111111111111111 111111111111111111111111111111111111111111111111111111011111 010011010111011111001101111111011001011011011011111010111111 110011011111001111001111011100111011111011110011111101100110 110101111111111011111011111000110101110011011010111111110110 010111111111001111111001111000110001111111011111111110101110 010001111111111111110001011100110001100011110111101010111101 011011111011001011111001011100111111110111110110111011100110 011001011111101111110111011100110111100111111110111111111100 011101111011101111110001111110111111111111110111111010111111 011101111011101011111101111110110011011111010111101110101111 111101111011111011110001011101110001111011011111111000111100 111101011111011111111011111110111001101111111111111101111111 111101111111001111111111111110110011000011111111111100100111 11010101111110^C Command terminated ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 354 bytes ``` •4¤Q}qV¸dí¼ÔÁpoEW"Eáãø>jή\墻kq;Çl:&»"6*²h†z¬e™/[ΧąèRÝ\iåÚˆ2-dŠX‹öäùœUqB͸©Ùì)z«×íP÷»éuøêB9hŽÒ>·Ä.ãò‰Z‡*…4:W&.½ñÝm·›mìQ[Š,í5(/øé‡”¿ô¿®P4^eã$–…l÷¿6?z·RˆN¥eWIãÀ}áÎåÇ)PÍ2ž?cLnfýµ‚áIípпÖÝYp~FüÇ@jÉZßÝÓóÜåÀÑ=EôÿwµŽk`"ÍÝ8*$ˆœ¢7œÄÕw(A®?®h:rGPO¯7¥‘Å)UôÛ€¦—“ÇÙ(áÖ©£ŠÂ”áÊ¡õZ‘]½Æ¬„нMâ$¾)Yé:â#滫Z=hõ¹‚.ðË7_Î#@¹OH—?9PyÆIð¼S%³zëJïzGÍä\{g…Ë;nEwÀ@ɳ_ˆ92ŽÚ@C’•b81ô}» ``` [Try it online!](http://05ab1e.tryitonline.net/#code=4oCiNMKkUX1xVsK4ZMOtwrzDlMOBcG9FVyJFw6HDo8O4PmrDjsKuXMOlwqLCu2txO8OHbDomwrsiNirCsmjigKB6wqxl4oSiL1vDjsKnw4TigKbDqFLDnVxpw6XDmsuGMi1kxaBY4oC5w7bDpMO5xZNVcULDjcK4wqnDmcOsKXrCq8OXw61Qw7fCu8OpdcO4w6pCOWjFvcOSPsK3w4Quw6PDsuKAsFrigKEq4oCmNDpXJi7CvcOxw51twrfigLptw6xRW8WgLMOtNSgvw7jDqeKAoeKAncK_w7TCv8KuUDReZcOjJOKAk-KApmzDt8K_Nj96wrdSy4ZOwqVlV0nDo8OAfcOhw47DpcOHKVDDjTLFvj9jTG5mw73CteKAmsOhScOtcMOQwr_DlsOdWXB-RsO8w4dAasOJWsOfw53Dk8Ozw5zDpcOAw5E9RcO0w793wrXFvWtgIsONw504KiTLhsWTwqI3xZPDhMOVdyhBwq4_wq5oOnJHUE_CrzfCpeKAmMOFKVXDtMOb4oKswqbigJTigJzDh8OZKMOhw5bCqcKjxaDDguKAncOhw4rCocO1WuKAmF3CvcOGwqzigJ7FoMK9TcOiJMK-KVnDqTrDoiPDpsK7wqtaPWjDtcK54oCaLsOww4s3X8OOI0DCuU9I4oCUPzlQecOGScOwwrxTJcKzesOrSsOvekfDjcOkXHtn4oCmw4s7bkV3w4BAw4nCs1_Lhjkyxb3DmkBD4oCZ4oCiYjgxw7R9wrs&input=) ``` 111111111111111110001111111111111111100000000000111111111111100000001111111111111 111111111111111111001111111111111111110000000111111111111111100001111111111111111 111111111111111111101111111111111111111000011111111111111111100111111111111111111 111111110000011111111111111100000111111100111111111111111111101111111111111111111 001111110000011111110011111100000111111101111111000000011111111111110000000111111 001111110000011111110011111100000111111111111110000000000000111111100000000000000 001111111111111111100011111111111111111011111110000000000000111111100000000000000 001111111111111111000011111111111111110011111110000000000000111111100001111111111 001111111111111100000011111111111111000011111110000000000000111111100001111111111 001111110000000000000011111100000000000011111110000000000000111111100001111111111 001111110000000000000011111100000000000011111110000000000000111111100000000111111 001111110000000000000011111100000000000001111111000000011111111111110000000111111 111111111100000000001111111111000000000000111111111111111111101111111111111111111 111111111100000000001111111111000000000000011111111111111111100111111111111111111 111111111100000000001111111111000000000000000111111111111111100001111111111111111 111111111100000000001111111111000000000000000000111111111111100000001111110001111 000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000111111111111111000000000111111111111111111111100000000000000000 000000000000000011111111111111111100000000111111111111111111111100000000000000000 000000000000000111111111111111111100000000111111111111111111111100000000000000000 000000000000000111111100000111111100000000111111111111111111111100000000000000000 000000000000000111111100000000000000000000001111111000000011111100000000000000000 000000000000000111111100000000000000000000001111111000000000000000000000000000000 000000000000000011111111100000000000000000001111111111111111100000000000000000000 000000000000000001111111111111000000000000001111111111111111100000000000000000000 000000000000000000011111111111110000000000001111111111111111100000000000000000000 000000000000000000000011111111111000000000001111111111111111100000000000000000000 000000000000000000000000000111111100000000001111111000000000000000000000000000000 000000000000000000000000000111111100000000001111111000000011111100000000000000000 000000000000000111111100000111111100000000111111111111111111111100000000000000000 000000000000000111111111111111111101111110111111111111111111111101111110000000000 000000000000000111111111111111111001111110111111111111111111111101111110000000000 000000000000000011111111111111100001111110111111111111111111111101111110000000000 ``` ]
[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/206769/edit). Closed 3 years ago. [Improve this question](/posts/206769/edit) Well, last time I asked for an [arithmetic sequence](https://codegolf.stackexchange.com/questions/206711/is-it-an-arithmetic-sequence-or-not), now comes the geometric sequence # Challenge In this challenge, the input will be an unordered set of numbers and the program should be able to tell if the set of numbers is a [Geometric Sequence](https://www.mathsisfun.com/algebra/sequences-sums-geometric.html). # Input * The input will be a set separated by `,`(comma). # Output * The Output can be a Boolean (True or False), or a number (1 for True, 0 for False). # Test cases ``` In: 1,3,9 Out: True In: 1,4,16 Out: 1 In: 2,6,14 Out: 0 In: 2,8,4 Out: True In: 4,6,9 Out: 1 ``` # Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code by bytes wins. * The minimum length of the input set would be 3 elements. Best of Luck [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` Ṣ÷ƝE ``` [Try it online!](https://tio.run/##y0rNyan8///hzkWHtx@b6/r/cPujpjX//0dHG@oY61jG6igAGSY6hmYglpGOmY6hCYRloQNlgCVjAQ "Jelly – Try It Online") Thanks to [fireflame241](https://codegolf.stackexchange.com/users/68261/fireflame241) for pointing out a mistake ## How it works ``` Ṣ÷ƝE - Main monadic link, takes an array as input - e.g A = [2, 8, 4] or A = [2, 6, 14] Ṣ - Sort [2, 4, 8] [2, 6, 14] Ɲ - Over overlapping pairs [x, y]... [[2, 4], [4, 8]] [[2, 6], [6, 14]] ÷ - ...divide x by y? [0.5, 0.5] [0.33, 0.43] E - Is the list all the same? 1 0 ``` [Answer] # [J](http://jsoftware.com/), 15 14 13 bytes ``` 1=&#&=2%/\/:~ ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DW3VlNVsjVT1Y/St6v5rcqUmZ@QrGCrYKqQBSWMFS1QBEwVDM4iIAVjESMdMx9AEWY2RjoUOioCJgpmC5X8A "J – Try It Online") *-1 byte thanks to xash* *-1 byte thanks to Bubbler* * `1=` Does one equal... * `&#&=` the length of the uniq of... * `2%/\` the list created by dividing each element by its right neighbor in the input list... * `/:~` sorted. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~25~~ 19 bytes ``` {~∨/⌈(⊣-⊃)2÷/⍵[⍋⍵]} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v7ruUccK/Uc9HRqPuhbrPupq1jQ6vF3/Ue/W6Ee93UAqtvZ/2qO2CcQoU3jUNxWo1FDBWMGSC8EzUTA0g3NNFMyQJI0ULBRMkHhmCoYmXMjmGAEA "APL (Dyalog Unicode) – Try It Online") *-6 bytes thanks to @Adám* ``` ⍵[⍋⍵] ⍝ sort ⍵ 2÷/ ⍝ Take the quotient of all consecutive pairs ⍝ Check if all are equal: (⊣-⊃) ⍝ Subtract the first quotient ~∨/⌈ ⍝ Are all 0? ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 56 bytes ``` N`\d+ Lv$`\b\d+,(\d+),(\d+) ;$2**_;$1*$1* A`(;_+)\1\b ^$ ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8N8vISZFm8unTCUhJgnI0tEAEpoQkstaxUhLK95axVALiLgcEzSs47U1YwxjkrjiVP7/N9Qx1rHUMTLnMtQx0TE00zEz4TLSMdMxBFEWICEuCx1DIx1DC6AaAA "Retina – Try It Online") Link includes test suite. Explanation: ``` N`\d+ ``` Sort in ascending order. ``` Lv$`\b\d+,(\d+),(\d+) ``` List all triples of numbers. ``` ;$2**_;$1*$1* ``` For each triple `a,b,c` calculate `ca` and `b²`. ``` A`(;_+)\1\b ``` Delete all lines where they equal. ``` ^$ ``` Check that there were no unequal triples. Note that this runs in unary so it fails on large numbers, but you can use this similar 62-byte program that does the calculations in decimal instead: ``` N`\d+ Lv$`\b\d+,(\d+),(\d+) ;$.($2**);$.($1*$1* A`(;.+)\1\b ^$ ``` [Answer] # JavaScript (ES6), 47 bytes Returns a Boolean value. ``` a=>!a.sort((a,b)=>b-a).some(p=n=>a-(a=p/(p=n))) ``` [Try it online!](https://tio.run/##bclBDoIwEEDRvbdwN5NMMUXS6GJ6EcNiwGI02Gko8fqVrmH53//IT/K4vNNqoj5DmbgI@7M0WZcVQGhA9oMR3OAbIHFkLwaE06UGIpZRY9Y5NLO@YIKHpSvde8TTzjuy7mC05Mh2h@NG1csf "JavaScript (Node.js) – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~56~~ 55 bytes Saved a byte thanks to [Surculose Sputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)!!! ``` lambda l:l.sort()!=len({b/a for a,b in zip(l,l[1:])})<2 ``` [Try it online!](https://tio.run/##XY/BboMwDIbvPIV3SiJ57QIRK6jZU@wGHKBNNKQsoBCkbYhnZwmdqm0@Wd/v3/49fvq3wWablvVm2vfu2oIpzWEanKfsQRpl6dIdW9CDgxY76C189SM1aCpeNmxl53TzavITSKAJhKIVxwyLBuHVzYrhHQrkeaD8jlLMkYuAnn6hE4r/VhHmih8nS1y8NJN6Tp/FhSDcWp4RlsSQMQyqj1FdfAy7Zyv3RaPrraeaLJGt8PgCBJW9ShKcUY8vaBpF9nd@WmFxVZAl3BY3K2HbNw "Python 3 – Try It Online") [Answer] # [R](https://www.r-project.org/), 38 bytes ``` function(x)!sd(diff(y<-sort(x))/y[-1]) ``` [Try it online!](https://tio.run/##K/qfWRyfnpqfG1@cWmj7P600L7kkMz9Po0JTsThFIyUzLU2j0ka3OL@oBCikqV8ZrWsYq4msRyNZw1DHWMdSU1NBWSGSC13GRMfQDKuUkY6ZjqEJWMoPQ8pCxwSrJhOgJphN/wE "R – Try It Online") * sort x * calculate difference between successive elements * divide by value of each element (except first) = fold-difference * check if results are all the same (standard deviation = zero) Fails for negative fold-differences between elements (which seems to be a true geometric sequence, but it isn't clear whether this is required by the challenge). Fixed by sorting x by absolute value, at a cost of +9 bytes: **[47 bytes](https://tio.run/##dZDRCoIwFIbve4pFNxtshCZiUK/QfYjIdGcy0I3cNH16WwoRZhfn6uP/fv7TTsrmFZgmt/C4TrLTpVNG44HsrcBCSYnHCxtS0wpoMS@sJyQjxzFlQUa@w7jEAT3RMyHogO67NYloEG@ikMY0iGZ0@0EJjTZDkQ/9a2KhL2PJQv1pqLhTPSBpasHek6AFXQIqwD0BNIIaGtDOrkwsoYvsY@IW8cL0QFHROWQ6x4xk82emFw)** ``` function(x)!sd(diff(y<-x[order(abs(x))])/y[-1]) ``` [Answer] # APL(NARS), 14 chars, 28 bytes ``` {1=≢∪2÷/⍵[⍒⍵]} ``` it seems 2÷/1 3 9 do 1÷3 3÷9 and 2,/1 3 9 make couples ``` h←{1=≢∪2÷/⍵[⍒⍵]} ⎕fmt {⍵,⊂,h⍵}¨(1 3 9)(1 4 16)(2 6 14)(2 8 4)(4 6 9) ┌5─────────────────────────────────────────────────────────────────┐ │┌4─────────┐ ┌4──────────┐ ┌4──────────┐ ┌4─────────┐ ┌4─────────┐│ ││ ┌1─┐│ │ ┌1─┐│ │ ┌1─┐│ │ ┌1─┐│ │ ┌1─┐││ ││1 3 9 │ 1││ │1 4 16 │ 1││ │2 6 14 │ 0││ │2 8 4 │ 1││ │4 6 9 │ 1│││ ││~ ~ ~ └~─┘2 │~ ~ ~~ └~─┘2 │~ ~ ~~ └~─┘2 │~ ~ ~ └~─┘2 │~ ~ ~ └~─┘2│ │└∊─────────┘ └∊──────────┘ └∊──────────┘ └∊─────────┘ └∊─────────┘3 └∊─────────────────────────────────────────────────────────────────┘ ``` ]
[Question] [ ## This is the cops' thread, the robbers' thread is [here](https://codegolf.stackexchange.com/questions/172222/polycops-and-robbers-robbers-thread) A polyglot is a program, that without modification, can run in multiple languages. --- # Allowed languages Any language that was made before the challenge and isn't made for the purpose of the challenge, it is allowed, though discouraged, to use languages that are easy to recognize --- # Cops' Challenge To write a non-empty program that does one of the following tasks: * Adds two numbers from STDIN * Prints "Hello, World!" * Prints the first 20 terms of the Fibonacci sequence Then, list the languages it works in (it must do the same thing in all languages). When you first post your answer, it is *vulnerable*, and robbers will try to find more languages it works in other than the ones you specified. If any robber finds a language, they comment on your question saying they cracked it. You should then edit your question saying it got cracked and list the languages you were missing. --- If a week passes by and nobody cracked your submission, you can mark it as *safe*, no robbers can crack it. --- # Winning Most upvoted safe answer is the winner. --- # Extra rules Cops must know there *is* a language that the program runs in other than the ones they wrote, so that there's a guarantee that all answers are *possible* to crack. And as always, standard loopholes apply. [Answer] # Wow, cracked by [Jo King](https://codegolf.stackexchange.com/questions/172222/polycops-and-robbers-robbers-thread/172235#172235 "@JoKing") while I'm still typing the explanations lol ``` '<?php '//'; #@ SPELL,WITH,ME, ,H,E,L,L,O, ,W,O,R,L,D,"'Hello, World!'" $a = "'Hello, World!'"; if ([]) console.log($a); else { for ($i = 1; $i < strlen($a) - 1; $i++) echo($a[$i]); } // ?>' ``` Prints `'Hello, World!'` (with single quotes) in both JavaScript and PHP. This should be an easy one to solve. ## How this works `'<?php '//'; #@ SPELL,WITH,ME, ,H,E,L,L,O, ,W,O,R,L,D,"'Hello, World!'"` JS treats this line as a string `'<?php '` followed by a `//` comment, and PHP prints `'` (outside the tag, so literally), then starts the script with open tag, and a string `'//'`, then a `#` comment. `$a = "'Hello, World!'";` Both JS and PHP defines the variable `a` to be the string `"'Hello, World!'"`. ``` if ([]) console.log($a); ``` In JS, since `[]` is consider truly, `console.log($a)` is executed and this prints out the string `"'Hello, World!'". ``` else { for ($i = 1; $i < strlen($a) - 1; $i++) echo($a[$i]); } ``` In PHP, since `[]` is consider falsy, the `for` loop is executed and this prints out the characters `Hello, World!` (notice the absence of quotes) subsequently. `// ?>'` In JS this is a comment, but in PHP the close tag ends the script and the `'` after the tag is printed out literally. --- ## Yes, the remaining language is Befunge-93. `'<?php '//'; #@ SPELL,WITH,ME, ,H,E,L,L,O, ,W,O,R,L,D,"'Hello, World!'"` `<` redirects the IP to the end of the line, then `"'Hello, World!'"` is pushed in reversed order. After that the 15 `,`s are used to output the characters (in normal order because of the double reversal). Finally `@` terminates the program. [Answer] # Almost all Befunges, Safe! ``` &<v @.+< ``` [Try it online!](https://tio.run/##S0pNK81LT/3/X0HNpozLQU/b5v9/QwMFIwMFAA "Befunge-93 – Try It Online\"") Starting it off with an easy one. This is adds two numbers from STDIN in every version of Befunge, 93, 96, 97, 98 etc. Thanks to Johnathan Allen for reminding me about Trefunge, Quadfunge, and all those variations as well. This doesn't work in Unefunge though. --- ### The answer is [Flobnar](https://github.com/Reconcyl/flobnar)! [Try it online!](https://tio.run/##S8vJT8pLLPr/X0HNpozLQU/b5v9/QwMFI4P/uikA "Flobnar – Try It Online") By the makers of Befunge, Flobnar is described as "what happens when you get Befunge drunk". It uses a lot of the same instructions, but goes backwards in comparison, starting at the `@`. ``` .... @... Start here going left .... ..+< Sum above the + and below ..&. Both end up here and get input as a number .... Implicitly output the return value ``` I thought someone would have gotten it since I've done a few things in Flobnar recently. [Answer] # Hello World, Cracked ``` puts "Hello World!" ``` List of Languages it works in (minus a few :D): 05AB1E 05AB1E (Legacy) 2sable Oasis Ruby Tcl Cracked: Working Language is Foo [Answer] # [Jelly](https://github.com/DennisMitchell/jelly) and [M](https://github.com/DennisMitchell/m), 15 bytes ``` +19С1-4181ḢFḊĊ ``` [Try it online!](https://tio.run/##y0rNyan8/1/b0PLwhEMLDXVNDC0MH@5Y5PZwR9eRrv//AQ "Jelly – Try It Online") Prints the first 20 terms in the Fibonacci sequence. Hexdump is ``` 1B 21 29 0F 00 21 1D 24 21 28 21 B5 36 B1 B0 ``` *Edit*: Three weeks and no crack? This shouldn't be too hard... [Answer] # Python, vulnerable Also works in Coconut (Thanks BMO!) Also works in Cython (which is a superset of Python, so why wouldn't it) Adds two inputs together ~~(may have some garbage output before the output when run in the second language, let me know if that's not okay)~~ No longer has garbage output Hint: The language name is somewhere on this page. ``` """ " "- Z B.m " "" "" "" "" "" "" "[ K O.a- F R.d " "" "" "- C P.u- O T.h " "" "" "" "" "" "" "" "" "- T I.q- O K.a " "" "" "- H C.n- G Y.t " "" "" "" "" "" "" "" "> W C.a+ M T.a " "" "< D N.h] V T.r " "" "" "" "" "" "" "" "> D K.b- M S.i " "" "" "" "" "" "" "" ". U Y.u- I J.x " "" "" "" "" "[ X C.e- K U.m " "" "" "> L W.y+ F X.l " "" "" "+ D B.n+ V N.e " "" "" "" "" "" "" "" "" "+ L F.g+ T Q.k " "" "" "" "" "" "" "" "< L Z.f] V I.b " "" "" "" "" "" "" "" "" "> I O.s+ D F.p " "" "" "" "" "" "" "+ D P.g. W B.j" "+ J S.z+ X U.l " "" "+ J A.o+ L V.t " "" "" "" "" "" "" "" "" "+ R P.x+ Y L.j " "" "" "+ H W.s. Q P.l " "" "" "" "" ". N U.d+ C K.l " "" "" "" "" "" "" "" "+ U B.h+ W L.n " "" "" ". X L.k[ Q Y.v " "" "" "- F B.r- B X.z " "" "" "" "" "- M F.t> W L.v " "" "" "" "" "+ O W.x< F W.g " "" "" "" "" "" "] L P.y> M A.m " "" "" "" "" "" "" "- I K.x- F A.i " "" "" "" "" "- Z U.a- M M.t " "" "" "- C L.s. C C.j " "" "" "" "" "" "" "" "" "- T R.u- N U.i " "" "" "" "" "" "" "- U R.p[ F D.x " "" "" "" "" "" "" "" "" "- S P.o> C H.d " "" "" "" "" "" "" "" "+ O W.p+ N W.i " "" "" "" "" "" "" "" "" "+ U A.r< O A.k " "" "" "" "" "" "" "" "" "" "] A M.y> W H.m " "" "" "" "" "" "" "" "" ". G J.g- L M.p " "" "" "" "" "[ J K.k- P E.n " "" "" "" "" "" "" "- S V.y- U U.j " "" "" "" "" "" "" "" "> P T.v+ Z F.h" "< X R.g] J A.d " "" "" "" "" "" "" "" "> A U.f- U G.u " "" "" "" "- P L.o- I V.q " "" "" "" "" "" ". B Y.b+ H Y.r " "" "" "" "" "+ O Y.u+ P N.w " "" ". F K.n- D L.c " "" "" "" "" "- I G.g- D Y.m " "" "" "" "" "" "" "" "" "- B Y.h- S H.x " "" "" "" "- N R.k. K A.n " "" "" "" "" "" "- N F.r- F S.l " "" "" "" "" "" "" "" "" "- Q L.e- L J.f" "- S Q.o- K U.k " "" "- C I.h- A N.s" ". N P.t- D J.b " "" "" "" "" "" "[ I S.t- D A.j " "" "" "" "" "" "- N F.a- Z S.b " "" "" "" "" "> A G.g+ Z N.g " "" "< A K.t] U W.g " "" "" "" "" "" "> V D.b. Y U.j " "" "" "" "" "" "" "" "" "" "+ K F.j+ G M.t " "" "+ J E.c+ X S.i " "" "" "" "" "" "" "+ K F.r+ Z R.e " "" "" "" "" "" "" "" "+ S X.p+ Q R.h " "" "" "" "" "+ E L.p+ J U.p " "" "" "" "" "" "" "" "+ F G.z. K S.s " "" "" "- Y O.k- C P.i " "" "" "" "" "" "" "- H N.v- O C.k " "" "" "" "- S J.x- H O.p " "" "" "- X D.p- W E.h " "" "" "- K F.v- B X.q " "" "" "" "- M Z.a- W E.d " "" "" "" "" "" "" ". N Y.a+ T H.r " "" "" "" "" "" "" "" "" "+ R S.c+ U Q.k " "" "" "" "" "" "" "" "+ U D.s[ U L.o " "" "" "" "- E U.u> V C.l " "" "" "" "" "" "" "" "" "" "+ N U.d+ E H.x " "" "" "" "" "< M W.v] C S.i " "" "" "" "> F U.p+ G F.a " "" "" "" ". G S.c- K C.l " "" "" "" "" "" "[ M J.p- R G.w " "" "> Z M.q+ Z J.e " "" "" "" "+ Y Q.k+ S L.c " "" "" "" "" "+ Q R.i< Y C.l " "" "" "" "" "] L F.h> M K.r " "" "" "" "" "" "" "" ". Z K.q- K R.c " "" "" "" "" "" "" "" "" "" "[ Q R.u- W L.x " "" "" "" "" "" "" "- D C.g- Z T.a " "" "" "" "" "" "" "" "" "" "> L G.u+ R M.h " "" "" "+ G U.c< R C.s " "" "] N D.n> W T.u " "" "" "" "" "" "" "" "- I X.d- W Q.l " "" "" "" "" "" "" ". H Z.a- P C.n " "" "- F P.i- R O.x " "" "- R R.w- J Q.j " "" "- H R.y- C D.y " "" "" "" ". L A.t+ K C.t " "" "" "" "" "" "" "" "" "[ G P.o- N N.j " "" "- Q V.x- S V.b " "" "" "" "> U K.u+ Q F.x " "" "" "" "" "" "< M U.v] P I.c " "" "" "" "" "" "" "" "" "> S U.t. U G.t " "" "" "+ Z N.k[ X Y.t " "" "" "" "- E Y.v> L W.c" "+ K S.g+ S B.h " "" "" "+ K V.a< Z C.z " "" "" "] G C.n> J Z.u " "" "" "" "" "" "" "" ". U K.t- G V.o " "" "" "" "" "- K Z.f[ K J.e " "" "" "" "" "" "" "" "" "" "- J B.l- S N.f " "" "" "" "" "" "" "" "" "- O L.w> G J.z " "" "" "+ X V.y< G F.a " "" "" "" "" "" "" "" "] M V.z> L N.x" "- Z R.r. V R.x " "" "" "" "[ G R.h- D O.g " "" "" "" "" "" "" "> W I.g+ R C.x " "" "" "" "+ S F.h+ B G.m " "" "< B G.f] L D.z " "" "" "" "" "> F O.a+ K M.h " "" "" "" "" "" "+ V F.x. P V.w " "" "" "" "" "" "" "" "" "- C X.z. A L.x " "" "" "" "" "" "" "" "" "+ M J.b+ I O.t " "" "" "" "" "" "+ Z Y.q. N I.h" "- T W.e[ W K.o " "" "" "" "" "" "" "" "" "- S M.a- P O.d " "" "" "" "" "- B T.g> W K.s " "" "" "" "" "" "" "" "+ D V.g< O J.f " "" "" "" "" "" "] O O.r> C Z.f " "" "- W L.b. P F.d " "" "" "" "" "" "" "" "" "" "+ Y P.t[ H O.h " "" "" "" "- O Z.c- C A.z " "" "" "" "" "- X Y.g- O Q.g " "" "" "" "" "" "- N E.n> G C.s " "" "" "" "" "" "" "+ B I.g< Z P.a " "" "" "] H F.y> G J.j " "" "" "" "" "" "+ N R.u. G D.q " "" "" "" "" "" "" "" "- A F.e- P C.i " "" "" "" "- W L.i- L V.d " "" "" "" "" "" "- X P.r- Y S.x " "" "- F C.n- G N.o" "- Z A.q. K Q.j " "" "" "" "" "" "[ S B.n- W C.l " "" "" "" "" "" "" "- N Q.g- O M.h " "" "" "" "" "" "" "" "" "" "> J T.f+ M N.h " "" "" "" "" "" "< O C.w] J E.l " "" "" "" "" "" "" "" "" "" "> F N.c. Z H.d " "" "" "" "" "" "- G M.n- L S.x " "" "" "" "" "" "- S Z.h- C M.l" ". C S.z+ G I.a " "" "" "" "" "" "" "" "[ D W.g- C P.j " "" "- H V.t- C T.p " "" "" "" "- F F.o> Y A.s " "" "" "" "" "" "" "" "" "" "+ O R.g< I V.h " "" "" "" "" "" "] D H.p> H D.j " "" "" "" "" "+ O G.c+ I Z.p " "" "" "" "" "" "" "" "+ S R.f. I J.m " "" "" "" "" "" "+ H Z.l+ X V.h " "" "" "" "" "" "" "[ Y M.m- L O.r " "" "" "" "" "" "" "" "" "" "> B Z.n+ D W.x " "" "" "" "+ Z C.m+ X Q.t " "" "" "" "" "" "" "" "" "" "< S E.w] L Y.n" "> V F.b. V S.z " "" "+ C M.n+ L K.n" "+ S S.y+ S O.b " "" "" "" "" "" "" "" "" "" "+ R G.y+ K X.j " "" "" "" "+ F O.g+ A C.z " "" "+ R L.q. S N.g " "" "" "" "" "" "" "" "" "" "+ X L.x+ C F.x " "" "" "" "" "" "" "+ C O.x. G A.h " "" "" "" "" "" "" "" "" "" "[ Z L.u- A P.o " "" "" "" "- O H.i> U Q.v" "+ F A.d+ E T.n " "" "" "+ B S.o+ F B.y " "" "" "+ L S.r< O X.n " "" "" "" "" "" "" "] C D.h> H O.d " "" "" "" "" "" "+ X O.x+ H Q.b " "" "+ E S.n. M X.q " "" "" "- D S.j- U E.l " "" "" "" "" "" "" "[ H J.g- A R.a " "" "" "" "> T X.s+ D C.d " "" "" "" "" "" "+ G X.p+ I J.l " "" "" "" "" "" "" "" "" "" "+ F K.i< C Q.h" "] X L.c> X V.i " "" "" "" "" "+ B Q.t. S J.j " "" "" "" "" "- L J.v- D C.h " "" "" "" "" "" "- F D.f- R N.u " "" "" "" "" "" "- T Y.p- R S.p " "" "" "" "" "" "" "- V S.y- X U.r " "" "" "" "" "" "" "- H E.r- H O.l" ". I A.a+ C S.u " "" "" "" "" "" "" "" "" "+ S B.q+ L N.j " "" "" "" "" "" "" "+ B F.u+ L X.r " "" "" "" "" "" "" "+ V C.b. K P.l" "- U K.l[ P S.q " "" "" "" "" "" "" "- Z E.u- P M.s " "" "" "" "" "" "- I P.z- A W.f " "" "" "" "> W A.x+ S B.l " "" "" "" "" "" "< P H.m] T C.l " "" "" "" "" "" "" "" "" "" "> D N.o+ H T.w " "" "" "+ H X.n+ S Y.g " "" "" "" "" ". L C.b- M N.h " "" "" "" "" "- D B.q- X C.s " "" "" "" "" "" "[ D Y.o- L W.z " "" "" "> D N.n+ C P.o " "" "" "" "" "+ A V.a+ X X.w " "" "" "" "" "+ L T.l< V K.s" "] C E.f> C I.o " "" "" "" "" "" "" "" "" "" ". O C.a- L B.a " "" "- E Q.c- I F.h " "" "" "" "" "" "- A Y.q- K T.a" "- C Y.h- F A.e " "" "" "" "" "" "- M D.h- L I.z " "" "" "" "" "- X G.c- M F.x " "" "" "" "- P U.s. N F.f " "" "" "" "" "" "" "" "" "+ A E.c+ F B.k " "" "" "" "" "" "" "+ Q K.f+ W I.y " "" "" "" "" "+ E S.a+ R S.o " "" "" "+ N Y.a. J G.u " "" "+ L V.i+ X T.y " "" "" "+ S F.l+ O Y.i " "" "" "" "" "" "" "" "" "" "+ Q V.e+ S Q.l " "" "" "" "" "" "" ". O A.g+ W S.r " "" "" "" "" "" "" "" "" "+ Z D.e[ N A.l " "" "" "" "- A D.b> I K.a " "" "" "" "" "" "+ E U.c+ E O.x " "" "" "" "" "" "" "" "+ P D.h< G K.g " "" "" "" "" "] G X.b> H W.g " "" "" "" "" "" "" "" "+ K D.c+ H B.f " "" "" ". K Z.e+ M P.p " "" "" "" "" "" "" "" "" ". A L.n- O B.m" "- P T.z- C S.w " "" "" "" "" "" "" "" "- Q Y.e[ I N.g " "" "- X A.q> Y L.i" "+ I Y.u+ T A.w " "" "+ B Z.t< W U.z " "" "" "" "" "" "" "] R S.i> U S.a " "" "" "" "" "" "" "" "" ". O T.a- M D.f " "" "" "" "" "" "- H U.s- V O.g " "" "" "" "" "" "" "" "- O H.p- O L.v " "" "" "" "" "" "" "" "" "" "- X R.b- U V.w " "" "" "" "" "" "- G H.w- E R.n " "" "" "" "" "" "" "" "" "" "- R J.c- H S.p " "" "" "" "- J A.x. F W.h " "" "" "" "" "" "" "" "" "[ J R.s- F R.c " "" "" "" "" "" "" "> L H.w+ Z A.z " "" "" "" "+ Z O.s+ S D.u " "" "" "" "" "" "" "" "< B C.k] J F.k" "> P C.t+ H C.q " "" "" "" "" "" "" "" "" "+ N B.e. V S.t " "" "" "" "" "[ Q M.p- M C.m " "" "" "" "" "" "" "- B A.r- Q C.y " "" "" "> F D.t+ A G.r " "" "< A V.d] X H.m " "" "" "" "" "" "" "" "> J E.x- Y P.d " "" "- E T.h- P I.p " "" "" "" "" "" "" "" "- R O.f. I B.f" "+ P M.n+ N L.j " "+ N Z.c[ Y V.z " "" "" "- K G.k> D F.u " "" "" "+ L D.e+ W I.k " "" "" "" "" "" "+ P M.k< X Y.y " "" "" "" "" "" "] O L.n> Q K.e " "" "" "" "+ R M.t+ C B.i " "" "" ". E J.g+ I C.a " "" "" "" "" "" "" "" "" "" "+ C C.k+ B I.e " "" "" "" "" "" "" "" "" "+ T U.d+ K D.x " "" "" "" "" "" "" "+ F K.p+ M O.h " "" "" "" "" "" "" "+ Q H.e. M Z.a " "" "" "" "+ I Q.m+ W M.d " "" "" "" "+ A I.y+ G H.u " "" "" "" "" "" "" "+ E U.j. Z W.z " "" "" "" "" "" "" "" "" "- G X.r- R V.h " "" "- I P.a- M X.d " "" "" "" "" "" "" "" "" "- V M.q- C M.z " "" "" "" "" "" "- P K.l- N L.r " "" "" "" "" "" ". L D.t- G A.f " "" "" "" "" "" "" "" "" "" "[ T J.f- M X.p " "" "" "" "" "" "" "- V P.t- G Z.f " "" "> T O.h+ S Q.r " "" "" "" "" "" "" "" "" "< Z S.r] D P.v " "" "" "" "" "" "" "> G Q.n- F M.v " "" "" "" "" "" "" "" "" "- P Z.g. N S.d " "" "" "" "" "" "" "" "" "" "+ E G.x[ U N.t " "" "" "- R J.z> Y Y.e " "" "" "" "" "" "" "" "+ V N.x+ V U.s " "" "" "" "" "+ W P.s< S P.m " "" "" "" "" "" "" "" "] G O.x> X J.d " "" "" "" "" "" "+ X E.l. Z T.o " "" "" "" "+ T N.l+ L U.t " "" "" "" "+ C L.i+ Z M.g" "+ M K.k+ E P.p " "" "" "" "" "+ P T.l+ S Z.h" ". F W.k- Q D.q " "[ O I.r+ K W.r " "" "" "+ J B.x> F A.s " "" "" "" "" "" "" "" "" "- Y D.b- O H.r " "" "" "" "" "" "- W N.a< H S.e" "] N F.o> Q I.y " "" "" "" "" "" "+ B V.w. Q G.b " "" "" "- J R.i[ B M.j" "- Q R.a- K V.v " "" "" "- M S.b> W O.i " "" "" "" "" "" "" "" "" "+ C D.t+ T X.o " "" "" "" "" "" "" "" "" "< S C.m] T F.f " "" "" "" "" "" "" "" "" "" "> E Q.z- O B.w " "" "" "" "" "" "" ". Z T.a+ X L.t" "+ H U.f+ B E.x " "" "" "" "" "" "" "" "+ K A.c+ A E.p " "" "" "" "" "+ S N.v+ P P.h " "" "" "" "" "" "" "" "+ R C.f+ I I.y " "" "" "" "" "" "" "" "" "+ N C.h. U P.x " "" "" "" "" "" "" "- D Q.c- I K.k " "" "" "" "" "" "" "" "" "- U U.c- A X.j " "" "" "" "" "" "" "" "" "" "- N B.u. A J.p " "" "" "" "" "[ N K.j+ L H.t " "" "" "" "" "+ D E.j> T Q.c" "- B U.z- A N.e " "" "" "- C J.k< D O.n " "" "" "" "" "" "" "" "" "] O U.c> Z J.e " "" "" "" "" "" "+ K E.m+ B O.p" ". H S.l[ T N.r " "- Z M.e> D Q.i " "" "" "" "" "" "" "" "+ K B.v+ S P.o " "" "" "" "" "+ Q O.w< Y D.o " "" "" "" "] I C.n> R H.i " "" "" "" "" "" "" "- I F.z. L Q.t " "" "[ W U.q- A C.q " "" "" "" "- H U.l- V P.f " "" "" "- J Z.n> C Y.j " "" "" "" "" "" "" "+ E Y.b< J Q.g " "" "" "" "" "" "] F W.x> X H.c " "" "+ Z X.r+ O K.g " "" "" "" "+ Y Q.f. X Z.d " "" "" "" "" "" "" "[ O G.z- F K.u " "" "> P Z.o+ M D.s " "" "" "" "" "" "" "" "+ L G.h+ Z M.l " "" "" "" "" "" "" "" "" "" "< J L.y] O U.x " "" "" "" "" "> L K.q+ P U.c " "" "" "" ". F H.l+ X W.j " "" "" "" "" "" "" "+ N I.x. U A.u " "" "" "" "" "" "" "" "- Y B.m[ X W.a " "" "" "" "" "" "" "" "" "" "- B X.u- V G.w " "" "" "" "" "- D N.d> M Q.g " "" "" "" "" "" "" "" "+ I I.w< E P.u " "" "] F V.k> I U.s " "" "" "" "" "" "" "- F P.b- B H.u " "" "" "" "" "" ". J X.n+ G E.e " "" "" "" "" "" "" "" "" "" ". U J.t[ T C.l " "" "" "" "" "- O K.g> T L.r " "" "" "" "" "" "" "" "+ W A.a+ O Z.g " "" "+ A N.e< Q N.q " "" "" "" "" "] W U.k> Y J.w " "" "" "" "" "" "" "" "" "+ V V.k+ Y L.w " "" "" "" ". S V.k+ P C.h " "" "" "" "" "" "+ C G.v+ N F.d " "" "" "" "" "" "" "" "" "" "+ K P.u+ R J.z " "" "+ E R.y+ I I.p " "" "" "" "" "" "" "" "" "" "+ Y H.z+ G U.v " "" "+ T E.o+ G S.g " "" "" "" ". S A.u. Z X.n " "" "- L S.x[ M X.z " "" "" "" "" "" "" "" "" "- V Z.e- S C.p " "" "" "" "" "- T H.m> E B.m " "" "" "" "" "" "" "" "" "" "+ Q T.t< N Z.g " "" "" "] R I.y> B J.k " "" "" "" "" ". V V.r- L T.x " "" "" "" "" "" "" "" "[ L Z.s- T Y.p " "" "" "" "" "" "- N A.p- W X.q " "" "" "" "" "" "" "- M D.t> Z Y.r " "" "" "" "+ B Q.u< L C.m" "] V R.j> Z D.y " "+ A C.j+ P S.w " "" "" "" ". V K.r- E N.s " "" "" "" "" "- C F.n- Q B.p " "" "" "" "" "" "[ R E.d- H Y.r " "" "" "" "" "" "> H D.v+ X E.h" "+ V R.j+ C C.m " "+ C Q.j< Q X.b " "" "" "" "" "" "" "" "" "] Y J.g> K Y.s " "" "" "" "" "" "" "" ". T R.i- K R.f " "" "" "" "" "" "" "" "- B U.o- Z I.n " "" "" "" "" "" "" "" "- I X.s- G D.p" "- B C.i- K G.c " "- V G.i- P Y.f " "" "" "" "- V G.t- U D.s " "" "" "" "" "" "" "" "" "- K P.f. F X.m " "" "" "" "" "- O B.l- S C.e " "" "" "" "" "" "- B K.l. D Z.f " "" "- U K.m- J F.z " "" "" "" "[ H N.l- D G.i " "" "" "" "" "" "" "" "" "- Y T.u- Z R.s " "" "> Z O.p+ D V.g" "< Q W.w] W K.w " "" "" "" "" "" "> O V.l- I A.w " "" "" "" "" "" "" ". B L.j+ H C.k " "" "" "" "" "" "" "+ B W.w[ H T.q " "" "" "" "" "" "" "" "- Z F.z- H S.u" "- K B.j> M T.w " "" "" "" "" "" "" "+ Q N.d+ G K.a " "" "" "" "" "" "< W U.e] H M.u " "" "" "" "" "> B Q.u. O J.r " "" "" "" "" "" "" "" "- Z G.n- H K.i " "" "" "" "" "" "" "" "" "- I E.j- X U.y " "" "" "" "" "- L O.u- J D.h " "" "" "- X F.q- P J.v " "" "- E T.u- X M.c " "" "" "" "" "- S P.y. U S.z " "" "" "" "" "" "" "" "" "+ E C.l+ S N.y " "" "+ T N.r+ J F.s " "" "" "" "" "" "" "" "+ U I.x+ I P.o " "" "" "" "+ F Z.e+ P E.k " "" "" "" "" "" "" "+ G J.k+ X Y.w " "" "" "" "" "" "" "+ Z Z.d+ Y B.b " "" "+ F A.d. R W.p " "" "" "- M A.z- Y R.l " "" "" "" "" "" "" "- Z L.a- E X.h " "" "" "" "" "" "" "" "" "" "- I G.d- H J.b " "" "- U E.n. H X.k " "" "" "- V E.s- S F.h " "" "" "" "[ L A.x- A C.l " "" "" "" "- P O.q- X J.x " "" "" "> M X.u+ W H.s " "" "" "< H T.p] V U.o " "" "" "" "" "> P Z.v- C K.a " "" "" "- U J.p. V N.l " "" "" "" "" "" "" "" "" "" "[ L T.u- N K.d " "" "" "" "" "" "" "" "" "> I G.u+ Z N.g " "" "" "" "" "" "" "" "" "" "+ H K.j+ M S.h " "" "" "" "" "" "" "" "< F M.t] D J.z " "" "" "" "" "" "" "> E K.d+ J M.c " "" "" "" "" "" "" "" "" "+ O M.u. A P.k " "" "" "" "" "" "" "" "" "+ R V.v+ U I.e " "" "+ Z C.m+ L L.m " "" "" "" "" "+ B Z.d+ O R.s " "" "" "" "" "" ". B D.m- W R.x " "" "" "" "" "" "" "" "- W H.b. S R.g " "" "- Y N.a- P L.b " "" "" "" "" "" "" "" "[ T M.k- D H.x " "" "" "" "" "" "" "" "" "- P I.s- U A.z " "" "" "" "> E B.m+ O I.t " "" "" "" "" "< T N.c] A D.t " "" "" "> Q I.y- Z P.y " "" "" "" "" "" "" "" "" ". M B.t- N E.j " "" "" "- K T.z- Y S.p " "" "" "" "" "" "" "" "[ D J.x- V R.z" "> R Q.i+ C G.h " "" "+ Z V.a+ U C.n " "" "" "" "" "" "" "" "+ D U.s< W C.x " "" "" "" "" "" "] F A.j> J L.h " "" "" "" "" "" ". N U.r- R F.n " "" "" "" "" "- V N.s- T L.n " "" "" "" "- V E.i- T G.n" "- O M.r- Z A.g " "" "" "" "" "" "" "- A Q.h- S Z.n " "" "" "" "" "" "- Q G.q- L X.p " "" "- Z D.k. M C.a" "- P M.e- V S.u " "" "" "" "" "" "" "- S I.k- B W.o " "" "" "" "" "" "" "" "" "" "- C W.o- U U.m " "" "" "" "" "" "" "" "" "- V C.o. Q F.i " "" "" "" "" "" "" "" "" "" "- P N.w- S Y.l " "" "" "" "" "" "" "" "" "" "[ J R.h- D A.k " "" "" "" "" "" "" "" "" "" "- N A.o- Q L.g " "" "> P L.c+ L T.n " "" "" "" "" "" "" "< O W.o] P O.v " "" "" "" "" "" "> K G.h- T O.j " "" "" "" "" ". P J.u[ O W.x " "" "" "" "" "" "- I F.c- N Z.c" "- S U.e- L D.y " "" "" "" "" "" "" "" "" "" "> E Y.l+ X Y.l " "" "" "" "" "" "< L S.q] P K.c " "" "" "" "" "" "" "> D V.l+ M F.a " "" "" "" "" "" "" "" "+ F F.f+ C N.z " "" "" "" "" "" "" "" ". E D.d- P J.p " "" "" "" "" "" "- Q Z.c- E T.w " "" "" "" "" "[ O E.t- C G.w " "" "" "" "" "" "> D F.a+ S X.d " "" "" "" "+ V Z.a+ O V.x " "" "" "" "" "" "" "" "" "+ I Z.z< N H.f " "" "" "" "" "] E L.n> U V.m " "" "" "" ". G E.r- P T.n " "" "" "" "" "" "- H U.p- N J.v " "" "" "" "" "" "" "" "" "" "- D W.g- Q P.f " "" "" "" "" "" "- I S.w- L L.d " "" "" "" "" "" "" "" "- O S.j- I W.u " "" "" "" "" "" "" "" "- F J.m- Q D.s " "" "" "- T C.v. F L.z " "" "" "" "" "" "" "" "+ C J.k. Z B.m " "" "" "" "" "" "" "" "" "" "+ Y J.r+ B G.n " "" "" "" "" "" "" "" "" "+ P P.c+ T F.x " "" "" "" "" "" "" "" "" "" "+ U A.k+ A W.x " "" "" "" "" "" "" "" "" "+ L R.s+ U U.b " "" "" "" "" "" "" "" "+ Z B.t+ C J.g " "" "" "" ". Z Q.v+ Q W.l " "" "" "[ M C.i- J A.p" "- N V.p- V V.s " "" "- V O.v> M C.w " "" "" "" "" "" "" "" "+ M O.f< I U.j" "] A G.b> Z D.z " "" "" "" "" "+ O J.h+ X K.u " "" "" "" "" "" "" "+ Y I.r. Y E.u " "" "" "" "" "" "" "" "" "- V P.s- R I.g " "" "- Q J.u[ V I.e " "" "" "" "" "- D B.g- C Z.f " "" "" "" "" "" "" "- C E.f- U K.k " "" "" "" "" "" "" "" "" "- Z P.e> D N.y " "" "" "" "" "+ V K.k+ A J.b" "< C E.l] B E.t " "" "" "> D R.p. D L.a " "" "" "" "+ A H.q+ H Y.w " "" "" "" "+ K A.o. M X.k " "" "" "" "- M C.o- B N.c " "" "- F T.w- J F.u " "" "" "" "" "- N Q.i- W K.j " "" "" "- D V.q. E W.g " "" "" "+ C X.p+ R T.y" "+ R P.j+ B S.a " "" "+ D B.i. M G.c" "+ N B.l[ I N.x " "" "" "" "" "" "" "" "" "- Z R.w- P W.n " "" "" "" "" "" "" "" "- C B.h- R P.m " "" "" "" "> S I.t+ H L.n " "" "" "" "" "" "" "" "< G O.e] T Z.w " "" "" "" "" "" "> A Q.k+ N V.q " "" "" "" "" "+ E S.y+ D C.n " "" "" "" ". U E.f- Z A.p" "[ Y C.q- D O.p " "" "" "" "" "" "" "- D R.g- M A.k " "" "" "" "" "> Q D.j+ D E.r " "" "" "" "+ W W.p< E T.y " "" "" "" "" "" "" "" "" "] V P.g> G E.x " "" "" "- L O.p. S P.r " "" "" "" "" "" "" "" "+ B F.q+ G X.x " "" "" "" "" "" "" "" "" "" "+ W X.q+ O E.o" "+ E Z.v. Q G.w " "[ H H.n- C F.x " "" "" "- N L.j- Z N.t " "" "" "" "" "" "" "" "- L G.e- F Y.y " "" "" "" "" "" "" "" "> C L.l+ T R.l " "" "" "" "" "" "" "" "" "" "+ Q F.e< Z D.g " "" "" "" "" "" "" "" "" "" "] W I.i> S T.z " "" "" "" "+ V Z.s+ Y W.r " "" "" "" "" "" "" "" ". R C.e+ O A.d " "" "" "" "" "" "" "" "" "+ J P.b[ H W.i " "" "" "" "" "" "- L F.u- H D.k" "- H Q.w> L Y.c " "" "" "" "" "" "" "" "+ B F.p+ J U.y " "" "" "< X U.c] N E.p " "" "" "" "" "" "" "" "" "> W M.k. J W.n " "" "" "> C K.i- T R.l " "" "" "" "" "" "" "" "" "" "[ S A.c- D W.w " "" "" "" "" "" "" "" "" "" "- R I.g- M F.p " "" "" "" "" "" "" "" "" "> I V.e+ Q U.j " "" "" "< T U.p] I C.j " "" "" "" "" "> W E.t- U O.y " "" "" "" "" "- I S.l. H M.t " "" "" "" "[ A Z.w- F H.x " "" "" "" "" "" "" "" "" "- M A.p- S J.k " "" "" "" "" "" "" "" "" "" "> F X.s+ F A.a" "< P A.c] I G.r " "" "> Y W.m- K F.l " "" "" "" "" "" "" "- V W.e. G Q.u " "" "" "" "" "" "" "" "" "" "+ S C.t+ F W.y " "" "" "" "+ I S.v. N Y.k " "" "" "" "" "" "" "" "" "" ". U Q.f+ V K.f " "" "+ N S.m+ W Y.u " "" "" "+ X X.j+ I I.m " "" "" "" "" "" "+ V I.g+ B Z.f" ". Q Q.q- L A.e " "" "" "" "" "" "[ F O.w- Z K.v " "" "- P I.b- M X.r " "" "" "" "" "" "- H O.n> I R.e " "" "" "+ V S.b< P U.a " "" "" "" "] Y G.g> S C.l " "" "" "" "" "" "" "" "" "+ X I.z+ P I.n"+ Q E.q" ""- Z B.m " "" "" "" "" "" "" "[ K O.a- F R.d " "" "" "- C P.u- O T.h " "" "" "" "" "" "" "" "" "- T I.q- O K.a " "" "" "- H C.n- G Y.t " "" "" "" "" "" "" "" "> W C.a+ M T.a " "" "< D N.h] V T.r " "" "" "" "" "" "" "" "> D K.b- M S.i " "" "" "" "" "" "" "" ". U Y.u- I J.x " "" "" "" "" "[ X C.e- K U.m " "" "" "> L W.y+ F X.l " "" "" "+ D B.n+ V N.e " "" "" "" "" "" "" "" "" "+ L F.g+ T Q.k " "" "" "" "" "" "" "" "< L Z.f] V I.b " "" "" "" "" "" "" "" "" "> I O.s+ D F.p " "" "" "" "" "" "" "+ D P.g. W B.j" "+ J S.z+ X U.l " "" "+ J A.o+ L V.t " "" "" "" "" "" "" "" "" "+ R P.x+ Y L.j " "" "" "+ H W.s. Q P.l " "" "" "" "" ". N U.d+ C K.l " "" "" "" "" "" "" "" "+ U B.h+ W L.n " "" "" ". X L.k[ Q Y.v " "" "" "- F B.r- B X.z " "" "" "" "" "- M F.t> W L.v " "" "" "" "" "+ O W.x< F W.g " "" "" "" "" "" "] L P.y> M A.m " "" "" "" "" "" "" "- I K.x- F A.i " "" "" "" "" "- Z U.a- M M.t " "" "" "- C L.s. C C.j " "" "" "" "" "" "" "" "" "- T R.u- N U.i " "" "" "" "" "" "" "- U R.p[ F D.x " "" "" "" "" "" "" "" "" "- S P.o> C H.d " "" "" "" "" "" "" "" "+ O W.p+ N W.i " "" "" "" "" "" "" "" "" "+ U A.r< O A.k " "" "" "" "" "" "" "" "" "" "] A M.y> W H.m " "" "" "" "" "" "" "" "" ". G J.g- L M.p " "" "" "" "" "[ J K.k- P E.n " "" "" "" "" "" "" "- S V.y- U U.j " "" "" "" "" "" "" "" "> P T.v+ Z F.h" "< X R.g] J A.d " "" "" "" "" "" "" "" "> A U.f- U G.u " "" "" "" "- P L.o- I V.q " "" "" "" "" "" ". B Y.b+ H Y.r " "" "" "" "" "+ O Y.u+ P N.w " "" ". F K.n- D L.c " "" "" "" "" "- I G.g- D Y.m " "" "" "" "" "" "" "" "" "- B Y.h- S H.x " "" "" "" "- N R.k. K A.n " "" "" "" "" "" "- N F.r- F S.l " "" "" "" "" "" "" "" "" "- Q L.e- L J.f" "- S Q.o- K U.k " "" "- C I.h- A N.s" ". N P.t- D J.b " "" "" "" "" "" "[ I S.t- D A.j " "" "" "" "" "" "- N F.a- Z S.b " "" "" "" "" "> A G.g+ Z N.g " "" "< A K.t] U W.g " "" "" "" "" "" "> V D.b. Y U.j " "" "" "" "" "" "" "" "" "" "+ K F.j+ G M.t " "" "+ J E.c+ X S.i " "" "" "" "" "" "" "+ K F.r+ Z R.e " "" "" "" "" "" "" "" "+ S X.p+ Q R.h " "" "" "" "" "+ E L.p+ J U.p " "" "" "" "" "" "" "" "+ F G.z. K S.s " "" "" "- Y O.k- C P.i " "" "" "" "" "" "" "- H N.v- O C.k " "" "" "" "- S J.x- H O.p " "" "" "- X D.p- W E.h " "" "" "- K F.v- B X.q " "" "" "" "- M Z.a- W E.d " "" "" "" "" "" "" ". N Y.a+ T H.r " "" "" "" "" "" "" "" "" "+ R S.c+ U Q.k " "" "" "" "" "" "" "" "+ U D.s[ U L.o " "" "" "" "- E U.u> V C.l " "" "" "" "" "" "" "" "" "" "+ N U.d+ E H.x " "" "" "" "" "< M W.v] C S.i " "" "" "" "> F U.p+ G F.a " "" "" "" ". G S.c- K C.l " "" "" "" "" "" "[ M J.p- R G.w " "" "> Z M.q+ Z J.e " "" "" "" "+ Y Q.k+ S L.c " "" "" "" "" "+ Q R.i< Y C.l " "" "" "" "" "] L F.h> M K.r " "" "" "" "" "" "" "" ". Z K.q- K R.c " "" "" "" "" "" "" "" "" "" "[ Q R.u- W L.x " "" "" "" "" "" "" "- D C.g- Z T.a " "" "" "" "" "" "" "" "" "" "> L G.u+ R M.h " "" "" "+ G U.c< R C.s " "" "] N D.n> W T.u " "" "" "" "" "" "" "" "- I X.d- W Q.l " "" "" "" "" "" "" ". H Z.a- P C.n " "" "- F P.i- R O.x " "" "- R R.w- J Q.j " "" "- H R.y- C D.y " "" "" "" ". L A.t+ K C.t " "" "" "" "" "" "" "" "" "[ G P.o- N N.j " "" "- Q V.x- S V.b " "" "" "" "> U K.u+ Q F.x " "" "" "" "" "" "< M U.v] P I.c " "" "" "" "" "" "" "" "" "> S U.t. U G.t " "" "" "+ Z N.k[ X Y.t " "" "" "" "- E Y.v> L W.c" "+ K S.g+ S B.h " "" "" "+ K V.a< Z C.z " "" "" "] G C.n> J Z.u " "" "" "" "" "" "" "" ". U K.t- G V.o " "" "" "" "" "- K Z.f[ K J.e " "" "" "" "" "" "" "" "" "" "- J B.l- S N.f " "" "" "" "" "" "" "" "" "- O L.w> G J.z " "" "" "+ X V.y< G F.a " "" "" "" "" "" "" "" "] M V.z> L N.x" "- Z R.r. V R.x " "" "" "" "[ G R.h- D O.g " "" "" "" "" "" "" "> W I.g+ R C.x " "" "" "" "+ S F.h+ B G.m " "" "< B G.f] L D.z " "" "" "" "" "> F O.a+ K M.h " "" "" "" "" "" "+ V F.x. P V.w " "" "" "" "" "" "" "" "" "- C X.z. A L.x " "" "" "" "" "" "" "" "" "+ M J.b+ I O.t " "" "" "" "" "" "+ Z Y.q. N I.h" "- T W.e[ W K.o " "" "" "" "" "" "" "" "" "- S M.a- P O.d " "" "" "" "" "- B T.g> W K.s " "" "" "" "" "" "" "" "+ D V.g< O J.f " "" "" "" "" "" "] O O.r> C Z.f " "" "- W L.b. P F.d " "" "" "" "" "" "" "" "" "" "+ Y P.t[ H O.h " "" "" "" "- O Z.c- C A.z " "" "" "" "" "- X Y.g- O Q.g " "" "" "" "" "" "- N E.n> G C.s " "" "" "" "" "" "" "+ B I.g< Z P.a " "" "" "] H F.y> G J.j " "" "" "" "" "" "+ N R.u. G D.q " "" "" "" "" "" "" "" "- A F.e- P C.i " "" "" "" "- W L.i- L V.d " "" "" "" "" "" "- X P.r- Y S.x " "" "- F C.n- G N.o" "- Z A.q. K Q.j " "" "" "" "" "" "[ S B.n- W C.l " "" "" "" "" "" "" "- N Q.g- O M.h " "" "" "" "" "" "" "" "" "" "> J T.f+ M N.h " "" "" "" "" "" "< O C.w] J E.l " "" "" "" "" "" "" "" "" "" "> F N.c. Z H.d " "" "" "" "" "" "- G M.n- L S.x " "" "" "" "" "" "- S Z.h- C M.l" ". C S.z+ G I.a " "" "" "" "" "" "" "" "[ D W.g- C P.j " "" "- H V.t- C T.p " "" "" "" "- F F.o> Y A.s " "" "" "" "" "" "" "" "" "" "+ O R.g< I V.h " "" "" "" "" "" "] D H.p> H D.j " "" "" "" "" "+ O G.c+ I Z.p " "" "" "" "" "" "" "" "+ S R.f. I J.m " "" "" "" "" "" "+ H Z.l+ X V.h " "" "" "" "" "" "" "[ Y M.m- L O.r " "" "" "" "" "" "" "" "" "" "> B Z.n+ D W.x " "" "" "" "+ Z C.m+ X Q.t " "" "" "" "" "" "" "" "" "" "< S E.w] L Y.n" "> V F.b. V S.z " "" "+ C M.n+ L K.n" "+ S S.y+ S O.b " "" "" "" "" "" "" "" "" "" "+ R G.y+ K X.j " "" "" "" "+ F O.g+ A C.z " "" "+ R L.q. S N.g " "" "" "" "" "" "" "" "" "" "+ X L.x+ C F.x " "" "" "" "" "" "" "+ C O.x. G A.h " "" "" "" "" "" "" "" "" "" "[ Z L.u- A P.o " "" "" "" "- O H.i> U Q.v" "+ F A.d+ E T.n " "" "" "+ B S.o+ F B.y " "" "" "+ L S.r< O X.n " "" "" "" "" "" "" "] C D.h> H O.d " "" "" "" "" "" "+ X O.x+ H Q.b " "" "+ E S.n. M X.q " "" "" "- D S.j- U E.l " "" "" "" "" "" "" "[ H J.g- A R.a " "" "" "" "> T X.s+ D C.d " "" "" "" "" "" "+ G X.p+ I J.l " "" "" "" "" "" "" "" "" "" "+ F K.i< C Q.h" "] X L.c> X V.i " "" "" "" "" "+ B Q.t. S J.j " "" "" "" "" "- L J.v- D C.h " "" "" "" "" "" "- F D.f- R N.u " "" "" "" "" "" "- T Y.p- R S.p " "" "" "" "" "" "" "- V S.y- X U.r " "" "" "" "" "" "" "- H E.r- H O.l" ". I A.a+ C S.u " "" "" "" "" "" "" "" "" "+ S B.q+ L N.j " "" "" "" "" "" "" "+ B F.u+ L X.r " "" "" "" "" "" "" "+ V C.b. K P.l" "- U K.l[ P S.q " "" "" "" "" "" "" "- Z E.u- P M.s " "" "" "" "" "" "- I P.z- A W.f " "" "" "" "> W A.x+ S B.l " "" "" "" "" "" "< P H.m] T C.l " "" "" "" "" "" "" "" "" "" "> D N.o+ H T.w " "" "" "+ H X.n+ S Y.g " "" "" "" "" ". L C.b- M N.h " "" "" "" "" "- D B.q- X C.s " "" "" "" "" "" "[ D Y.o- L W.z " "" "" "> D N.n+ C P.o " "" "" "" "" "+ A V.a+ X X.w " "" "" "" "" "+ L T.l< V K.s" "] C E.f> C I.o " "" "" "" "" "" "" "" "" "" ". O C.a- L B.a " "" "- E Q.c- I F.h " "" "" "" "" "" "- A Y.q- K T.a" "- C Y.h- F A.e " "" "" "" "" "" "- M D.h- L I.z " "" "" "" "" "- X G.c- M F.x " "" "" "" "- P U.s. N F.f " "" "" "" "" "" "" "" "" "+ A E.c+ F B.k " "" "" "" "" "" "" "+ Q K.f+ W I.y " "" "" "" "" "+ E S.a+ R S.o " "" "" "+ N Y.a. J G.u " "" "+ L V.i+ X T.y " "" "" "+ S F.l+ O Y.i " "" "" "" "" "" "" "" "" "" "+ Q V.e+ S Q.l " "" "" "" "" "" "" ". O A.g+ W S.r " "" "" "" "" "" "" "" "" "+ Z D.e[ N A.l " "" "" "" "- A D.b> I K.a " "" "" "" "" "" "+ E U.c+ E O.x " "" "" "" "" "" "" "" "+ P D.h< G K.g " "" "" "" "" "] G X.b> H W.g " "" "" "" "" "" "" "" "+ K D.c+ H B.f " "" "" ". K Z.e+ M P.p " "" "" "" "" "" "" "" "" ". A L.n- O B.m" "- P T.z- C S.w " "" "" "" "" "" "" "" "- Q Y.e[ I N.g " "" "- X A.q> Y L.i" "+ I Y.u+ T A.w " "" "+ B Z.t< W U.z " "" "" "" "" "" "" "] R S.i> U S.a " "" "" "" "" "" "" "" "" ". O T.a- M D.f " "" "" "" "" "" "- H U.s- V O.g " "" "" "" "" "" "" "" "- O H.p- O L.v " "" "" "" "" "" "" "" "" "" "- X R.b- U V.w " "" "" "" "" "" "- G H.w- E R.n " "" "" "" "" "" "" "" "" "" "- R J.c- H S.p " "" "" "" "- J A.x. F W.h " "" "" "" "" "" "" "" "" "[ J R.s- F R.c " "" "" "" "" "" "" "> L H.w+ Z A.z " "" "" "" "+ Z O.s+ S D.u " "" "" "" "" "" "" "" "< B C.k] J F.k" "> P C.t+ H C.q " "" "" "" "" "" "" "" "" "+ N B.e. V S.t " "" "" "" "" "[ Q M.p- M C.m " "" "" "" "" "" "" "- B A.r- Q C.y " "" "" "> F D.t+ A G.r " "" "< A V.d] X H.m " "" "" "" "" "" "" "" "> J E.x- Y P.d " "" "- E T.h- P I.p " "" "" "" "" "" "" "" "- R O.f. I B.f" "+ P M.n+ N L.j " "+ N Z.c[ Y V.z " "" "" "- K G.k> D F.u " "" "" "+ L D.e+ W I.k " "" "" "" "" "" "+ P M.k< X Y.y " "" "" "" "" "" "] O L.n> Q K.e " "" "" "" "+ R M.t+ C B.i " "" "" ". E J.g+ I C.a " "" "" "" "" "" "" "" "" "" "+ C C.k+ B I.e " "" "" "" "" "" "" "" "" "+ T U.d+ K D.x " "" "" "" "" "" "" "+ F K.p+ M O.h " "" "" "" "" "" "" "+ Q H.e. M Z.a " "" "" "" "+ I Q.m+ W M.d " "" "" "" "+ A I.y+ G H.u " "" "" "" "" "" "" "+ E U.j. Z W.z " "" "" "" "" "" "" "" "" "- G X.r- R V.h " "" "- I P.a- M X.d " "" "" "" "" "" "" "" "" "- V M.q- C M.z " "" "" "" "" "" "- P K.l- N L.r " "" "" "" "" "" ". L D.t- G A.f " "" "" "" "" "" "" "" "" "" "[ T J.f- M X.p " "" "" "" "" "" "" "- V P.t- G Z.f " "" "> T O.h+ S Q.r " "" "" "" "" "" "" "" "" "< Z S.r] D P.v " "" "" "" "" "" "" "> G Q.n- F M.v " "" "" "" "" "" "" "" "" "- P Z.g. N S.d " "" "" "" "" "" "" "" "" "" "+ E G.x[ U N.t " "" "" "- R J.z> Y Y.e " "" "" "" "" "" "" "" "+ V N.x+ V U.s " "" "" "" "" "+ W P.s< S P.m " "" "" "" "" "" "" "" "] G O.x> X J.d " "" "" "" "" "" "+ X E.l. Z T.o " "" "" "" "+ T N.l+ L U.t " "" "" "" "+ C L.i+ Z M.g" "+ M K.k+ E P.p " "" "" "" "" "+ P T.l+ S Z.h" ". F W.k- Q D.q " "[ O I.r+ K W.r " "" "" "+ J B.x> F A.s " "" "" "" "" "" "" "" "" "- Y D.b- O H.r " "" "" "" "" "" "- W N.a< H S.e" "] N F.o> Q I.y " "" "" "" "" "" "+ B V.w. Q G.b " "" "" "- J R.i[ B M.j" "- Q R.a- K V.v " "" "" "- M S.b> W O.i " "" "" "" "" "" "" "" "" "+ C D.t+ T X.o " "" "" "" "" "" "" "" "" "< S C.m] T F.f " "" "" "" "" "" "" "" "" "" "> E Q.z- O B.w " "" "" "" "" "" "" ". Z T.a+ X L.t" "+ H U.f+ B E.x " "" "" "" "" "" "" "" "+ K A.c+ A E.p " "" "" "" "" "+ S N.v+ P P.h " "" "" "" "" "" "" "" "+ R C.f+ I I.y " "" "" "" "" "" "" "" "" "+ N C.h. U P.x " "" "" "" "" "" "" "- D Q.c- I K.k " "" "" "" "" "" "" "" "" "- U U.c- A X.j " "" "" "" "" "" "" "" "" "" "- N B.u. A J.p " "" "" "" "" "[ N K.j+ L H.t " "" "" "" "" "+ D E.j> T Q.c" "- B U.z- A N.e " "" "" "- C J.k< D O.n " "" "" "" "" "" "" "" "" "] O U.c> Z J.e " "" "" "" "" "" "+ K E.m+ B O.p" ". H S.l[ T N.r " "- Z M.e> D Q.i " "" "" "" "" "" "" "" "+ K B.v+ S P.o " "" "" "" "" "+ Q O.w< Y D.o " "" "" "" "] I C.n> R H.i " "" "" "" "" "" "" "- I F.z. L Q.t " "" "[ W U.q- A C.q " "" "" "" "- H U.l- V P.f " "" "" "- J Z.n> C Y.j " "" "" "" "" "" "" "+ E Y.b< J Q.g " "" "" "" "" "" "] F W.x> X H.c " "" "+ Z X.r+ O K.g " "" "" "" "+ Y Q.f. X Z.d " "" "" "" "" "" "" "[ O G.z- F K.u " "" "> P Z.o+ M D.s " "" "" "" "" "" "" "" "+ L G.h+ Z M.l " "" "" "" "" "" "" "" "" "" "< J L.y] O U.x " "" "" "" "" "> L K.q+ P U.c " "" "" "" ". F H.l+ X W.j " "" "" "" "" "" "" "+ N I.x. U A.u " "" "" "" "" "" "" "" "- Y B.m[ X W.a " "" "" "" "" "" "" "" "" "" "- B X.u- V G.w " "" "" "" "" "- D N.d> M Q.g " "" "" "" "" "" "" "" "+ I I.w< E P.u " "" "] F V.k> I U.s " "" "" "" "" "" "" "- F P.b- B H.u " "" "" "" "" "" ". J X.n+ G E.e " "" "" "" "" "" "" "" "" "" ". U J.t[ T C.l " "" "" "" "" "- O K.g> T L.r " "" "" "" "" "" "" "" "+ W A.a+ O Z.g " "" "+ A N.e< Q N.q " "" "" "" "" "] W U.k> Y J.w " "" "" "" "" "" "" "" "" "+ V V.k+ Y L.w " "" "" "" ". S V.k+ P C.h " "" "" "" "" "" "+ C G.v+ N F.d " "" "" "" "" "" "" "" "" "" "+ K P.u+ R J.z " "" "+ E R.y+ I I.p " "" "" "" "" "" "" "" "" "" "+ Y H.z+ G U.v " "" "+ T E.o+ G S.g " "" "" "" ". S A.u. Z X.n " "" "- L S.x[ M X.z " "" "" "" "" "" "" "" "" "- V Z.e- S C.p " "" "" "" "" "- T H.m> E B.m " "" "" "" "" "" "" "" "" "" "+ Q T.t< N Z.g " "" "" "] R I.y> B J.k " "" "" "" "" ". V V.r- L T.x " "" "" "" "" "" "" "" "[ L Z.s- T Y.p " "" "" "" "" "" "- N A.p- W X.q " "" "" "" "" "" "" "- M D.t> Z Y.r " "" "" "" "+ B Q.u< L C.m" "] V R.j> Z D.y " "+ A C.j+ P S.w " "" "" "" ". V K.r- E N.s " "" "" "" "" "- C F.n- Q B.p " "" "" "" "" "" "[ R E.d- H Y.r " "" "" "" "" "" "> H D.v+ X E.h" "+ V R.j+ C C.m " "+ C Q.j< Q X.b " "" "" "" "" "" "" "" "" "] Y J.g> K Y.s " "" "" "" "" "" "" "" ". T R.i- K R.f " "" "" "" "" "" "" "" "- B U.o- Z I.n " "" "" "" "" "" "" "" "- I X.s- G D.p" "- B C.i- K G.c " "- V G.i- P Y.f " "" "" "" "- V G.t- U D.s " "" "" "" "" "" "" "" "" "- K P.f. F X.m " "" "" "" "" "- O B.l- S C.e " "" "" "" "" "" "- B K.l. D Z.f " "" "- U K.m- J F.z " "" "" "" "[ H N.l- D G.i " "" "" "" "" "" "" "" "" "- Y T.u- Z R.s " "" "> Z O.p+ D V.g" "< Q W.w] W K.w " "" "" "" "" "" "> O V.l- I A.w " "" "" "" "" "" "" ". B L.j+ H C.k " "" "" "" "" "" "" "+ B W.w[ H T.q " "" "" "" "" "" "" "" "- Z F.z- H S.u" "- K B.j> M T.w " "" "" "" "" "" "" "+ Q N.d+ G K.a " "" "" "" "" "" "< W U.e] H M.u " "" "" "" "" "> B Q.u. O J.r " "" "" "" "" "" "" "" "- Z G.n- H K.i " "" "" "" "" "" "" "" "" "- I E.j- X U.y " "" "" "" "" "- L O.u- J D.h " "" "" "- X F.q- P J.v " "" "- E T.u- X M.c " "" "" "" "" "- S P.y. U S.z " "" "" "" "" "" "" "" "" "+ E C.l+ S N.y " "" "+ T N.r+ J F.s " "" "" "" "" "" "" "" "+ U I.x+ I P.o " "" "" "" "+ F Z.e+ P E.k " "" "" "" "" "" "" "+ G J.k+ X Y.w " "" "" "" "" "" "" "+ Z Z.d+ Y B.b " "" "+ F A.d. R W.p " "" "" "- M A.z- Y R.l " "" "" "" "" "" "" "- Z L.a- E X.h " "" "" "" "" "" "" "" "" "" "- I G.d- H J.b " "" "- U E.n. H X.k " "" "" "- V E.s- S F.h " "" "" "" "[ L A.x- A C.l " "" "" "" "- P O.q- X J.x " "" "" "> M X.u+ W H.s " "" "" "< H T.p] V U.o " "" "" "" "" "> P Z.v- C K.a " "" "" "- U J.p. V N.l " "" "" "" "" "" "" "" "" "" "[ L T.u- N K.d " "" "" "" "" "" "" "" "" "> I G.u+ Z N.g " "" "" "" "" "" "" "" "" "" "+ H K.j+ M S.h " "" "" "" "" "" "" "" "< F M.t] D J.z " "" "" "" "" "" "" "> E K.d+ J M.c " "" "" "" "" "" "" "" "" "+ O M.u. A P.k " "" "" "" "" "" "" "" "" "+ R V.v+ U I.e " "" "+ Z C.m+ L L.m " "" "" "" "" "+ B Z.d+ O R.s " "" "" "" "" "" ". B D.m- W R.x " "" "" "" "" "" "" "" "- W H.b. S R.g " "" "- Y N.a- P L.b " "" "" "" "" "" "" "" "[ T M.k- D H.x " "" "" "" "" "" "" "" "" "- P I.s- U A.z " "" "" "" "> E B.m+ O I.t " "" "" "" "" "< T N.c] A D.t " "" "" "> Q I.y- Z P.y " "" "" "" "" "" "" "" "" ". M B.t- N E.j " "" "" "- K T.z- Y S.p " "" "" "" "" "" "" "" "[ D J.x- V R.z" "> R Q.i+ C G.h " "" "+ Z V.a+ U C.n " "" "" "" "" "" "" "" "+ D U.s< W C.x " "" "" "" "" "" "] F A.j> J L.h " "" "" "" "" "" ". N U.r- R F.n " "" "" "" "" "- V N.s- T L.n " "" "" "" "- V E.i- T G.n" "- O M.r- Z A.g " "" "" "" "" "" "" "- A Q.h- S Z.n " "" "" "" "" "" "- Q G.q- L X.p " "" "- Z D.k. M C.a" "- P M.e- V S.u " "" "" "" "" "" "" "- S I.k- B W.o " "" "" "" "" "" "" "" "" "" "- C W.o- U U.m " "" "" "" "" "" "" "" "" "- V C.o. Q F.i " "" "" "" "" "" "" "" "" "" "- P N.w- S Y.l " "" "" "" "" "" "" "" "" "" "[ J R.h- D A.k " "" "" "" "" "" "" "" "" "" "- N A.o- Q L.g " "" "> P L.c+ L T.n " "" "" "" "" "" "" "< O W.o] P O.v " "" "" "" "" "" "> K G.h- T O.j " "" "" "" "" ". P J.u[ O W.x " "" "" "" "" "" "- I F.c- N Z.c" "- S U.e- L D.y " "" "" "" "" "" "" "" "" "" "> E Y.l+ X Y.l " "" "" "" "" "" "< L S.q] P K.c " "" "" "" "" "" "" "> D V.l+ M F.a " "" "" "" "" "" "" "" "+ F F.f+ C N.z " "" "" "" "" "" "" "" ". E D.d- P J.p " "" "" "" "" "" "- Q Z.c- E T.w " "" "" "" "" "[ O E.t- C G.w " "" "" "" "" "" "> D F.a+ S X.d " "" "" "" "+ V Z.a+ O V.x " "" "" "" "" "" "" "" "" "+ I Z.z< N H.f " "" "" "" "" "] E L.n> U V.m " "" "" "" ". G E.r- P T.n " "" "" "" "" "" "- H U.p- N J.v " "" "" "" "" "" "" "" "" "" "- D W.g- Q P.f " "" "" "" "" "" "- I S.w- L L.d " "" "" "" "" "" "" "" "- O S.j- I W.u " "" "" "" "" "" "" "" "- F J.m- Q D.s " "" "" "- T C.v. F L.z " "" "" "" "" "" "" "" "+ C J.k. Z B.m " "" "" "" "" "" "" "" "" "" "+ Y J.r+ B G.n " "" "" "" "" "" "" "" "" "+ P P.c+ T F.x " "" "" "" "" "" "" "" "" "" "+ U A.k+ A W.x " "" "" "" "" "" "" "" "" "+ L R.s+ U U.b " "" "" "" "" "" "" "" "+ Z B.t+ C J.g " "" "" "" ". Z Q.v+ Q W.l " "" "" "[ M C.i- J A.p" "- N V.p- V V.s " "" "- V O.v> M C.w " "" "" "" "" "" "" "" "+ M O.f< I U.j" "] A G.b> Z D.z " "" "" "" "" "+ O J.h+ X K.u " "" "" "" "" "" "" "+ Y I.r. Y E.u " "" "" "" "" "" "" "" "" "- V P.s- R I.g " "" "- Q J.u[ V I.e " "" "" "" "" "- D B.g- C Z.f " "" "" "" "" "" "" "- C E.f- U K.k " "" "" "" "" "" "" "" "" "- Z P.e> D N.y " "" "" "" "" "+ V K.k+ A J.b" "< C E.l] B E.t " "" "" "> D R.p. D L.a " "" "" "" "+ A H.q+ H Y.w " "" "" "" "+ K A.o. M X.k " "" "" "" "- M C.o- B N.c " "" "- F T.w- J F.u " "" "" "" "" "- N Q.i- W K.j " "" "" "- D V.q. E W.g " "" "" "+ C X.p+ R T.y" "+ R P.j+ B S.a " "" "+ D B.i. M G.c" "+ N B.l[ I N.x " "" "" "" "" "" "" "" "" "- Z R.w- P W.n " "" "" "" "" "" "" "" "- C B.h- R P.m " "" "" "" "> S I.t+ H L.n " "" "" "" "" "" "" "" "< G O.e] T Z.w " "" "" "" "" "" "> A Q.k+ N V.q " "" "" "" "" "+ E S.y+ D C.n " "" "" "" ". U E.f- Z A.p" "[ Y C.q- D O.p " "" "" "" "" "" "" "- D R.g- M A.k " "" "" "" "" "> Q D.j+ D E.r " "" "" "" "+ W W.p< E T.y " "" "" "" "" "" "" "" "" "] V P.g> G E.x " "" "" "- L O.p. S P.r " "" "" "" "" "" "" "" "+ B F.q+ G X.x " "" "" "" "" "" "" "" "" "" "+ W X.q+ O E.o" "+ E Z.v. Q G.w " "[ H H.n- C F.x " "" "" "- N L.j- Z N.t " "" "" "" "" "" "" "" "- L G.e- F Y.y " "" "" "" "" "" "" "" "> C L.l+ T R.l " "" "" "" "" "" "" "" "" "" "+ Q F.e< Z D.g " "" "" "" "" "" "" "" "" "" "] W I.i> S T.z " "" "" "" "+ V Z.s+ Y W.r " "" "" "" "" "" "" "" ". R C.e+ O A.d " "" "" "" "" "" "" "" "" "+ J P.b[ H W.i " "" "" "" "" "" "- L F.u- H D.k" "- H Q.w> L Y.c " "" "" "" "" "" "" "" "+ B F.p+ J U.y " "" "" "< X U.c] N E.p " "" "" "" "" "" "" "" "" "> W M.k. J W.n " "" "" "> C K.i- T R.l " "" "" "" "" "" "" "" "" "" "[ S A.c- D W.w " "" "" "" "" "" "" "" "" "" "- R I.g- M F.p " "" "" "" "" "" "" "" "" "> I V.e+ Q U.j " "" "" "< T U.p] I C.j " "" "" "" "" "> W E.t- U O.y " "" "" "" "" "- I S.l. H M.t " "" "" "" "[ A Z.w- F H.x " "" "" "" "" "" "" "" "" "- M A.p- S J.k " "" "" "" "" "" "" "" "" "" "> F X.s+ F A.a" "< P A.c] I G.r " "" "> Y W.m- K F.l " "" "" "" "" "" "" "- V W.e. G Q.u " "" "" "" "" "" "" "" "" "" "+ S C.t+ F W.y " "" "" "" "+ I S.v. N Y.k " "" "" "" "" "" "" "" "" "" ". U Q.f+ V K.f " "" "+ N S.m+ W Y.u " "" "" "+ X X.j+ I I.m " "" "" "" "" "" "+ V I.g+ B Z.f" ". Q Q.q- L A.e " "" "" "" "" "" "[ F O.w- Z K.v " "" "- P I.b- M X.r " "" "" "" "" "" "- H O.n> I R.e " "" "" "+ V S.b< P U.a " "" "" "" "] Y G.g> S C.l " "" "" "" "" "" "" "" "" "+ X I.z+ P I.n""";import ast print(ast.literal_eval(input())+ast.literal_eval(input())) ``` [Answer] # Python 3 - Hello, World! ``` 3;s="!dlroW ,ollexH";(print(s[-1]+s[-3::-1]),")")#"`[;:]. ``` (Second language technically doesn't print a newline, but the interpreter adds one automatically) ...I just realised that I failed to read the date of the challenge, and the secondary language postdates the challenge. Many apologies. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes, safe ``` ”Ÿ™,‚ï! ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcPcozsetSzSedQw6/B6xf//AQ "05AB1E – Try It Online") Also works in * 05AB1E (legacy) * 2sable [Answer] # [><>](https://esolangs.org/wiki/Fish), 39 bytes, safe ``` vdvII$$$$$$$$$>r+n;O@ >ri68*-i~i68*-^u ``` [Try it online!](https://tio.run/##S8sszvj/vyylzNNTBQbsirTzrP0duOyKMs0stHQz68BUXKnC//@GCoYA "><> – Try It Online") Works in ><>, Gol><>, somehow not \*><>, and *Backhand*. ## Explanation ``` vdv Push the speed down twice II Take 2 inputs $$$$$$$$$>r A bunch of stuff that do nothing + Add n; More nothing O Output @ End ``` [Answer] # Hello, World!, cracked ``` #| print("Hello, World!")# wh|#(write-line "Hello, World!") ``` This works in Python, Lisp, and ~~one other language~~ [Deadfish~](https://esolangs.org/wiki/Deadfish~). ]
[Question] [ **This question already has answers here**: [Finding "sub-palindromes".](/questions/183/finding-sub-palindromes) (37 answers) Closed 6 years ago. A [palindrome](https://en.wikipedia.org/wiki/Palindrome) is a string which is the same when read forwards and backwards. For example "racecar" is a palindrome, but "Racecar" is not. A [substring](https://en.wikipedia.org/wiki/Substring) is a contiguous set of characters in a larger string. Your task is to write a program or method which takes a string or character array as input and outputs the length of the longest substring of that string which is a palindrome. **Examples** Input ``` banana ``` Ouput ``` 5 ``` This is because "anana" is a 5 character substring of "banana" Input ``` abracadabra ``` Output ``` 3 ``` This is because both "aca" and "ada" are 3 characters. Input ``` True ``` Output ``` 1 ``` This string has no palindromes that are more than 1 character. If the input is the empty string the output must be 0. This is code-golf so the shortest submission in any language wins. Note: There have been slight variations of this question in the past, which have all had wording issues or been asking a variation of this question. You can see these: [Find the Longest Palindrome in a String by Removing Characters](https://codegolf.stackexchange.com/questions/19381/find-the-longest-palindrome-in-a-string-by-removing-characters) [Longest reverse palindromic DNA substring](https://codegolf.stackexchange.com/questions/42184/longest-reverse-palindromic-dna-substring) [How do I find the longest palindrome in a string?](https://codegolf.stackexchange.com/questions/16327/how-do-i-find-the-longest-palindrome-in-a-string) [Finding "sub-palindromes".](https://codegolf.stackexchange.com/questions/183/finding-sub-palindromes) - The purpose of this challenge is to print *all* palindromic substring, rather than the length of the longest. As such many of the answers to this question do not have close analogues. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes ``` {s.↔}ᶠlᵐ⌉ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v7pY71HblNqH2xbkPNw64VFP5///SkmJeUCo9D8KAA "Brachylog – Try It Online") ### Explanation ``` { }ᶠ Find all… s. …substrings of the input… .↔ …which are their own reverse lᵐ Map length ⌉ Max ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 8 bytes ``` ŒʒÂQ}€gM ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6KRTkw43BdY@alqT7vv/f1JiHhAWg0kA "05AB1E – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), 7 bytes ``` le_I#.: ``` [Try it online!](https://tio.run/##K6gsyfj/Pyc13lNZz@r/f6XEpKLE5MQUEKUEAA "Pyth – Try It Online") ### How? ``` le_I#.: – Full program. .: – All contiguous non-empty subsequences. # – Keep those... _I – That are invariant under reversal. e – Get the last element. l – And take its length. ``` Note that the substrings are ordered by length, in Pyth. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes Saved 1 byte thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) (pointing out that `Þ` is stable and thus works instead of `Ðf`). ``` ẆŒḂÞṪL ``` [Try it online!](https://tio.run/##y0rNyan8///hrrajkx7uaDo87@HOVT7///9PTCpKTE5MAVEA "Jelly – Try It Online") ### How? ``` ẆŒḂÞṪL – Full program. Ẇ – All contiguous non-empty subsequences. Þ – Stable sort by... ŒḂ – 1 if the element is palindrome, 0 otherwise. Ṫ – Get the last element. L – And take its length. ``` Note that the substrings are ordered by length, in Jelly. [Answer] # Java 8, 163 bytes ``` s->{int r=0,l=s.length(),i=0,j,T;for(String t;i<l;i++)for(j=i;++j<=l;r=t.contains(new StringBuffer(t).reverse())&(T=t.length())>r?T:r)t=s.substring(i,j);return r;} ``` **Explanation:** [Try it online.](https://tio.run/##hZG9bsMgFIX3PMVVhgpkx@pc4lTq3gyNt6oDxjiBEmxdrl1VkZ/dxT8ZqwgQ4vBdzgGs7OWuabW31feonAwB3qXxtw2A8aSxlkrDcVrOAih2IjT@DIGLKA5xxB5IklFwBA85jGF3uE0s5s@py0PmtD/ThfHURMGmhagbvB9DwuydMEnCJ9HmRiSJ3edOYE6ZajzFMIF5/QNLwVtX1xoZ8Qx1rzFoxvkTKyJ8d@EHfC1ekFN0Dl0Z5jJmUssFaurQA4phFEvwtitdDL7m7xtTwTU6ruk@vyRfrn76DaSvWdNR1sYdcp75TLFtKX1sWz4/xv@YLFEqWU3TQ7bATj@EPuK3KIkPuRUYNsP4Bw) ``` s->{ // Method with String parameter and integer return-type int r=0, // Result-String, starting empty l=s.length(), // The length of the input-String i=0,j, // Index-integers T; // Temp integer for(String t; // Temp String i<l;i++) // Loop `i` over the String for(j=i;++j<=l; // Inner loop `j` over the String r= // After every iteration, set the result to: t.contains(new StringBuffer(t).reverse()) // If the temp-String is a palindrome, &(T=t.length())>r? // and the length of the substring is larger than the result T // Set this length as the new result : // Else: r) // Keep the result the same t=s.substring(i,j); // Set the temp String to the substring from index `i` to `j` return r;} // Return the result ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` L►LfS=↔Q ``` [Try it online!](https://tio.run/##yygtzv7/3@fRtF0@acG2j9qmBP7//18pMakoMTkxBUQpAQA "Husk – Try It Online") ### How? ``` L►LfS=↔Q – Full program. Q – All contiguous non-empty subsequences. f – Keep those... S= – That are equal to themselves when... ↔ – Reversed. ►L – Get the maximum element, sorted by length. L – Take its length. ``` Alternative: `▲mLfS=↔Q`. Note that the substrings are **not** ordered by length, in Husk. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 42 bytes ``` Lv`(.)*.?(?<-1>\1)*(?(1)(?!)) N$^` $.& \G. ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8N@nLEFDT1NLz17D3kbX0C7GUFNLw17DUFPDXlFTk8tPJS6BS0VPjSvGXe///6TEPCDkSkwqSkxOTAFRXCVFpakA "Retina – Try It Online") Link includes test cases. Explanation: ``` Lv`(.)*.?(?<-1>\1)*(?(1)(?!)) ``` For each character in the string, find the longest palindrome that starts at that point. ``` N$^` $.& ``` Sort the found palindromes in reverse order of length. ``` \G. ``` Count the length of the first (i.e. longest) palindrome. [Answer] # [Python 3](https://docs.python.org/3/), 58 bytes ``` f=lambda s:len(s)if s==s[::-1]else max(f(s[1:]),f(s[:-1])) ``` [Try it online!](https://tio.run/##VYmxCoAgFEX3vkKcfFBDtAn@RVs0PEspMAufQX39y5Yg7nLuOcedlz12zN4E3OyMgnRwURGsXpAxNGjdtKML5MSGl/KKhlaPUL/wFgA@0hpzKdJiLJMA1afQ4oQz2vTXfTrdT5TDDw "Python 3 – Try It Online") [Answer] # [J](http://jsoftware.com/), 20 bytes ``` [:>./@,#\(#*]-:|.)\] ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o63s9PQddJRjNJS1YnWtavQ0Y2L/a3IpcKUmZ@QrpCmo5yWCoDqcn5hUlJicmAKiEIIhRaWp6v8B "J – Try It Online") ]
[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/17981/edit). Closed 8 years ago. [Improve this question](/posts/17981/edit) Given an array (`N`) of integers, check if it is possible to obtain a sum of `S`, by choosing some (or none) elements of the array and adding them. **Example #1** ``` {1,2,3} 4 ``` should output ``` 1 (or true) ``` because 1 and 3 can be added to produce 4. **Example #2** ``` {3,6,2} 0 ``` should output ``` 1 (or true) ``` because adding none of them together produces 0. **Example #3** ``` {0,4,3,8,1} 6 ``` should output ``` 0 (or false) ``` because no combination of the elements in the array can be added to produce 6. **Example #4** ``` {3, 2 ,0 ,7 ,-1} 8 ``` should output ``` 1 ``` because 2+7+(-1)=8 [Answer] ## Mathematica This is easy in Mathematica. (1) Generate the subsets of your input list, using the `Subsets[]` command (I had originally used `Permutations[]`, which works but produces redundant results), (2) sum the numbers in each subset by mapping the `Total[]` command across the list of subsets, then (3) check to see if the target sum S is represented among those sums with `MemberQ[]`. To be concise, I've shown this below implemented as a single nested command. Put your inputs in the first line and execute this: ``` list = {0, 4, 3, 8, 1}; target = 6; MemberQ[Total /@ Subsets[list], target] ``` Assuming one-character variable names, that's 28 bytes of code. [Answer] ## C#, complexity O(N\*R) I think this is the first not-exponential solution so far. Complexity - O(N \* R); Space - O(R) bytes; where N is length of input array, and R is the difference between sum of positive numbers and sum of negative numbers in array. On my machine it takes about 15 seconds calculating answer for input array with 1000 randomly generated integers in range [-10000..10000] ``` static bool HasSum(int[] a, int s) { int n = a.Length; int positiveSum = a.Where(i => i > 0).Sum(); int negativeSum = a.Where(i => i < 0).Sum(); if (s > positiveSum || s < negativeSum) return false; int offset = -negativeSum; s += offset; int r = positiveSum - negativeSum + 1; bool[] map = new bool[r]; map[offset] = true; for (int i = 0; i < n; i++) if (a[i] < 0) { for (int j = 0; j < r; j++) if (map[j]) map[j + a[i]] = true; } else { for (int j = r - 1; j >= 0; j--) if (map[j]) map[j + a[i]] = true; } return map[s]; } ``` [Answer] ## Python Much like the ruby solution. ``` def f(l, s): if s == 0: return True if l == []: return False return f(l[1:], s) or f(l[1:], s - l[0]) l = list(input()) s = int(input()) print f(l, s) ``` Input format: ``` [1,2,3] 4 ``` to stdin. [Answer] # Ruby - the recursive brute force is the best brute force ``` def subsetSum(n,s) n.sort! #ruby checks if the array is already sorted, which doesn't take long return true if (s==0) || n.include?(s) #pretty sure this gets cached if n[-1] > s #(optional, will fail in some scenarios with negatives) n.delete_at(-1) #remove last number if it's over S return subsetSum(n,s) end if n.length>0 t=n.delete_at(n.length - 1) #length for safety return true if subsetSum(n,s-t) return true if subsetSum(n,s) #check with and without the last number used end false end ``` example usage: `subsetSum([2,3,4],7) => true` Warning\* will fail when negative numbers are used, I need to go right now and will try to fix the issue later. # Alternative solution (unoptimized brute force) ``` def subsetSum(n,s) return true if s==0 (0..n.length).each{|x| n.combination(x).each{|y| return true if y.inject(:+) == s } } return false end ``` (this one fully works, but is less effective) [Answer] # Clojure Function to generate all sub-sets, then checks if any add up! ``` (fn [s n] (let [genfun (fn [s] (reduce (fn [init e] (set (concat init (map #(conj % e) init) [[e]]))) [[]] s))] (some #(= n %) (map #(reduce + %) (genfun s))))) ``` [Answer] ### R, create all possible combinations and their sum ``` l=lapply;!S|S%in%unlist(l(l(seq_along(N),combn,x=N),colSums)) ``` The command returns `TRUE` or `FALSE`. `N` and `S` are variables, e.g., `N <- c(1, 2, 3)` and `S <- 4`. [Answer] # Haskell Very simple, just take all the subsets of the input array and check if any of them sum to the given number. ``` subsets [] = [[]] subsets (x:xs) = [x] : subsets xs ++ (map (x:) (subsets xs)) f xs n = any ((==n).sum) (subsets xs) ``` [Answer] # C# LINQ f has to be initiated to null before assigning the lambda expression because it is recursive and the compiler will complain about f not being initialised if I try and declare f and assign to it on the same line. e.g ``` Func<int, int[], int> f = (s, a) => a.Where((n, i) => s == 0 | (s - n) == 0 | f(s - n, a.Where((_, j) => i != j).ToArray()) == 1).Any() ? 1 : 0; ``` Working program below. ``` class Program { public static void Main() { Func<int, int[], int> f = null; f = (s, a) => a.Where((n, i) => s == 0 | (s - n) == 0 | f(s - n, a.Where((_, j) => i != j).ToArray()) == 1).Any() ? 1 : 0; Console.WriteLine(f(5, new[] { 2, 2, 9, 1 })); } } ``` [Answer] # Haskell ``` import Control.Monad checkSum :: [Int] -> Int -> Bool checkSum xs x = elem x . map sum . filter (not . null) . filterM (const [True, False]) $ xs ``` A simpler Haskell formula that makes use of the list monad. The algorithm is broken down below: ``` -- Take the list xs -- Compute the power set of this list filterM (const [True, False]) -- Filter out the empty set from the result filter (not . null) -- Add up each subset of the power set map sum -- Check and see if any of the sums is equal to the value elem x ``` [Answer] **Rust** ``` fn check(array: &[int], s:int) -> bool{ if s ==0 { return true; } if array == [] { return false; } return (check(array.slice(1, array.len()), s) || check(array.slice(1,array.len()), s - array[0])); } fn main(){ let a = ~[1,2,3]; println!("{}",check(a,0)); } ``` I just copied **quasimodo's** solution in rust [Answer] # Haskell Unlike the most other solutions, by computing the set of all possible sums, we often get better complexity than by constructing the sums of all possible subsets. In particular, if the numbers are small, the size of the set is bounded by *t=Σ|nₖ|*, so the whole algorithm is *O(n t log t)*. ``` import qualified Data.IntSet as S extend :: S.IntSet -> Int -> S.IntSet extend set n = set `S.union` (S.map (+ n) set) sums :: [Int] -> S.IntSet sums = foldl extend (S.singleton 0) canSumTo :: Int -> [Int] -> Bool canSumTo s = S.member s . sums ``` Or as a one-liner (with swapped arguments): ``` canSumTo' :: [Int] -> Int -> Bool canSumTo' = flip S.member . foldl (\set n -> S.union set (S.map (+ n) set)) (S.singleton 0) ``` [Answer] ## APL Now that the character count doesn't matter, here's some ungolfed APL: ``` canSumTo ← { ⍝ get all subsets subsets ← { ⍝ the bits for [1..2^length] each form ⍝ a bitmask for a subset bitmasks ← ↓⍉((⍴⍵)/2)⊤⍳2*⍴⍵ ⍝ apply each bitmap to the input /∘⍵¨bitmasks }⍺ ⍝ does any of the subsets of ⍺ sum to ⍵? ⍵ ∊ +/¨subsets } ``` Then: ``` 1 2 3 canSumTo 4 1 3 6 2 canSumTo 0 1 0 4 3 8 1 canSumTo 6 0 3 2 0 7 ¯1 canSumTo 8 1 ``` [Answer] ## Fortran Algorithm is as follows: 1. Check if the sum of the array is less than `S` 2. Check if any of the elements of the array equals `S` 3. Sort array 4. Slice linear elements of array & check if sum of slice is `S` 5. Sum elements by jumping `i` spaces I have omitted the module `quicksort` but it does exactly what it sounds like it does. It passed all the test cases above, but it does fail on the array `0,-1,3,5,7` when asked for 11 (requires cells 1,4,5 (0,3,4 for those stuck on 0-indexes) which can't be done for slicing--I am working on fixing this) ``` program rand_array_sum use quicksort implicit none integer, dimension(:), allocatable :: array integer :: n, s print *,"Enter number of cells in array" read(*,*) n; allocate(array(n)) print *,"Enter comma-separated integers in array:" read(*,*) array print *,"What is the sum you want?" read(*,*) s if(s==0) then print *,1 stop endif if(sum(array)< s) then print *,0 stop endif if(any(array==s)) then print *,1 stop endif call sort(array) print *,"Sorted array:",array call sum_array(n,array,s) contains subroutine sum_array(n,a,s) integer, intent(in) :: n, a(n), s integer :: i, j, b ! linear slices do i=1,n do j=1,i !print '("i=",i0," j=",i0," b=",i0)',i,j,abs(i-j) b=abs(i-j) if(sum(array(j:n-b))==s) then print *,1 return endif enddo print *,"" enddo ! jumping slices do i=2,n do j=1,n-i+1 if(sum(array(j:n:i))==s) then print *,1 return endif enddo enddo ! if all as failed, then it cannot be done print *,0 end subroutine sum_array end program rand_array_sum ``` [Answer] # **Java** golfed (223 chars): ``` int r(int s,int[] a){for(int i=0;i<a.length;i++){if(s==0|(s-a[i])==0|r(s-a[i],s(a,i))==1)return 1;}return 0;} int[] s(int[] a,int k){int[] b=new int[a.length-1];for(int i=0;i<a.length-1;i++){b[i]=a[i+(k>i?0:1)];}return b;} ``` formatted: ``` class M { public static void main(String[] a) { System.out.println(r(6, new int[] { 0, 4, 2, 8, -1 })); } static int r(int s, int[] a) { for (int i = 0; i < a.length; i++) { if (s == 0 | (s - a[i]) == 0 | r(s - a[i], s(a, i)) == 1) { return 1; } } return 0; } static int[] s(int[] a, int k) { int[] b = new int[a.length - 1]; for (int i = 0; i < a.length - 1; i++) { b[i] = a[i + (k > i ? 0 : 1)]; } return b; } } ``` [Answer] # JavaScript An homage to / shameless ripoff of [quasimodo's solution](https://codegolf.stackexchange.com/a/17998/13957). ``` function f(l, s) { var n = l.slice(1) return !s || (!l.length ? false : f(n, s) || f(n, s - l[0])) } ``` [Answer] ### Ruby This is a succinct way to do it in Ruby using `Array#combination` but has the unfortunate consequence of performing the calculation of all possible combinations of sub-sums in `array` and then checking to see if the given `sum` is possible. With a large array, that is likely to be a lot of needless calculation. ``` def contains_sum?(array, sum) [*1..array.size].reduce([]) { |x, i| x + array.combination(i).to_a } .map { |c| c.reduce(:+) }.push(0).include?(sum) end ``` Here's a version that isn't a one-liner, but tries to avoid calculating more sums than it has to: ``` def contains_sum?(array, sum) return true if sum == 0 || array.include?(sum) [*2..array.size].each do |i| return true if array.combination(i).detect { |c| c.reduce(:+) } == sum end false end ``` [Answer] # k/q ``` k){|/y=+/'+x*(-#x)#+0b\:'!*/(#x)#2} ``` this is an adaptation of the `s` function from <http://kx.com/q/greplin.q> `s n` returns the bitmasks for the power set of a set of count n i then simply apply the mask matrix to the vector, sum them all up and look for the number in question ungolfed and converted back to q, and with the examples: ``` q)s:{neg[x]#flip 0b vs/:til prd x#2} q)f:{any y=sum each flip x*s count x} q)f[1 2 3;4] 1b q)f[3 6 2;0] 1b q)f[0 4 3 8 1;6] 0b q)f[3 2 0 7 -1;8] 1b q) ``` [Answer] # Haskell We don't care which sets sum to the value, only whether any exists, so we need not ever compute the power-set, only the sums of the elements of the power-set. In particular, **F**(*S*) := { **∑**L | L ∈ **Power**(*S*) } **F**(∅) = {0} **F**(*S*) = { **x** + *s* | *s* ∈ **F**(*S*∖ **x**) } ⋃ **F**(*S*∖ **x**)   ∀ **x** ∈ *S* The following recursive definition arises naturally. ``` sums [] = [0] sums (x:t) = sums t >>= \y -> [x+y,y] possible n xs = elem n xs || elem n $ sums xs ``` `possible` is a function whose first argument is a target number, and whose second argument is a list (array) to search for the target sum within. I added a test for inclusion before a test for summation, as that both makes the search faster and makes searching of infinite lists containing the target much faster. I might make this more ~~complicated~~ sophisticated later on. ## Edit 1 I found that my code didn't work well for infinite lists \*not\* containing the target, so I optimized my code to use a `scanl`, thereby performing a lazy search and increasing the speed of infinite lookups dramatically. ``` import Data.List sums :: Integral a => [a] -> [[a]] sums = scanl (\acc x -> [i + j|j<-[x,0],i<-acc]) [0] possible :: Integral a => a -> [a] -> Bool possible n xs = any (elem n) (sums xs) ``` The order of the binds in the generator matters; switching the order of `i` and `j` reduces the performance speed. Also, the order of `[x,0]` matters, as it ensures that each successive element of the scan will begin with the sums including the new element, instead of starting with the ones already seen. This does not change the speed of advancing in the scan, but it increases the speed of identifying a scan containing the target. ]
[Question] [ Given two rectangular arrays, A and B, let's say that A is *embedded* in B if A can be obtained from B by deleting some (or none) of the rows and columns of B. Write a program with the following I/O: **Input**: two arbitrary rectangular arrays of letters (a-z), as a string from stdin. **Output**: the number of embeddings of the first array in the second array, followed by a "text picture" of each embedding (showing deleted elements replaced by dots). (This is a two dimensional generalization of my old question [Is string X a subsequence of string Y?](https://codegolf.stackexchange.com/questions/5529/is-string-x-a-subsequence-of-string-y)) **Example:** input: ``` abb aba ababb aabba babab abbaa ``` output (if I haven't missed any): ``` 5 a..bb a..ba ..... ..... ab.b. ..... ..... ab.a. ab..b ..... ..... ab..a ..... a.bb. ..... a.ba. ..... .abb. .aba. ..... ``` The winner is the shortest such program (least number of characters). [Answer] ## APL (160) ``` {∆,⍨⍴∆←⍵∘{(⍴⍵)⍴(,⍵){⍺:⍵⋄'.'}¨,⍺}¨⊃¨∘.∧/¨∆/⍨⍺∘≡¨⍵∘{(⊃⍵)⌿⍺/⍨⊃⌽⍵}¨∆←,⊃∘.,/⊂¨¨K{⍵=0:⊂⍺/1⋄~(⍳⍺)∘∊¨⍵{⍺=1:(⍳⍵)⋄∆/⍨{∧/</¨2,/⍵}¨∆←,⍳⍺/⍵}⍺}¨(K←⍴⍵)-⍴⍺}/{×⍴K←⍞:∇⍵,⊂K⋄↑⍵}¨⍬⍬ ``` Output: ``` {∆,⍨⍴∆←⍵∘{(⍴⍵)⍴(,⍵){⍺:⍵⋄'.'}¨,⍺}¨⊃¨∘.∧/¨∆/⍨⍺∘≡¨⍵∘{(⊃⍵)⌿⍺/⍨⊃⌽⍵}¨∆←,⊃∘.,/⊂¨¨K{⍵=0:⊂⍺/1⋄~(⍳⍺)∘∊¨⍵{⍺=1:(⍳⍵)⋄∆/⍨{∧/</¨2,/⍵}¨∆←,⍳⍺/⍵}⍺}¨(K←⍴⍵)-⍴⍺}/{×⍴K←⍞:∇⍵,⊂K⋄↑⍵}¨⍬⍬ abb aba ababb aabba babab abbaa 5 ..... ..... ab..b ab.b. a..bb a.bb. .abb. ..... ..... a..ba ..... .aba. ..... ..... ..... a.ba. ..... ab..a ab.a. ..... ``` Explanation: * `{`...`}/{×⍴K←⍞:∇⍵,⊂K⋄↑⍵}¨⍬⍬`: read the two arrays from the keyboard, and return them as two matrices. Reduce the following function over the list of the two matrices. * `∆{`...`}¨(∆←⍴⍵)-⍴⍺`: get the height and width of each of the matrices. In both the width and the height, get a list of possible lines to drop. + `⍵=0:⊂⍺/1`: if the matrices are the same length in a dimension, never drop any lines from that dimension. Otherwise: + `⍺=1:(⍳⍵)⋄`: If the difference is one, try to drop each line + `∆/⍨{∧/</¨2,/⍵}¨∆←,⍳⍺/⍵`: otherwise, drop each possible combination of `⍺` lines. * `∆←,⊃∘.,/⊂¨¨`: combine each height mask with each width mask, giving all possible combinations to make the second list the size of the first. * `⍵∘{(⊃⍵)⌿⍺/⍨⊃⌽⍵}¨∆`: for each possible combination, remove those lines from the second matrix. * `∆/⍨⍺∘≡¨`: drop all the ones that are not equal to the first matrix, giving the solutions. * `⊃¨∘.∧/¨`: for each of the possible solutions, make a matrix with `0` where a dot should go and `1` where the corresponding character from the first matrix should go. * `⍵∘{(⍴⍵)⍴(,⍵){⍺:⍵⋄'.'}¨,⍺}¨`: for each of these, flatten both the second matrix (`,⍵`) and the matrix of dots (`,⍺), and take either the character or a dot for each position (`{⍺:⍵⋄'.'}¨). Then reshape it to the shape it had before (`(⍴⍵)⍴`). * `∆,⍨⍴∆`: give the amount of solution, and each solution. [Answer] # Mathematica, 186 chars ``` {a,b}=Characters/@StringSplit@InputString[]&~Array~2;{Length@#,Grid/@#}&[ReplacePart[b,Except[$|##&@@Tuples@#,{_,_}]->"."]&/@Select[Tuples[Subsets/@Range/@Dimensions@b],b[[##]]&@@#==a&]] ``` ### Example: ``` In[1]:= {a,b}=Characters/@StringSplit@InputString[]&~Array~2;{Length@#,Grid/@#}&[ReplacePart[b,Except[$|##&@@Tuples@#,{_,_}]->"."]&/@Select[Tuples[Subsets/@Range/@Dimensions@b],b[[##]]&@@#==a&]] ? abb aba ? ababb aabba babab abbaa Out[1]= {5, {a . . b b, a b . b ., a b . . b, . . . . ., . . . . .}} a . . b a . . . . . . . . . . . a b b . a . b b . . . . . . . . . . . . . . . . . a b a . . . . . . . . . . . a b . a . a b . . a . . . . . a . b a . ``` [Answer] # Python 2 with Numpy, 342 chars ``` from numpy import* from itertools import* import sys S=str.split C=combinations R=range a,b=[mat(map(list,S(x)))for x in S(sys.stdin.read(),'\n\n')] n,m=b.shape o,p=a.shape z=[] for i in product(C(R(n),o),C(R(m),p)): i=ix_(*i);e=b[i] if all(a==e):f=copy(b);f[:]='.';f[i]=e;z+=[f] print len(z) for x in z:print'\n'.join(map(''.join,x))+'\n' ``` ## Output Example ``` 5 a..bb a..ba ..... ..... ab.b. ..... ..... ab.a. ab..b ..... ..... ab..a ..... .abb. .aba. ..... ..... a.bb. ..... a.ba. ``` [Answer] # Haskell, 364 chars ``` m=map l=length u=unlines v=reverse z=zip[0..] q s=p(lines s)[] e i a=[a!!j|j<-i] main=g.w.q=<<getContents g x=(print.l)x>>(putStr.u.m u)x c 0=[[]];c n=let x=m(m(1+))$c(n-1)in x++m(0:)x p(c:x) a|c==""=(v a,fst$p x[])|1<2=p x(c:a);p[]a=(v a,[]) w(a,b)=[m(\(p,r)->m(\(q,x)->if(elem p i&&elem q j)then(b!!p!!q)else '.')$z r)$z b|i<-c.l$b,j<-c.l$b!!0,a==(m(e j).e i)b] ``` ## Ungolfed Version, 716 chars ``` parse (c:x) a | c == "" = (reverse a, fst$parse x []) | otherwise = parse x (c:a) parse [] a = (reverse a, []) readMat s = parse (lines s) [] choose 0 = [[]] choose n = let x = map (map (1+))$choose (n-1) in x ++ map (0:) x select ix a = [a!!i | i<-ix] for = flip map make b (ix, jx) = for (zip [0..] b) (\(i,r) -> for (zip [0..] r) (\(j,x) -> if elem i ix && elem j jx then b!!i!!j else '.' ) ) main = do s <- getContents let (a, b) = readMat s (n, m) = (length b, length.head$ b) let ans = [make b (ix, jx) | ix <- choose n, jx <- choose n, a == (map (select jx).select ix$ b)] print$ length ans putStrLn$unlines.map unlines$ ans ``` [Answer] Ruby 448 ``` class Array alias t transpose alias z size alias e each alias s select end def x v=[] while(w=gets.chop).size>0 do v<<w.split('') end v end def w(i,j)(0...i).to_a.combination(i-j).to_a end a=x n=a.z a=a.t o=a.z b=x q=b.z r=b[0].z w=['.'] y=w*r z=w*q f=[] w(q,n).e{|u|w(r,o).e{|v| h=b.dup u.e{|i|h[i]=y} h=h.t v.e{|j|h[j]=z} h=h.t f<<h if(h.s{|i|i!=y}.t.s{|i|i!=w*n})==a}} p f.z puts f.e{|b|b.e{|i|k='';i.e{|j|(k<<' ')if k.size>0;k<<j} puts k} puts} ``` ]
[Question] [ Write a function `f(a,b)` that returns `a mod b` given the constraints: * you can't use division in any way * `f(a,b)` is always positive, eg: `f(-1,5) = 4` * it performs reasonably well for values of ~`10e50` for `a` and `b` [Answer] ## Haskell ~~36~~ 35 (~~34?~~ 33) If I may call the function `?` instead: ``` 1234567890123456789012345678901234 a?b|a<0=(a+b)?b|a>b=(a-b)?b|0<1=a ``` Elseway: ``` f a b|a<0=f(a+b)b|a>b=f(a-b)b|0<1=a ``` [Answer] ## Perl, 62 bytes Regex modulo ``` sub f{($a,$b)=@_;$_=1x$a;s/^(1{$b})+(1+)$/return length $2/e;} ``` [Answer] ## Java Solution, 114 66 chars Its now 66, thanks sepp2k!~ ``` int m(int x,int y){x=(x<0)?-(x*y-x):x;while(x>=y) x-=y;return x;} ``` [Answer] ## Haskell (22) Abuse of the rules, please don't downvote: Mathematically, the modulus may be arbitrary large, because all moduli are equivalent. Thus, you may also use this, it WILL always return a positive result: ``` 1234567890123456789012 a?b|a<0=(a+b)?b|True=a ``` And it will also always satisfy the equation ``` a?b = c <-> n*b + c = a ``` For some integer n. [Answer] # Ruby - 72 chars ``` f=->a,b{a==b&&0||a<b&&a+(a<0&&b||0)||(t=b;t<<=1until t>a;f[a-(t>>1),b])} ``` Uses recursion like a Binary Search to find the remainder. Test ``` p f[106, 95] p f[23, 2] p f[-1, 5] p f[20, 7] p f[10**100, 3] p f[4*10**200, 3123123] 11 1 4 6 1 823660 ``` [Answer] ## Brainfuck - 37 characters ``` ,>,<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>>. ``` Takes a and b as bytes from standard input. Outputs one byte. Does not meet criteria to work with arbitrary size numbers, but to do so in brainfuck would not be simple. [Answer] # Python 2, 35 bytes ``` f=lambda a,b:a if a<b else f(a-b,b) ``` Sadly, I can't use `and`/`or` short-circuiting here, so I have to do with one more byte. ]
[Question] [ Write the shortest code that traverses a tree, depth-first. **Input** Any programmatical structure found in your language of choice: lists, tuples, queues etc. **Output** A list of "names" of the nodes in correct order as shown in [Depth-first search](http://en.wikipedia.org/wiki/Depth-first_search) article at Wikipedia. **Requirement:** A node should be able to contain an **infinite** number of child nodes. Also, you're not required to actually print the result, just returning the correct result with the ability to use it in your program will do; I didn't really print mine [below in my answer](https://codegolf.stackexchange.com/a/598/52210), the function simply returned a list. [Answer] ## Haskell — 70 characters ``` data N a=N{v::a,c::[N a]} d n=f[n][] f(x:y)=f(c x++y).(++[v x]) f _=id ``` In a more readable format: ``` data Node a = Node {value::a, children::[Node a]} dfs :: Node a -> [a] dfs node = dfs' [node] [] where dfs' [] result = result dfs' (x:xs) result = dfs' (children x ++ xs) (result ++ [value x]) ``` Sample tree: ``` sampleTree = Node 1 [Node 2 [Node 3 [Node 4 [], Node 5 []], Node 6 []], Node 7 [], Node 8 [Node 9 [Node 10 [], Node 11 []], Node 12 []]] ``` Sample run: ``` *Main> dfs sampleTree [1,2,3,4,5,6,7,8,9,10,11,12] ``` [Answer] # [Haskell](https://www.haskell.org/), 35 bytes ``` data D a=T[D a]a d(T l n)=n:(d=<<l) ``` [Try it online!](https://tio.run/##LYs7CoAwEET7nGIKCwMWxk8jpvMI6cIWCxEUYxDN/WP8NDPvMczC1zZ7n5LjyJjA2ticxMKVBh5B6jCUTo@jlykqaAgYayypSgAfti8@QvVL1P8jNbmpEzuvIV@Pcw0RBRyiSjc "Haskell – Try It Online") `data D a=T[D a]a` defines a labelled tree data structure. Constructor `T` takes a list of sub-trees and same value of an arbitrary type `a` (which however must be consistent throughout each tree). Here is an example of a tree labelled with integers and the way this tree can be defined using the data structure: ``` 4 / | \ 1 5 2 / \ 3 0 tree = T[T[]1, T[T[]3, T[]0]5, T[]2]4 ``` The function `d` takes such a tree and returns a list of the tree's labels in depth-first order: Calling `d tree` yields `[4,1,5,3,0,2]`. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~10~~ 1, >2 or 8 bytes Thanks to [@Shaggy](https://codegolf.stackexchange.com/a/260462/114511) and [@Kevin Cruijssen](https://codegolf.stackexchange.com/a/260466/114511)!! If name of nodes are just a primitives (numbers, string) and 1D array is accepted output, than just: ``` f ``` If we need to do something with nodes, than: ``` fƛ<todo> ``` And if *"A node should be able to contain an infinite number of child nodes"*: ``` ƛ:@[vx;f ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwixps6QFt2eDtmIiwiIiwiWzQsWzEsWzUsWzMsMF1dLDJdXVxuWzEsWzIsWzMsWzRdXV0sWzUsWzYsWzddLDhdXSxbOSxbMTBdXV1cblsxLFsyLFszLFs0XSxbNV1dLFs2XV0sWzddLFs4LFs5LFsxMF0sWzExXV0sWzEyXV1dIl0=) ``` ƛ # Start lambda map : # Duplicate @ # Check is array or number (vectorized length==[] if a number) [ # Start If vx # If array - vectorized recursive call of lambda # Else - do nothing (virtual "|" ) # Close If (virtual "]" ) ; # Close lambda f # Flatten ``` [Answer] ## Perl, 34 Perl 5.10 or later, run with `perl -E'code here'`: ``` sub f{ref()?f($_):say for@{$_[0]}} ``` For example, running `f [1,[2,[3,[4],[5]],[6]],[7],[8,[9,[10],[11]],[12]]]` produces: ``` 1 2 3 4 5 6 7 8 9 10 11 12 ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 1 [byte](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ... It *seems* like simply flattening the array will to the job. ``` c ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Yw&input=WzQsWzEsWzUsWzMsMF1dLDJdXQotUQ) # [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` cȶÔ?ßXÔ:X ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Y8i21D/fWNQ6WA&input=WzQsWzEsWzUsWzMsMF1dLDJdXQotUQ) ``` cȶÔ?ßXÔ:X :Implicit input of multi-dimensional array c :Flat map by È :Passing each X through the following function ¶ : Is strictly equal to Ô : Its reverse, if it's an array, or maximum, if it's an integer (see more detailed explanation below) ? : If true ß : Recursive call with argument XÔ : X reversed (because reversing an array in JS mutates the original) :X : Else return X ``` --- To (try to) explain how the `Ô` (which is a shortcut for the `w` method, without any arguments) allows us to differentiate between arrays & numbers by testing for strict equality: While it's true that in JavaScript 2 arrays containing the exact same elements are [not strictly equal](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubyg&code=WzEsIDIsIDNdID09PSBbMSwgMiwgM10&footer=KSQ) as they are 2 distinct objects, an array assigned to a variable is, of course, [equal to itself](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubygo&code=VSA9IFsxLCAyLCAzXSwKVSA9PT0gVQ&footer=KSQ). Add to that that the `reverse` method for arrays (`w` in Japt) [mutates the original array](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubyhb&code=VSA9IFsxLCAyLCAzXSwKVS53KCk&footer=XS5xKFIpKSQ) and that explains how an array assigned to a variable (`X` in this case) can be [strictly equal to its reverse](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubygo&code=VSA9IFsxLCAyLCAzXSwKVSA9PT0gVS53KCk&footer=KSkk). As to why a number does not equal its maximum, that's down to a peculiarity of Japt. Firstly, when applied to a number, Japt's `w` method [returns the maximum](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubygo&code=VSA9IDgsClUudyg0LCAxMik&footer=KSkk) of that number and the arguments passed to the method, [as a `Number`](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubygo&code=VSA9IDgsCnR5cGVvZiBVLncoNCwgMTIp&footer=KSkk). However, if *no* arguments are passed to the `w` method then the number it's applied to is [returned as excpected](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubygo&code=VSA9IDgsClUudygp&footer=KSkk) but, [for some reason](https://github.com/ETHproductions/japt/blob/master/src/japt-interpreter.js#L220), Japt [converts the returned value to an `Object`](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubygo&code=VSA9IDgsCnR5cGVvZiBVLncoKQ&footer=KSkk) and a `Number` cannot be [strictly equal to](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&header=JE8ubygo&code=VSA9IDgsClUgPT09IFUudygp&footer=KSkk) an `Object` [Answer] # PHP - 57 characters ``` <?function s($t){echo$t[0].' ';for(;$T=next($t);s($T));} ``` Test: ``` s(json_decode('[1,[2,[3,[4],[5]],[6]],[7],[8,[9,[10],[11]],[12]]]')); ``` Output: ``` 1 2 3 4 5 6 7 8 9 10 11 12 ``` [Answer] # Ruby - ~~37~~ ~~35~~ ~~31~~ 25 characters ``` s=->t{p t.shift;t.map &s} ``` Test: ``` s[[1,[2,[3,[4],[5]],[6]],[7],[8,[9,[10],[11]],[12]]]] ``` [Answer] # [Scala](http://www.scala-lang.org/), 125 bytes Modified from [@Laikoni's Haskell solution](https://codegolf.stackexchange.com/a/122784/110802). --- Golfed version. [Try it online!](https://tio.run/##bVA9T8MwEN39K2601QgRCoulIEVipFPbKcpw2G4b5JpinyJQld@e2kYtCWJ6797HDS8otDh@vL0bRbDCzsGZjcGgNRrIY0fw0tQtUxgMKIshwCbe3Mq1@WyS1Ra9rAWYLzJOh5@0NjvQKUYy3SKH67YiOCKpwzl/23Bb9KJ67hfS3u0s0gpPXIthZAA9WqASqkghBjMAvHaBrjzJ@RYFlKKYqDf6tzAvLSeluXMvJsYs9cT@kX@LD9fizX3MKFiEtMkx7svR74OE2nv8btbkO7ePA8HWxamrOH4qnKJK1nHNqRTp6cCG8QI) ``` sealed trait D[A] case class T[A](l:Seq[D[A]],v:A) extends D[A] def d[A](t:D[A]):Seq[A]=t match{case T(l,v)=>v+:l.flatMap(d)} ``` Ungolfed version. [Try it online!](https://tio.run/##bZFBT4QwFITv/Io5tgkxsuqFBBMSj@5JPBEOT9pdMV120z6Nxuxvx7bACsYLfcy8r5NMXUuGhuH48qZbxpa6Ht8J4DQZrcCWOsZDXTZea8lptIacQ@UVYTrHOR79tw4bTYoPMu86RymhP1n3yo2oZ5XeQQWIrfYbQZYTWzYoEGQciNvXGD@FVTFjuleiuB8n5DmCcbUzxFs6CSU9cw453gdnKOIdlYgHYs48Bzn@yxSZTBfqZfwLrKGbBbR2ruXCWG3dJf/Iv@BmBi/ubTzlXN3Bv4sgu3e@XGvpq35i2/X70OFz71@omFo7eZVNL5TgTI6lnJNh@AE) ``` object Main { sealed trait D[A] case class T[A](list: List[D[A]], value: A) extends D[A] def d[A](tree: D[A]): List[A] = tree match { case T(list, value) => value :: list.flatMap(d) } val t1 = T( List( T(List(), 1), T( List( T(List(), 3), T(List(), 0) ), 5 ), T(List(), 2) ), 4 ) def main(args: Array[String]): Unit = { println(d(t1)) } } ``` [Answer] # JavaScript, 29 bytes ``` f=a=>a.flatMap(x=>1/x?x:f(x)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGCpaUlaboWe9NsE23tEvXSchJLfBMLNCps7Qz1K-wrrNI0KjQ1IWpuKifn5xXn56Tq5eSna6RpRJvoRBvqRJvqRBvrGMTG6hjFxsKUwowFAA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 2 (or 13) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ˜ε... ``` The `...` indicates something you'd want to do with the item 'name' we're traversing depth-first over. [Try it online with a print statement](https://tio.run/##yy9OTMpM/f//9JxzW3X@/4821Ik20ok21ok20TGNjdUxi9Ux14m20Im21Ik2NNAxNASKGRrFxv7X1c3L181JrKoEAA) to verify it's in the correct order, or [verify some more test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX2nLpeRflJJapJCfppCSWlCSoZuWWVRcolBSlFiWWlScmANUpfP/9JxzW3X@1x7aZv8/OtpEJ9pQJ9pUJ9pYxyA2VscIiBVAIkYgkWiTWCAfJGumE20eq2MB4lkCdRjEoqnTMQUKmMXqmOtEW0CV6BgaAsUMgSbG/tfVzcvXzUmsqgQA). [Try it online with a ragged list containing infinite sub-items](https://tio.run/##yy9OTMpM/f@oY56R26Edxhd21CooKIUWpxYrZOalZeZllqQq5KUWl6SmKORkFpcUK0RHRxvqGOkY6@jp6cXqYLJBTCCbWopiFRKLFVIrEnMLclKVYv6fnnNuq87///91dfPydXMSqyoB). **Explanation:** ``` ˜ # Flatten the (implicit) ragged input-list ε # Map over each item: # (do something) ``` The main rule that stops most other programming languages from using a similar approach is "*A node should be able to contain an **infinite** number of child nodes.*". Fortunately, 05AB1E (build in Elixir) supports infinite lists and can flatten them without too much trouble, allowing this approach. But for completeness sake, here is also a (**13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)**) program if this wouldn't have been possible: ``` "Ddi...ë®δ.V"©.V ``` The `...` again indicates something you'd want to do with the item 'name' we're traversing depth-first over. Assumes the 'names' of items used are positive integer ids. [Try it online with a print statement](https://tio.run/##yy9OTMpM/f9fySUlU@fw6kPrzm3RC1M6tFIv7P//aEOdaCOdaGOdaBMd09hYHbNYHXOdaAudaEudaEMDHUNDoJihUWzsf13dvHzdnMSqSgA) to verify it's in the correct order, or [verify some more test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX2nLpeRflJJapJCfppCSWlCSoZuWWVRcolBSlFiWWlScmANUpfNfySUlU@fw6kPrzm3RC1M6tFIv7P@hbfb/o6NNdKINdaJNdaKNdQxiY3WMgFgBJGIEEok2iQXyQbJmOtHmsToWIJ4lUIdBLJo6HVOggFmsjrlOtAVUiY6hIVDMEGhi7H9d3bx83ZzEqkoA). [Try it online with a ragged list containing infinite sub-items](https://tio.run/##yy9OTMpM/W9s8Khj3qOGWSYGQMLI4OhCCNcQyFJQUFAKLU4tVsjMS8vMyyxJVchLLS5JTVHIySwuKVaINjTQiTYCYmMgNtQx0jHW0dPTi43VMTGIRRFQSCxWSK1IzC3ISVWK@a/kkpKpc3j1oXXntuiFKR1aqRf2//9/Xd28fN2cxKpKAA). **Explanation:** As always, 05AB1E is pretty bad at recursive functions over [ragged-list](/questions/tagged/ragged-list "show questions tagged 'ragged-list'")s, and will have to a use a string and evaluate to accomplish this.. ``` "..." # Push the recursive string explained below © # Store it in variable `®` (without popping) .V # Evaluate and execute it as 05AB1E code, # using the (implicit) input as initial argument D # Duplicate the current value di # Pop the copy, and if it's a (non-negative) integer: ... # (do something) ë # Else (it's a list instead): δ # Map over the list: ® .V # Do a recursive call ``` [Answer] # [Go](https://go.dev), 89 bytes ``` import."fmt" type N struct{v int;c[]N} func f(n N){Println(n.v) for _,c:=range n.c{f(c)}} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RU5LCsIwFFybUzy6SqAWvyCVXiG4FREJISlFm5aYFiTEi7gpgjsv5G1Ma9TVfHhvZm73vOqeNeNHlgsoWaEejZHj1WtblHWlTRLJ0kTIXGoBFM5GN9zYFgpl1ny3pw7JRnGQWAEldqO9f1JYJS1BstJwiHmaaaZ8tEq4lZgT50LBdfjsGzEBi4wWAtIMqF3EPtiiEbXTgTkX92IZbE_nf9-ryV-F09nPcQ59R_UFflXAsKLrPvgG) This code also includes the type definition of a node `N`. Without it, the code is **63 bytes**. Prints node values to STDOUT, separated by newlines. [Answer] # [Python 3](https://www.python.org), 52 bytes ``` def f(t): yield t[0] for s in t[1]:yield from f(s) ``` Each node in the tree structure is encoded as a 2-tuple containing a value and an iterable of child nodes. The child nodes iterable may be infinite. Returns a generator containing values. [Attempt This Online!](https://ato.pxeger.com/run?1=bZGxTsMwEIbF6qc4tYsNIUpCkFClMiIxM1YZkvQsrCZ2ZF-Q8iwsXeCd4GmwnZSC1MX6T__d_9nn989holejj8ePkeTtw1e5RwmSk9gwmBR2e6BdVjGQxoIDpX2ZV5vZkdb0vteJefb7yq3hxfQIctQtKaNdHCN0BG3t0DHVD8YSKEJLxnSOBRrVB-R67Bu0SbTqpsPAV7CFbEa_1d2IAX_yve39my3kQUivH2HOCA40FuuDF_NF4zRja3hS2gecb8TIIuYew8sEdjz3RyUS4PehujtVWRRRFotkg1Wa-LXfVEgQIqQ_a3kpvwj5WXJ-ddpObYf8D6_4xysXSCV-OXFHue-YgYXwfas0TVfL7k__9wM) ### Explanation ``` def f(t): # Define generator function f that takes tree t yield t[0] # Yield the value of the root node for s in t[1]: # For each subtree s: yield from f(s) # Apply f to the subtree and yield each value in turn ``` --- Using itertools is never the answer.[[citation needed]](https://codegolf.meta.stackexchange.com/a/5603/16766) But in this case, it comes pretty close (**57 bytes**): ``` lambda t:chain(t[:1],*map(f,t[1])) from itertools import* ``` ]
[Question] [ Your task is to automatically complete URLs like the address bar in most browsers is doing. We will use the following (simplified) rules: * If the input string starts with `http://`, `ftp://` or `https://`, return the string unchanged. * Otherwise, if the input string contains a dot `.`, e.g. `in.put` then the HTTP is assumed and `http://` is prepended: `http://in.put`. * Otherwise `ftp://` is prepended, e.g. `ftp://input` when the input string was `input`. ## Input Any string which must not necessarily be a valid URL. ## Output The string modified according to the above rules. ## Test Cases ``` dan-pc -> ftp://dan-pc https://localhost/ -> https://localhost/ ftp://foo -> ftp://foo http://foo -> http://foo f.oo -> http://f.oo derp.me -> http://derp.me another.one/ ->http://another.one/ // -> ftp://// a://b -> ftp://a://b ``` *This is code golf, shortest code wins. Good Luck!* [Answer] # R, 98 bytes ``` x=scan() cat(`if`(grepl("^(https?|ftp)://",x),"",`if`(grepl("\\.",x),"http://","ftp://")),x,sep="") ``` [Try it online!](https://tio.run/##K/r/v8K2ODkxT0OTKzmxRCMhMy1BI70otSBHQym6oKY41kpfX0mnQlNHSUkHWU4PIphRUlIAVqGUBmFoaupU6BSnFtgqKWn@/6@UkpinW5CsBAA "R – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-p`, 38 bytes ``` m%://%||s%.*\.%http://$&%||s%^%ftp://% ``` [Try it online!](https://tio.run/##K0gtyjH9/z9X1UpfX7WmplhVTytGTzWjpKQAKKCiBhaKU00Dc1X//0/Lz/@XX1CSmZ9X/F/X11TPwNDgv24BAA "Perl 5 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~63~~ ~~56~~ 55 bytes ``` ->a{a[%r*(https?|ftp)://*]?a:"#{a[?.]?'ht':?f}tp://"+a} ``` [Try it online!](https://tio.run/##HcyxDsIgEIDhV2lqTLWmsJMocXJ3cGkYTgphqO0FroMpPPtJnL8/f9zeX/ZXHm6ww3iM/SkQYdLZE56VlL3RoNpDNS2M7gJ1SvtCWKm9QOH78/ESDmzYc8oNbpQaPyZTmCdYBrT839V6Xi3MYU0keXIRxcf9AA "Ruby – Try It Online") [Answer] # [Swift](http://rextester.com/l/swift_online_compiler), ~~147~~ 133 bytes Thanks to [Herman L](https://codegolf.stackexchange.com/users/70894/herman-l) for saving 14 bytes. Sadly, `NSRegularExpression` would've taken away lots of precious bytes. ``` import Foundation;let s=readLine()!,h=["http://","https://","ftp://"];print(h.contains{s.hasPrefix($0)} ?s:h[s.contains(".") ?0:2]+s) ``` **Prettyfied:** ``` import Foundation let s = readLine()!, h = ["http://","https://","ftp://"] print(h.contains{ s.hasPrefix($0) } ? s :h[s.contains(".") ? 0 : 2] + s) ``` [Try it online!](https://tio.run/##PcqxCsIwEIDhV4nBIcGSFnFKKd06ObiXDsEm5EAvIXeiID57BAtuHz8/PSHwqVa451RYTOmBq2NI2N88CxqKd@sZ0Cu9a@Iwy8icbdvK5ifaGLa29LkAsormmpAdIL3JREeX4gO81L7THzGSjTP9ByWN1GLs7HE5kK7VYeLoi0novw) [Answer] # JavaScript (Firefox 52), 41 bytes ``` s=>new URL(s,/\./.test(s)?'http:':'ftp:') ``` If a string is required for output, add 3 bytes `+''` at the end. (Notice this solution may add a trailing `/` at the end of domain name since they are the same URL) ``` f= s=>new URL(s,/\./.test(s)?'http:':'ftp:') t=s=>console.log(`${s} -> ${f(s)}`) t('example.com') t('example') t('http://example') t('https://example') t('ftp://example') t('http://example.com') t('https://example.com') t('ftp://example.com') ``` It seems this only works on Firefox 52 ESR but not Firefox 60 or Chrome 65. So sad. [Answer] # PHP, 59 bytes ``` <?=strpos($s=$argn,':')?$s:(strpos($s,'.')?ht:f)."tp://$s"; ``` To run all the tests: ``` cat <<EOF | php -nF <filename> dan-pc https://localhost/ ftp://foo http://foo f.oo derp.me another.one/ EOF ``` (Put a newline before the `<?=` for formatting, not required for one line of input) Or just one at a time: ``` echo '<input>' | php -nF <filename> ``` Or [Try it online!](https://tio.run/##PYpBCsMgEEX3HiMIJpCMe9uQXe8hidZCOjM4c/5aCaWbz@O9z4VbM/dtFa1MMlpZbaxPnF1w02YljP8wO@iqaMgTDMrBeyvDrbUj4sK7KaosXZ60x7OQqDf5emWiK/4wQ58jVYZ3MhFJS6pAmPyHWF@E0hZ8fAE) [Answer] # Java 8, ~~74~~ 72 bytes ``` s->s.matches("(https?|ftp)://.*")?s:(s.contains(".")?"ht":"f")+"tp://"+s ``` -2 bytes thanks to *@HermanLauenstein*. [Try it online.](https://tio.run/##jY/BbsMgDIbvfQqLE6wKuafa@gTtZcepB5eQJR0BFLuVqi3PnnlZLjtMqQQSmM/@Py54w@JSf0wuIBEcsIufG4Aush8adB6OP1eAVx66@A5OLwcyO6mPsmURI3cOjhDhGSYqXsj2yK71pJVumTPtvxrOpipL@6TMnipN1qXIkiaIlZJqWVWqUWarOAuntjTtfqfn6znI9CXklroaemlcTN5OaBbFO7HvbbqyzfLCIeponVY1xiI7ZWbj/7HZU5JDchjaRFyutjSzapPSKln7Idver3IYE7d@sCk@wNbuPPuGh/72x3TcjNM3) **Explanation:** ``` s-> // Method with String as both parameter and return-type s.matches("(https?|ftp)://.*")? // If the input starts with one of // "http://", "https://", or "ftp://" s // Return it as is : // Else: (s.contains(".")? // If it contains a dot "ht" // Start with "ht" : // Else: "f") // Start with "f" +"tp://"+s // And append "tp://" and the input-String ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 64 bytes ``` ^(?!(https?|ftp)://)(?=.*\.) http:// ^(?!(https?|ftp)://) ftp:// ``` [Try it online!](https://tio.run/##K0otycxLNPz/P07DXlEjo6SkoNi@Jq2kQNNKX19Tw95WTytGT5MLJA4U4MKmiCsNLPf/f5pefj4A "Retina – Try It Online") [Answer] # JavaScript, 64 bytes ``` x=>x.match`^(https?|ftp)://`?x:`${/\./.test(x)?'ht':'f'}tp://`+x ``` # JavaScript, ~~51~~ 50 bytes, Real life assumption ``` x=>x.match`//`?x:`${/\./.test(x)?'ht':'f'}tp://`+x ``` Thank tsh for 1 byte [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), ~~58~~ 55 bytes ``` .'://':a/.,(\0=['https'.4<'ftp']:l?)*{}{.'.'?)!)l=a@}if ``` [Try it online!](https://tio.run/##LYzBCoMwEETv@YsKslXa3R56kor9D/WQalKFmA1JbuK3p0F6GYaZefNlo8PkVxdTMdii3PuE0BBBIwlv1@HR9rDE6ALg8wU6Ohgb01X1fuwICF11qUwr38eq0whQH6Wt0yzt3U3ixPKV4UmahUMkkfkcaOaz/FuNWWblHW5KSMtxUR7ZKhJEQubR5wc "GolfScript – Try It Online") This is my first GolfScript program, so I expect there is a lot room for golfing. Explanation: ``` .'://':a/.,(\0=['https'.4<'ftp']:l?)*{}{.'.'?)!)l=a@}if Full program, implicit input . Copy input '://':a Push '://', and assign it to a /. Split input at '://' and copy ,( Push length of the result - 1 (<==> '://' in input) \0= Pull up the array and get the first element ['https'.4<'ftp']:l Push [ 'https', 'http', 'ftp' ] and assign it to l ?) Test if first element is in that array *{}{ }if If at least one of those values is false .'.'?) Push whether the input contains a dot !) Logical not and increment: '.' in input -> 1 no '.' in input -> 2 l= Get that element of l ([ 'https', 'http', 'ftp' ]) a@ Append a ('://') and input Implicit output ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~87~~ 85 bytes ``` lambda s:re.match('(https?|ftp)://',s)and s or['f','ht']['.'in s]+'tp://'+s import re ``` [Try it online!](https://tio.run/##RYxNCoMwEIXX9RTZjWKq0KVgexDrIpqkETQTMrMp9O5pIpTu3s/3XnizQ39LdnymXR2LVoKGaLpD8epqqB1zoMfHcmiGvgdJjfJakMA4gQUJjmGeoIPNC5pb4FColqrtCBhZRJMsxsznfgKt/DWsIAWctxndcVW7Q@K@pPacW8RitImhO0yRyiM7Ezv0pv@t/6BaVp2dsS@Yh@oS4uZZkITxDtLW1KQv "Python 2 – Try It Online") -2 bytes thx to [Titus](https://codegolf.stackexchange.com/users/55735/titus) and [wastl](https://codegolf.stackexchange.com/users/78123/wastl) [Answer] # [Pyth](https://github.com/isaacg1/pyth), 58 bytesSBCS ``` J"://"I:Q."(|e<UGÐÌ@ãy!'"ZQ.?I}\.Q++"http"JQ.?++"ftp"J ``` [**Test suite**](https://pyth.herokuapp.com/?code=J%22%3A%2F%2F%22I%3AQ.%22%28%7C%06%C2%90%C2%9De%3CUG%C3%90%C3%8C%40%C3%A3%11y%21%27%22ZQ.%3FI%7D%5C.Q%2B%2B%22http%22JQ.%3F%2B%2B%22ftp%22J&test_suite=1&test_suite_input=%22dan-pc%22%0A%22https%3A%2F%2Flocalhost%2F%22%0A%22ftp%3A%2F%2Ffoo%22%0A%22http%3A%2F%2Ffoo%22%0A%22f.oo%22%0A%22derp.me%22%0A%22another.one%2F%22%0A%22%2F%2F%22%0A%22a%3A%2F%2Fb%22&debug=0) ### Code contains unprintable characters, and as such does not display properly on Stack Exchange. The link provided contains these characters and is the correct version of the program. ]
[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/17368/edit). Closed 6 years ago. [Improve this question](/posts/17368/edit) Lucky numbers are those numbers which contain only "4" and/or "5". For example 4, 5, 44, 54,55,444 are lucky numbers while 457, 987 ,154 are not. Lucky number sequence is one in which all lucky numbers exist in increasing order for example 4,5,44,45,54,55,444,445,454,455... Now we concatenate all the lucky numbers (in ascending order) to make a lucky string "4544455455444445454455..." Given n, your task is to find the nth digit of the lucky string. If the digit is 4 then you have to print "F" else you have to print "E". ``` 1<=n<=10^15 ``` [Answer] ## JavaScript - 49 ``` for(s=i=0;!(r=s[n+i++]);s+=i.toString(2));"FE"[r] ``` Execute this on a JavaScript console (tested on Node), with `n` set to the 1-based index of the digit you want. Explanation: The script builds a version of the lucky string, and stops when the character we're looking for exists. ``` Lucky string: 4 5 44 45 54 55 Generated string: 011011100101110111 ``` The lucky string is equivalent to [the concatenation of all binary numbers with the leading one stripped](http://oeis.org/A076478). We can get the index of the appropriate character in `s` from `n` by adding the number of leading ones in the string to skip, or, equivalently, how many binary numbers we generated. Luckily for us, we can just grab the current value of `i`. It greatly helps to see the final values of `s` and `i` after running. For sake of brevity, I won't post a table here, but you can certainly check their values in the console. Details: ``` s=i=0 ``` Initializes `s` and `i`. `s` later becomes a string, but rather than initialize to `"0"`, `0` works fine because of implicit type conversion. ``` i++ ``` Increments i every iteration. ``` r=s[n+i++] ``` Gets the character of `s` at `n+i` (0 or 1) and stores it in `r`. ``` !(r=s[n+i++]) ``` Loops while the character we are looking for is still undefined. ``` s+=i.toString(2) ``` Appends the next binary number in sequence to `s`. ``` "FE"[r] ``` Causes the expression to evaluate to `F` if `r` is `0`, `E` if `r` is `1`. [Answer] ## GolfScript: 48 ``` 10 15?,{''+{.52=\53=|}%{&}*},{''++}*=52='F''E'if ``` Very inefficient. Can definitely be improved. Explanation: `10 15?,` builds a sequence of the first `10^15` numbers. The next block preceding the next comma filters the sequence down to so-called lucky numbers by converting to a string, mapping characters of the string to `1` if they equal `'4'` (52) or `'5'` (53), and then folding `&` over the elements. Finally, fold string concatenation across the lucky sequence to form a big string, take the nth element, and convert to `'F'` or `'E'` appropriately. [Answer] # GolfScript, 34 Based on Kendall Frey's solution, uses 0-based indices. ``` ~''{0):0 2base(;+.,2$)<}do='FE'1/= ``` Alternative solution, 44 bytes: ``` ~0{-.0):0.2\?*.@)<}do 1$+0/2base\0%)='FE'1/= ``` This has the advantage that it's **MUCH** faster, in fact it's instant even for 15-digit inputs. Java equivalent (more or less): ``` public static void f(long n) { long k = 0; // number of digits long t = 0; while (true) { k++; t = k << k; if (t > n) break; n -= t; } // the lucky number with 0s and 1s, prefixed with a 1 String s = Long.toBinaryString((n + t) / k); int d = s.charAt((int) (n % k + 1)) - '0'; // the digit we want System.out.println("FE".charAt(d)); } ``` [Answer] # Haskell, fast I'm aiming for the fastest program. The hidden structure of this question, as explained by Kendall Frey, is that the lucky numbers can be explained as binary numbers. But his answer is searching each number in succession, making for a terrible runtime for large numbers. Can we do better? How do we solve for `n=10^15` in a speedy manner? The length of each lucky number is the following: ``` x lucky length 1 4 1 2 5 1 3 44 2 4 45 2 5 54 2 6 55 2 7 444 3 8 445 3 9 454 3 10 455 3 11 544 3 e t c ``` Note the pattern in the length increase. We first have a run of 2 same-length numbers, then 4, 8, 16, 32, ... I'm going to use this fact to find the length of my number fast, by multiplying by two until I find the "block" of similar-length numbers, and accumulate the length up to that block. I then use divison to find out which number inside that block is the one I'm looking for, and modulo to find what digit it has. ``` find n = let (digits, n') = block n num = n' `div` digits digit = digits - (n' `rem` digits) - 1 in case (num `div` (2^digit)) `rem` 2 of 0 -> 'F' 1 -> 'E' -- Return (digits in each number in block, n-(length up to block)-1) block n = block' n 2 0 2 1 where block' n add acc pow length | acc+add >= n = (length, n-acc-1) | otherwise= let len' = length+1 pow' = pow*2 add' = len'*pow' in block' n add' (acc+add) pow' len' ``` (I stumbled across lots of off-by-one pitfalls while implementing this. Also, I didn't see aditsus speed-edit until I had already written this, but at least I bring an explanation :-) ) [Answer] **Python 2.7** based on Kendall Frey somewhat deduction of the problem xD ... well spot ``` s = "";n=10;i=2 while len(s) < n: i+=1; s+=bin(i)[3:] print "FE"[int(s[n-1])] ``` ]
[Question] [ One of my colleagues proposed us a challenge: to write the shortest C/C++ program to determine if a number is even or odd. These are the requirements: * Get a number from keyboard, at run-time (not from command line) * Output the string `pari` if the number is even * Output the string `dispari` if the number is odd * We can assume that the input is legal * We can assume that the machine has a i386 architecture * Code preprocessing is not allowed (e.g.: use `#define`s) * [edit after comments] The code can be considered valid if it compiles with `gcc 4.x` This is the best attempt we had so far (file test.c, 50B): ``` main(i){scanf("%d",&i);puts("dispari"+3*(~i&1));} ``` Do you think we can go further? (\*): "dispari" is the italian for odd and "pari" is the italian for even [Answer] ## 47 bytes (2 less) ``` main(i){scanf("%d",&i);puts("dispari"-~i%2*3);} ``` For a positive `i`, `~i` is negative, so `~i%2` is 0 or -1. [Answer] ## 39 bytes Given you didn't specified the range of the number input, then here's a solution that handles 0..9 only: ``` main(){puts("dispari"-~getchar()%2*3);} ``` [Answer] # 48 bytes ``` main(i){scanf("%d",&i);puts("dispari"+3-i%2*3);} ``` [Answer] ## 34 bytes Build with ``` gcc -nostartfiles -Wl,-ea odd.c ``` Works in GCC 6.3.0. ``` a(){puts("dispari"-~getch()%2*3);} ``` ]
[Question] [ **Overview** Adding slightly to [the complexity of working with Roman numerals](https://codegolf.stackexchange.com/q/6005/3862)... The ancient Romans devised a number system using Latin letters, which served them well, and which is still used by modern civilization, though to a much smaller degree. In the time of its use, Romans would have had to learn to use and manipulate these numbers in order to be of much use for many applications. For example, if a man owned 35 oxen, and he sold 27 of them, how would he know the new total other than counting them all? (*Ok, that and using an abacus...*) If the Romans could do it, surely we can figure it out as well. **Objective** Write the shortest algorithm/function/program that will **subtract** two Roman numerals together and output the result **without** converting the string representation of either input into a number. **Rules/Constraints** Because of historical/pre-medieval inconsistencies in formatting, I'm going to outline some non-standard (per modern usage) rules for orthography. See the value guide below as an example. * Since we are subtracting, negative numbers are permissible. 0s, as they have no representation in the Roman system, should be returned as `NULL` or an empty string. * The letters I, X, C, and M can be repeated up to four times in succession, but no more. D, L, and V can never be repeated. * The letter immediately to the right of another letter in the Roman representation will be of the same or lesser value than that to its left. + In other words, `VIIII == 9` but `IX != 9` and is invalid/not allowed. * All input values will be 2,000 (MM) or less; no representation for numbers greater than M is necessary. * All input values will be a valid Roman numeral, pursuant to the rules above. * You may not convert any numbers to decimal, binary, or any other number system as part of your solution (you are welcome to use such a method to *VERIFY* your results). * This is code golf, so shortest code wins. I do have a solution to this problem that has already been beaten, but I'll hold off on posting it for a few days to see if any other answers come up. **Value Guide** ``` Symbol Value I 1 II 2 III 3 IIII 4 V 5 VIIII 9 X 10 XIIII 14 XXXXIIII 44 L 50 LXXXXVIIII 99 C 100 D 500 M 1,000 ``` **Examples** ``` XII - VIII = IIII (12 - 8 = 4) MCCXXII - MCCXXII = '' (2,222 - 2,222 = 0) XXIIII - XXXXII = -XVIII (24 - 42 = -18) ``` If any further clarification is needed, please ask. [Answer] ## sed 144 Most of you will know this little episode from roman times, when Cesar invented the Cesar crypting (aka rot13) using SED. As a big fanatic of SED, he printed the most common used commands: substitute, print, quit and read (SPQR) on signs which he carried with him to teach his soldiers the use of SED. ``` # 63 = sed-file # 81 = this # 144 summa summarum tac a|rev|sed y/gs/sg/ >b echo $1|sed -f a|sed "s/$(echo $2|sed -f a)//"|sed -f b ``` ### first version 181: ``` # 126 = 2 sed-files =126 # 55 = this # 181 summa summarum echo $1|sed -f a|sed "s/$(echo $2|sed -f a)//"|sed -f b ``` 2 files to use which count to the solution: a: ``` s/M/DD/g s/D/CCCCC/g s/C/LL/g s/L/XXXXX/g s/X/VV/g s/V/IIIII/g ``` b: ``` s/IIIII/V/g s/VV/X/g s/XXXXX/L/g s/LL/C/g s/CCCCC/D/g s/DD/M/g ``` but b can be produced with the first line of the new solution from a: it is - more or less - the inverse, and so we read the file from bottom to top (tac) and from right to left (rev), and switch s and g which are now in the wrong order. Invocation: ``` ./cg-6061-roman-minus.sh MDCCCCLXV LXVI MDCCCLXXXXVIIII ``` I guess I can golf this further, but I liked to occupy wallstreet the sed slot. :) Since the logic isn't only in the sed files, but in the invocation too, I sum it all up. It could be argued about echo $1, but what about the nested $2? Let's just sum it together. The sedfiles are pretty long and very redundant in their structure. There seems to be room for optimization. Luckily, the romans already had `QVANTVM <OMPVTVVMZ`, so they didn't care for the otherwise lousy performance. ### tl;dr: I convert both numbers into church numerals (IIIIII=6), remove the second from the first, and reconvert the result back. s.e.d. - sod errat demonstrandum. [Answer] ### Ruby, 112 characters Using the same idea - but considerably longer than the add-version: ``` f=->a,b{r=0;v=5;n="IVXLCDM".gsub(/./){|g|r+=a.count(g)-b.count(g);t=r%v;r/=v;v^=7;g*t}.reverse;r<0?"-"+f[b,a]:n} ``` It is an implementation as a function. Takes two strings and returns the result when subtracting the second from the first. Examples: ``` puts f["XII", "VIII"] # -> IIII puts f["MCCXXII", "MCCXXII"] # -> puts f["XXIIII", "XXXXII"] # -> -XVIII ``` [Answer] ## Sed, 146 chars ``` :;s/M/DD/;s/D/CCCCC/;s/C/LL/;s/L/XXXXX/;s/X/VV/;s/V/IIIII/;t;s/\(I\+\)-\1/-/;:a;s/IIIII/V/;s/VV/X/;s/XXXXX/L/;s/LL/C/;s/CCCCC/D/;s/DD/M/;ta;s/-$// ``` This is a pure sed implementation. Input is expected to be in the following format, with no spaces ``` XXIIII-XXXXII ``` It outputs negative values correctly, and prints zeros as empty strings. still trying to shave a bit off the code without resorting to using extended regexps [Answer] ## Sed, 154 chars This is a table driven implementation, correctly outputs negative numbers. expects input in the form of `V-VI` ``` s/$/;,MDD,DCCCCC,CLL,LXXXXX,XVV,VIIIII,/;:;s/\([^;]\)\(.*;.*,\1\([^,]\+\),\)/\3\2/;t;s/\(I*\)-\1/-/;:b;s/\([^;]\+\)\(.*;.*,\(.\)\1,\)/\3\2/;tb;s/-*;.*$//; ``` [Answer] ## VBA - 396 ``` Function s(f,c) a=Split("I,V,X,L,C,D,M",",") For i=6 To 0 Step -1 x=Replace(f,a(i),""):y=Replace(c,a(i),""):m=Len(f)-Len(x):n=Len(c)-Len(y) If b=0 Then b=IIf(m>=n,IIf(m=n,0,1),2) Next q=f:p=c If b=1 Then:p=f:q=c For i=0 To 6 x=Replace(p,a(i),"") y=Replace(q,a(i),"") t=(Len(p)-Len(x)-u)-(Len(q)-Len(y)) r=IIf(i Mod 2,2,5) u=IIf(t<0,1,0) t=IIf(t<0,t+r,t) s=String(t,a(i)) & s Next If b=2 Then s="-" & s End Function ``` [Answer] ## Erlang 392 ``` -module(r). -export([s/2,n/1]). e(L)->[Y||X<-L,Y<-t([X])]. -define(T(A,B),t(??A)->e(??B);). ?T(M,DD)?T(D,CCCCC)?T(C,LL)?T(L,XXXXX)?T(X,VV)?T(V,IIIII)t(L)->L. s([H|A],[H|B])->s(A,B);s(R,[])->n(R);s([],R)->[$-|n(R)];s(A,B)->s(e(A),e(B)). n(L)->d(c(l(x(v(i(L)))))). -define(E(F,A,B),F(??A++X)->??B++F(X);F(X)->X). ?E(i,IIIII,V). ?E(v,VV,X). ?E(x,XXXXX,L). ?E(l,LL,C). ?E(c,CCCCC,D). ?E(d,DD,M). ``` Usage: ``` 1> c(r). {ok,r} 2> r:s("XXIIII","XXXXII"). "-XVIII" 3> r:s("MCCXXII","MCCXXII"). [] 4> r:s("XII","VIII"). "IIII" ``` [Answer] # JavaScript 276 I honestly thought I could make this smaller... Alas, not as easy as one might think... I'd appreciate any help with reducing this even further... ``` a="IIIII0VV0XXXXX0LL0CCCCC0DD0M".split(0);d=(e,b)=>e.replace(g=RegExp((c=z)>b?a[c][0]:a[c],"g"),c>b?a[b]:a[b][0]);x=(w=prompt().split("-"))[0];y=w[1];for(z=6;0<z;z--)x=d(x,z-1),y=d(y,z-1);r=x>=y?x.replace(y,""):y.replace(x,"");for(z=0;6>z;z++)r=d(r,z+1);alert((x>=y?"":"-")+r) ``` [Answer] ## C++ 581 478 ``` #define A [j]==a[i]? #define B for(j=0;j< #define C .length();j++){ #define E 1:0) #include <iostream> int main(){int b=0,m=0,n=0,k,l,j,i,u=0,r,t;std::string x,y,q,p,s,a="IVXLCDM";std::cin>>x>>y;for(i=6;i>=0;i--){B x C m+=(x A E;}B y C n+=(y A E;}b=(b==0?(m>=n?(m!=n?E:2):b);}if(b==1){p=x;q=y;}else{p=y;q=x;}for(i=0;i<7;i++){k=0;l=0;B p C k+=(p A E;}B q C l+=(q A E;}t=(k-u)-l;r=(i%2?2:5);u=(t<0?E;t=(t<0?t+r:t);B t;j++){s=a[i]+s;}}s=(b==2?"-"+s:s);std::cout<<s<<"\n";return 0;} ``` [Answer] ## Python 3, 401 This is a port of my VBA solution, and the length makes me think I need to learn some more about Python. :-/ ``` a="IVXLCDM" f=input() c=input() g=range s=x=y=z="" b=u=0 for i in g(6,-1,-1):x,y=f.replace(a[i],z),c.replace(a[i],z);m=len(f)-len(x);n=len(c)-len(y);b=b if(b!=0)else 0 if(m==n)else 1 if(m>n)else 2 q,p=f,c if(b==1):p,q=f,c for i in g(7): x,y=p.replace(a[i],z),q.replace(a[i],z);t=(len(p)-len(x)-u)-(len(q)-len(y));r=2 if(i%2)else 5;u=1 if(t<0)else 0 if(t<0):t+=r s=a[i]*t+s if(b==2):s="-"+s print(s) ``` ]
[Question] [ I recently tried to produce the shortest C code possible to display all its command line arguments (which are stored in argv). I ended with a relatively small piece of code, and I was wondering if there was some trick I'm not aware of. Here's my try (I compile with C17, but any standard before C23 is very likely to compile/link/run as intended, probably with some warnings though): ``` main(c,v)int**v;{for(;*v;)puts(*v++);} ``` First, `main(c,v)int**v`. In C, every variable and function must have a type, but if it isn't specified at the declaration, then `int` [is assumed](https://stackoverflow.com/questions/25171602/what-is-the-default-type-for-c-const). For now, it means `main` function returns an `int`, and both `c` and `v` (argc and argv) are also of `int` type. But, the `int**v` right after the closing parenthesis is actually changing the type of `v` to `int**`. This syntax is the old-style function definition, back from the K&R book. However, C23 standard plans to remove this feature from the language (see on [cppreference](https://en.cppreference.com/w/c/language/function_definition)). So we end up with `c` being an int (as a normal `argc` is), and `v` being an `int**` (contrary to a normal `argv` which is `char**` or `char*[]` (but `char*[]` is treated as a `char**` in a function)). Then, the for loop `for(;*v;)` (note: a `while(*v)` does the same thing). As a remainder, `v` is filled with a list of char pointers to the command line arguments, but they're treated as integer pointers and not character pointers here. Thus, the loop runs until the first pointer in `v` is NULL (is equal to 0). `puts(*v++);` does two things ; writing down the first string (it takes the first pointer in `v`, a `int*`, but `puts` expects a `char*`, so it can correctly deal with it) in the console and increases `v` (instead of having an iterator variable i, then doing `v[i]`, here I use `*v` and `v++` to save some characters). I also haven't used curly brackets around the for loop because when omitting them, the loop body is the first statement below it. I used `int` instead of `char` to declare `v`, in order to save a char. But is there a platform where those pointer types aren't the same size ? I once saw that function pointers may have a different size than ordinary pointers, but I don't know if this may be true for two pointers of different types. It is guaranteed that `argv[argc]` is NULL, thus the code is guaranteed not to have an infinite loop (see [here](https://stackoverflow.com/questions/3772796/argvargc)). Then no need to add a `return 0;` because it is guaranteed `main` will return 0 if I don't put a `return` statement. Some may wonder why I was able to call `puts` without including stdio.h, it's because in C, [the whole library is linked to the binary](https://stackoverflow.com/questions/2199076/printf-and-scanf-work-without-stdio-h-why?noredirect=1&lq=1) (this question is a duplicate, but I put it here because the answer better explains this point than the original question). It also not seems to have a standard behavior (hence the warning), thus be aware of that (never rely on an undefined behavior). Same thing seems to apply for implicit `int` type. Can someone confirm or not ? Thus, my final question, is there any way to shorten this code ? I'm asking either for standard or platform-specific ways. Sorry for the long post, but I wanted to explain for any interested beginner. [Answer] # [C (gcc)](https://gcc.gnu.org/), 37 bytes ``` main(c,v)int*v;{for(;*v;)puts(*v++);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1mnTDMzr0SrzLo6Lb9IwxrI0CwoLSnW0CrT1ta0rv3//3/i/6R/yWk5ienF/3VzjY0A "C (gcc) – Try It Online") When using 32-bit, you can use `int` to store a pointer if not explicitly deferred # [C (gcc)](https://gcc.gnu.org/), 35 bytes, exit by segment fault ``` main(c,v)int*v;{for(;puts(*v++););} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1mnTDMzr0SrzLo6Lb9Iw7qgtKRYQ6tMW1vTWtO69v///4n/k/4lp@Ukphf/1801NgIA "C (gcc) – Try It Online") [Answer] # [C (GCC)](https://gcc.gnu.org), 34 bytes ``` main(c,v)int*v;{execvp("echo",v);} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700OT49OXnBgqWlJWm6FjeVchMz8zSSdco0M_NKtMqsq1MrUpPLCjSUUpMz8pWAwta1EJVQDTCNAA) # [C (GCC)](https://gcc.gnu.org) with `-m32` flag, 28 bytes *thanks to [@jdt](https://codegolf.stackexchange.com/users/41374/jdt)* ``` main(c,v){execvp("echo",v);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1mnTLM6tSI1uaxAQyk1OSNfCShgXfv////E/0n/ktNyEtOL/@vmGhsBAA "C (gcc) – Try It Online") --- Replaces the current process image with the process image of `/bin/echo` (which is assumed to be in the `PATH`). It may not work correctly if the first argument(s) are recognized as flags by your version of echo. May not be useful in every situation. Note that more than the first argument could be messed up. For example, with GNU coreutils' echo: * `-n`, `-e`, `-E` are recognized as short arguments, so `/bin/echo -n -e x` outputs just `x`, while `/bin/echo -n x -e` outputs `x -e`; * `/bin/echo --help` and `/bin/echo --version` print a lot of stuff that wasn't present in the arguments. [Answer] # [C](https://en.wikipedia.org/wiki/C_(programming_language)) ([gcc](https://gcc.gnu.org/)): 37 bytes ``` main(c,v)int**v;{main(puts(*v),++v);} ``` Don't forget about recursion. :) [Try it online](https://tio.run/##S9ZNT07@/z83MTNPI1mnTDMzr0RLq8y6GixQUFpSrKFVpqmjrV2maV37//9/w/9G/43/m/xLTstJTC/@r1sOAA) [Answer] # [C (gcc)](https://gcc.gnu.org), 37 bytes ``` main(c,v)int*v;{for(;*v;)puts(*v++);} ``` ]
[Question] [ [Greeklish](https://en.wikipedia.org/wiki/Greeklish), a portmanteau of the words Greek and English, is a way of writing modern Greek using only ASCII characters. This informal way of writing was extensively used in older applications / web forums that did not support Unicode, and were not programmed to show Greek characters. Nowadays, its use is minimized due to the Unicode support of modern platforms, but there are still some users who opt to write in it. ## Input / Output: Your task in this challenge, should you choose to accept it, is to take as input a lowercase, non-punctuated sentence written in Greeklish and output it in the same format in non-accented modern Greek. To do this conversion you should use the table below. Note that the digraph characters take precedence over single characters during conversion. You are free to opt any acceptable string format that works best for you (e.g., a sentence, a list of words, etc.). ## Conversion table | ASCII Character(s) | Greek Character | | --- | --- | | a | α | | b | β | | g | γ | | d | δ | | e | ε | | z | ζ | | h | η | | 8 | θ | | i | ι | | k | κ | | l | λ | | m | μ | | n | ν | | ks, 3 | ξ | | o | ο | | p | π | | r | ρ | | s | σ | | t | τ | | y | υ | | f | φ | | x | χ | | ps, 4 | ψ | | w | ω | ## Test cases ``` geia soy kosme -> γεια σου κοσμε epsaxna gia mia aggelia sth thleorash -> εψαχνα για μια αγγελια στη τηλεοραση kati 3erei sxetika me ayto -> κατι ξερει σχετικα με αυτο pswnisa ksylina spa8ia -> ψωνισα ξυλινα σπαθια ekeinh agorase 4aria kai 8ymari -> εκεινη αγορασε ψαρια και θυμαρι ``` ## Rules * You may use [any standard I/O method](https://codegolf.meta.stackexchange.com/q/2447) * [Standard loopholes](https://codegolf.meta.stackexchange.com/q/1061) are forbidden * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Answer] # [Python](https://www.python.org), 121 bytes ``` lambda s:re.sub("[kp]s|\S",lambda c:chr(1023&"abgdezh8iklmn3opr_styfx4w".find(c[0])%(824+2*ord(c[0][0]))-79),s) import re ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XY9RSgNBDIbfPUVY0N3VbaltwbXgKXxsi6RtdifM7swwmdKOeBNfCqJn0ts4pUXUQEhIvp8_ef1wMShrDm_Nw-J9G5pB_RU77FcbBJl5Gsp2VWRz7ZbysnjMqvNqPVsrX9yOxpOrDFfthp5VzbrrzcQ6_yQhNvvpLhs2bDbFej5alpdFPZ7ejK-tPw2Os3Jwd19WUl5w76wP4Ol8wGdjPQiwgXneEqdLbARtpae8ggv4iZyc4N4gtInpU2LbUnfkg4KgOrIeRf3TaAwME_LEIHsKrJOUAGOwefWbc7IzLAhaYsfJQxzWjH8Z0sRGJdujEcEUfTLXyFDHPvX5cpZo59mEoimkLE__HQ6n-g0) This is a lot like Arnauld's approach. I did some weird math and I'm not sure if it helped. [Answer] # JavaScript (ES6), ~~106~~ 105 bytes ``` s=>s.replace(/[kp]s|\S/g,s=>String.fromCharCode(946+'bgdezh8iklmn3opr_styfx4w'.search(s[1]?s<'p'?3:4:s))) ``` [Try it online!](https://tio.run/##dVJNjtMwFN73FE/ZJBEhI9QKlUKmixEnmGWo0JuOk5j8OLIjpkEsqEo1g4TEhiUcokJRW5ifGzh3mAtwhPLcAANCWPJz/Bx/f/ILfIlqKnlZ3S/EKdtFwU4Fh8qXrMxwypyDMC0n6vWz44PYo4PjSvIi9iMp8qME5RFdcR4NHt6zT@JT9ioZ8jTLi74o5XNV1dFscGb7iqGcJo4KH0zG6old2uP@aDBSruvuHoc9gBCsmHEEJWpIhcqZ5cF/hqW/6EZv9Qrahb5pl6C/0rLQl7qxYOJ1YKxUOCsQYsLMaWIcs8zgVwlUScaERJUQh6Wb9kKv2nN9RYCEbHAJar@saG@4vv1ka9/qNZhCnYY453Rxodd3rClWHPpMMg5qxiqeEjkDrCvxtx2LJK8IaAv6mgTMjR@Df04b6ppTI6IhCe2SOjd3FKU6K7hCSFWdcTKoShxy/Dctq71o35GpLSkksOt2ubdx1Rl5Q942xtUfiaWMFwkFZaJhMEBJcaXIYVjn9P2bgRIjfc0ea91l9CuJBvZZzrv0yIQxuCHmy65LZL1Jz4@EfIr0GJwQ0IMTmLgQHMJUFEpkzM9E7EQOuh6YCkFAf4zB/r75cPvpI1UbRmDffn5v09P5AQ "JavaScript (Node.js) – Try It Online") ### Commented ``` s => // s = input string s.replace( // replace in s: /[kp]s|\S/g, // the digraph 'ks', the digraph 'ps' // or any other non-space character s => // with String.fromCharCode( // the character whose Unicode code point 946 + // is 946 (for 'β') 'bgdezh8iklmn3opr_styfx4w' // + the position of the reference /* ς is missing ^ */ // character in this lookup string // (giving -1 for 'a' which is omitted) .search( // where said reference character is: s[1] ? // if this is a digraph: s < 'p' ? 3 : 4 // '3' for 'ks' or '4' for 'ps' : // else: s // s itself ) // end of search() ) // end of String.fromCharCode() ) // end of replace() ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 45 bytes ``` ks 3 ps 4 T`abg\dez\h8ik-n3o-pr_styfx4w`α-ω ``` [Try it online!](https://tio.run/##FY7BDcMwDAP/nkIL5JU8MkifARoVVW1BiW1YBhp3g47TRdqRXOVBgCCIIwtVjti7qBtdVje5y4o3v9zptYSZZYhjGnK5am2PY3qu38/we/fuiRE0NZCkOznKikdE8JbuJvSetrNRA9SwUSqowQlWhpEKMehhu2JlAmw12fIzsiKIts3@gGacGR0JcQyGOwEEExaDCjLMbTf/Bw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` ks 3 ps 4 ``` Translate the digraphs. ``` T`abg\dez\h8ik-n3o-pr_styfx4w`α-ω ``` Translate the letters. The order is chosen to minimise the number of Greek letters used, going so far as to add in the dummy `_` (which never matches unless quoted) so that the missing `ς` doesn't need to be special-cased. (Note that `d`, `h`, `o` and `p` have special meanings if they are not quoted or part of a range.) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 50 bytes ``` ≔”+%⊟⊟Kκ↓⁼≧T_X4⍘«⊞⊞ ↘”θ⭆⪫⪪⪫⪪SksI³psI⁴⎇№θι℅⁺⁹⁴⁵⌕θιι ``` [Try it online!](https://tio.run/##TY4xC8JADIX3/oqjUwp1agXFSQRBQSjo6BJrbUPP9Hq5qvXPnz0cdMkL33svpGzQlh1q79ciVDPEeKmv1btZUKvvnHXGnlnceHvlzzhVfbKKCkvs4OgmqQ9oYN8Rw9Focv/rjs3gviFIUhW3Ek@yQXGQJQGYH8gDOFWW0Y6w6YbpfJ8qCvb0HpauslDoQWCZz1O1Jb5@/VALc@W9kSeToGpl1MSoxOCCMPKzh/4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @Arnauld's JavaScript answer. ``` ≔”+%⊟⊟Kκ↓⁼≧T_X4⍘«⊞⊞ ↘”θ ``` Create the lookup table `abgdezh8iklmn3opr¶styfx4w` from a compressed string. ``` ⭆⪫⪪⪫⪪SksI³psI⁴⎇№θι℅⁺⁹⁴⁵⌕θιι ``` Replace `ks` with `3` and `ps` with `4` in the input, then translate any characters in the lookup table to the appropriate Greek letter. Note that although the Greek letters are in Charcoal's character set, they need to be quoted and can't be compressed which makes them too expensive to use. [Answer] # [Lexurgy](https://www.lexurgy.com/sc), 127 bytes Simple 1-1 substitution. The `Symbol` forces `ks` and `ps` to be treated as a single character/string. ``` Symbol ks,ps k: {a,b,g,d,e,z,h,\8,i,k,l,m,n,ks,\3,o,p,r,s,t,y,f,x,ps,\4,w}=>{α,β,γ,δ,ε,ζ,η,θ,ι,κ,λ,μ,ν,ξ,ξ,ο,π,ρ,σ,τ,υ,φ,χ,ψ,ψ,ω} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~48~~ ~~46~~ 45 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 3„ks4„ps8).•ŒMb•ASr‡•qâ&¬k±ûï+%ΘÔβ>&•₂в944+ç: ``` [Try it online.](https://tio.run/##FY4xysJAEIX7nGIIKIhgY4poIXiAv/IEIwzJsEk2ZhZ@0wWPIBZWgjY2gmhr52IrniEXiWMxbx7zHh9jBZdMXTdum4ORSLWUeDBqm9Nr@7fUNV9UbXNUs/Kn/vNinjf/8Ndh7733u/d91tek3Ww@90kUDf152nVhGCbECGJrMFZyCqgUXBcIiV5zHUwSyn4Nl4JLM7IVShoYdAxjqohB1uTYaJkAa2eDUv4LFgQjdcYKkhJjxoAMcZEq7gcgiLBSqEGGuM7V6yNf) **Explanation:** Although [05AB1E's codepage](https://github.com/Adriandmen/05AB1E/wiki/Codepage) includes a lot of the Greek characters (`αβδεaγηιλμοζ`), it doesn't include all of them (missing `φκνπρστωχυ`), so just converting codepoint-integers to the characters for all of them is shorter than using part literal string and part conversion. ``` 3„ks4„ps8 # Push 3, "ks", 4, "ps", 8 ) # Wrap the stack into a list: [3,"ks",4,"ps",8] .•ŒMb• # Push compressed string "qcujv" A # Push the lowercase alphabet: "abcdefghijklmnopqrstuvwxyz" S # Convert it to a list of characters r # Reverse these three values on the stack ‡ # Transliterate "q"→"3"; "c"→"ks"; "u"→"4"; "j"→"ps"; "v"→"8" # (note that "c"→"ks" comes before "k" and "j"→"ps" before "p" in the alphabet) •qâ&¬k±ûï+%ΘÔβ>&• # Push compressed integer 259947718887064480860780139517113420 ₂в # Convert it to base-26 as list: [1,2,14,4,5,22,3,7,9,24,10,11,12,13,15,16,14,17,19,20,24,8,25,23,21,6] 944+ # Add 944 to each: [945,946,958,948,949,966,947,951,953,968,954,955,956,957,959,960,958,961,963,964,968,952,969,967,965,950] ç # Convert these codepoint-integers to characters: ["α","β","ξ","δ","ε","φ","γ","η","ι","ψ","κ","λ","μ","ν","ο","π","ξ","ρ","σ","τ","ψ","θ","ω","χ","υ","ζ"] : # Replace all "a"→"α"; "b"→"β"; "ks"→"ξ"; etc. in the (implicit) input # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (sections *How to compress strings not part of the dictionary?*; *How to compress large integers?*; and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•ŒMb•` is `"qcujv"`; `•qâ&¬k±ûï+%ΘÔβ>&•` is `259947718887064480860780139517113420`; and `•qâ&¬k±ûï+%ΘÔβ>&•₂в` is `[1,2,14,4,5,22,3,7,9,24,10,11,12,13,15,16,14,17,19,20,24,8,25,23,21,6]`. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 53 bytes ``` ‛ks958CV‛ps968CVka«Þİ»«»1m»Ŀ»4⁽.ṘŻ⟨«⋎D-§ƛE←₍»₄τ944+CĿ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigJtrczk1OENW4oCbcHM5NjhDVmthwqvDnsSwwrvCq8K7MW3Cu8S/wrs04oG9LuG5mMW74p+owqvii45ELcKnxptF4oaQ4oKNwrvigoTPhDk0NCtDxL8iLCIiLCJlcHNheG5hIGdpYSBtaWEgYWdnZWxpYSBzdGggdGhsZW9yYXNoIl0=) Transliterate doesn't work when replacing two-character strings unfortunately, so `ks` and `ps` had to be done separately. Otherwise this would be 45 bytes. ``` ‛ks958CV‛ps968CVka«Þİ»«»1m»Ŀ»4⁽.ṘŻ⟨«⋎D-§ƛE←₍»₄τ944+CĿ ‛ks V # Replace all occurrences of "ks" with... 958C # Character code 958, "ξ" ‛ps V # Replace all occurrences of "ps" with... 968C # Character code 968, "ψ" ka # Push the lowercase alphabet «Þİ»« # Push compressed string "cjquv" »1m» # Push compressed number 12348 Ŀ # Transliterate in the alphabet, c -> 1, j -> 2, q -> 3, u -> 4, v -> 8 # Produces "ab1defghi2klmnop3rst48wxyz" (as a list of single-character strings). Call this V »4⁽.ṘŻ⟨«⋎D-§ƛE←₍» # Compressed integer 255394376001292872295693368395691084 ₄τ # Convert to base-26 as a list 944+ # Add 944 to each C # Get the character codes of each: "αβαδεφγηιακλμνοπξρστψθωχυζ" (as a list of single-character strings). Call this X Ŀ # Replace each of V with the corresponding character in X in the input ``` ]
[Question] [ **Expand an array to all directions by duplicating the outer elements** You will be given two inputs: an array and the expansion degree For example if I give you `[[1,2,3][4,5,6][7,8,9]]` and `3`, you must output: ``` 1 1 1 1 2 3 3 3 3 1 1 1 1 2 3 3 3 3 1 1 1 1 2 3 3 3 3 1 1 1 1 2 3 3 3 3 4 4 4 4 5 6 6 6 6 7 7 7 7 8 9 9 9 9 7 7 7 7 8 9 9 9 9 7 7 7 7 8 9 9 9 9 7 7 7 7 8 9 9 9 9 ``` As you can see the given array is in the center and all the outer elements have expanded: `1` -> 3 times up, 3 times left and also to every position of the upper left corner `2`-> 3 times up `5`-> is not an outer element etc here are some more test cases to make things clearer ``` Input [[4,5,6]],0 Output 4 5 6 Input [[1]],2 Output 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 Input [[1,2,3]],2 Output 1 1 1 2 3 3 3 1 1 1 2 3 3 3 1 1 1 2 3 3 3 1 1 1 2 3 3 3 1 1 1 2 3 3 3 Input [[1,2,3][11,22,33][111,222,333][1111,2222,3333]],1 Output 1 1 2 3 3 1 1 2 3 3 11 11 22 33 33 111 111 222 333 333 1111 1111 2222 3333 3333 1111 1111 2222 3333 3333 ``` You can use as many whitespaces as you like. But the output has to be a `mXn` array just like it is shown here. You cannot output a list of lists. This is [codegolf](/questions/tagged/codegolf "show questions tagged 'codegolf'") Shortest answer on bytes wins [Answer] # Octave, 35 bytes ``` @(a,x)padarray(a,[x x],'replicate') ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQSNRp0KzIDElsagosRLIia5QqIjVUS9KLcjJTE4sSVXX/J9mq5CYV2zNlahgqxDNZahgpGDMZaJgqmDGZa5goWAZa81VAZQxtuZKAxv2HwA "Octave – Try It Online") [Answer] # [Matlab](https://www.mathworks.com/products/matlab.html), 27 bytes ``` @(a,n)padarray(a,[n,n],'r') ``` The key over the Octave solution is that Matlab accepts partial option strings when they are unambiguous. [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` th2Y5I4$Ya ``` Port of [@rahnema1's Octave answer](https://codegolf.stackexchange.com/a/145923/36398). [**Try it online!**](https://tio.run/##y00syfn/vyTDKNLU00QlMvH/f2OuaEMFIwVjawUTBVMFM2sFcwULBctYAA "MATL – Try It Online") ### Explanation ``` t % Implicit input: number, n. Duplicate h % Concatenate. Gives an array [n,n] 2Y5 % Push 'replicate' (predefined literal). Will be used as an input flag I % Push 3. Will be used as equivalent to an input flag 4$ % Specify that the next function will use 4 inputs Ya % Call 'padarray' with 4 inputs. This takes the array as implicit % input. Number 3 as third input is interpreted as the input flag % 'both'. So the function pads the array (first input) by n in each % dimension (second input) by replicating the border (third input) in % both directions (fourth input). Implicit display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` ;ṫ¥0$¡Ṛ$⁺Zµ⁺G ``` [Try it online!](https://tio.run/##y0rNyan8/9/64c7Vh5YaqBxa@HDnLJVHjbuiDm0Fku7///@PjjbUUTDSUTCO1VGINgSxQRwoD8wF82ECEBGIkHFs7H9DAA "Jelly – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~138~~ 113 bytes *-9 bytes thanks to @JonathanFrech* *-16 bytes thanks to @Lynn* ``` a,n=input() for e in a[:1]*n+a+n*a[-1:]:print' '.join('%*s'%(len(`max(sum(a,[]))`),n)for n in e[:1]*n+e+n*e[-1:]) ``` [Try it online!](https://tio.run/##VY5LDoIwEED3nKIhIbRlNBbRBQknaZrQ6BgxMiV8Ejw9tpWNq3lvMW9m@MxPR@V2c3ds0jTdLFDT0bDMXCQPNzJkHTGra2UkFbYgafVB1aYexo7mnOXHl@uI55mc8oy/kXjb25VPS88taCNEK4BECFEI4R5CH8IYElssJf52giveWPhEVpvWFVzgagycEq2Vn2WYUML5j0ErD55@GDjIblGjhy31BQ "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 15 bytes ``` 2F2F¤¸².׫R}ø}» ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fyM3I7dCSQzsObdI7PP3Q6qDawztqD@3@/z862lBHwUhHwThWRyHaREfBVEfBDMQ011Gw0FGwjI3lMgEA "05AB1E – Try It Online") Yes, this [output format](https://codegolf.stackexchange.com/questions/145921/expand-an-array/145925#comment357035_145921) is [valid](https://codegolf.stackexchange.com/questions/145921/expand-an-array/145925#comment357036_145921). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~33~~ ~~28~~ 23 bytes ``` F2Fø2FR¤¸«]øεD€gZs-ú}ø» ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fzcjt8A4jt6BDSw7tOLQ69vCOc1tdHjWtSY8q1j28q/bwjkO7//835oqONtQx0jGO1Yk2MdExNdUxMwMyzc3NdSwsLHQsLS1jYwE "05AB1E – Try It Online") ~~15~~ 10 bytes of actual code, the rest is formatting the output. Explanation: ``` ¤ Copy last element ¸ Turn it into a list « Concatenate 2F Repeat twice R Reverse list each time 2F Repeat twice ø Transpose list each time F Repeat the given number of times ] Close all the loops ø Transpose the array D Duplicate €g Take length of each number Z Get the maximum s- Subtract each length from the maximum ú Pad with that number of spaces ε } For each row (column originally) ø Transpose back » Join with spaces and newlines ``` Formatting costs 2 bytes if I copy @ErikTheOutgolfer's output format for 12 bytes: ``` F2Fø2FR¤¸«]» ``` [Answer] # Python 2.7, 74 characters Pretty straightforward: uses numpy padding and regex to force a return string without brackets. This code returns an anonymous lambda. ``` import numpy,re;lambda a,n:re.sub('[\[\]]', '',str(numpy.pad(a,n,'edge'))) ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~94~~ ~~89~~ ~~86~~ 82 bytes ``` a,n=input() for l in a[:1]*n+a+n*a[-1:]:print' '.join(map(str,l[:1]*n+l+n*l[-1:])) ``` [Try it online!](https://tio.run/##VY1LDsIgEED3nIJ0099opFYXTXqSCQtSa8TgQBATPT0CduNq3kvezLhPuFka4mIv61xVVVRAsyb3Ck3LrtZzwzVxhZOQHfWqp07hTkxycl5TqHm9v1tNzUO55hk8mC00KTQlbNtYUpaOM7a@14XnX90YEUc4wVlKODBEkeaQJwxw/GNAkSDRDzNn2axo8bwlvg "Python 2 – Try It Online") ]
[Question] [ Your dumb teacher is always wrong, so flip his answer. ### Change these responses ``` True -> False Yes -> No 0 -> 1 Yeah -> Nope ``` and vice versa. Keeping punctuation and the first letter's capitalization counts. Only one condition will be passed to the program. **You only need to accept the following test cases**: ``` True <-> False True. <-> False. true <-> false true. <-> false. Yes <-> No Yes. <-> No. yes <-> no yes. <-> no. 0 <-> 1 Yeah <-> Nope yeah <-> nope Yeah. <-> Nope. yeah. <-> nope. ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~45~~ ~~41~~ ~~40~~ ~~39~~ 38 bytes ### Code: ``` “‰¦žä¥æ€¸pe…Ü€¸“ð¡2ôDí«D€™«vy`:D_D¹Êiq ``` ### Explanation: It first starts with the compression: ``` “‰¦žä¥æ€¸pe…Ü€¸“ ``` This is a compressed version of `"true false yeah nope yes no"`. After that, we split on the spaces with `ð¡`, resulting into: ``` ['true', 'false', 'yeah', 'nope', 'yes', 'no'] ``` We slice this array into pieces of 2 with `2ô`, resulting into: ``` [['true', 'false'], ['yeah', 'nope'], ['yes', 'no']] ``` We duplicate this array and reverse each element of it with `Dí`. Then we append this to our first array with `«`, resulting into: ``` [['true', 'false'], ['yeah', 'nope'], ['yes', 'no'], ['false', 'true'], ['nope', 'yeah'], ['no', 'yes']] ``` To get the titlecased words, we duplicate the array again and convert each word to titlecase with `€™`. Finally, this is appended to the initial array. So, the final list is: ``` [['true', 'false'], ['yeah', 'nope'], ['yes', 'no'], ['false', 'true'], ['nope', 'yeah'], ['no', 'yes'], ['True', 'False'], ['Yeah', 'Nope'], ['Yes', 'No'], ['False', 'True'], ['Nope', 'Yeah'], ['No', 'Yes']] ``` The imporant part here is that `Nope` comes *before* `No`. Eventually, we get to this part of the code: ``` vy`:D_D¹Êiq ``` Explanation: ``` v # For each in the array... y` # Push the array (containing 2 words) and flatten. : # Replace the first word with the second. D_ # Duplicate and negate (resulting 0 into 1 and 1 into 0). If this is not possible, this results into nothing. D # Duplicate the top of the stack again. ¹Ê # If it's not equal to the inital input string... iq # Quit the program and implicitly print the processed string. ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=4oCc4oCwwqbFvsOkwqXDpuKCrMK4cGXigKbDnOKCrMK44oCcw7DCoTLDtETDrcKrROKCrOKEosKrdnlgOkRfRMK5w4ppcQ&input=WWVzLg). [Answer] # Pyth, 44 bytes ``` j\.XXXcz\.`M2)Jc."<unprintables>"\b)rR3J ``` Hexdump: ``` 00: 6A5C 2E58 5858 637A 5C2E 604D 3229 4A63 10: 2E22 6179 0862 3C40 D23B 9A54 C2B4 A20A 20: FEE7 8701 225C 6229 7252 334A ``` [Test suite.](http://pyth.herokuapp.com/?code=j%5C.XXXcz%5C.%60M2%29Jc.%22ay%08b%3C%40%C3%92%3B%C2%9AT%C3%82%C2%B4%C2%A2%0A%C3%BE%C3%A7%C2%87%01%22%5Cb%29rR3J&test_suite=1&test_suite_input=True%0AFalse%0ATrue.%0AFalse.%0AYes%0ANo%0AYes.%0ANo.%0Ayes%0Ano%0Ayes.%0Ano.%0A0%0A1%0AYeah%0ANope%0Ayeah%0Anope%0AYeah.%0ANope.%0Ayeah.%0Anope.&debug=0) [Answer] # TI-Basic, 217 bytes Longer than I thought it would be... ``` Input Str1 If Str1="0 Then Disp 1 Stop End "e"=sub(Str1,2,1 sub("FalsefalseNopenope",1+5not(Ans)(sub(Str1,1,1)="t")+10Ans+4Ans(sub(Str1,1,1)="y"),5-Ans-2(sub(Str1,3,1)="s"))+sub(" .",1+(sub(Str1,length(Str1),1)="."),1 ``` [Answer] # Python 3, 227 bytes ``` def f(x):l=["True","False","True.","False.","true","false","true.","false.","Yes","No","yes","no","Yes.","No.","yes.","no.","0","1","Yeah","Nope","Yeah.","Nope.","yeah","nope","yeah.","nope."];r=l.index(x);return l[r+1-2*(r%2)] ``` Ungolfed form: ``` def f(x): l=["True","False","True.","False.","true","false","true.","false.","Yes","No","yes","no","Yes.","No.","yes.","no.","0","1","Yeah","Nope","Yeah.","Nope.","yeah","nope","yeah.","nope."] r=l.index(x) return l[r + 1 -2*(r % 2)] ``` [Answer] ## Pyke, ~~51~~ 44 bytes ``` .d̾ॗǣ/ற㻯dc2cDMl4+D.F\.+)+T`]1+Dm_+Y@ ``` [Try it here!](http://pyke.catbus.co.uk/?code=.d%06%CC%BE%E0%A5%97%C7%A3%2F%E0%AE%B1%E3%BB%AFdc2cDMl4%2BD.F%5C.%2B%29%2BT%60%5D1%2BDm_%2BY%40&input=%22yes%22) ``` .d̾ॗǣ/ற㻯dc2c - {'yeah': 'nope', 'true': 'false', 'yes': 'no'} DMl4+ - ^ += map(^, str.title()) D.F\.+)+ - ^ += map(^+".") T`]1+ - ^ += [repr(10)] Dm_+ - ^ += map(^, reversed) Y@ - dict(^)[input] ``` [Answer] # [Perl 6](http://perl6.org), ~~86~~ 81 bytes ``` ~~{my@a=<true yes yeah 1 0 nope no false>;my%h=@a Z=> reverse @a;S:ii/(@a)/{%h{lc $0}}/}~~ {my@a=<true yes yeah 1 0 nope no false>;S:ii/(@a)/{%(@a Z=> reverse @a){lc $0}}/} ``` ### Explanation: ``` { # list of responses ordered in such a way that # reversing it will give you the opposite response my @a = <true yes yeah 1 0 nope no false>; # create a lookup table my %h = @a Z=> reverse @a; # the :samecase / :ii modifier causes the regex to call .samecase # on the replacement, and also turns on :ignorecase / :i S:samecase / (@a) # match against the values in @a /{ %h{lc $0} }/ } ``` ### Test: ``` #! /usr/bin/env perl6 use v6.c; use Test; my @tests = ( < True False >, < True. False. >, < true false >, < true. false. >, < Yes No >, < Yes. No. >, < yes no >, < yes. no. >, < 0 1 >, < Yeah Nope >, < yeah nope >, < Yeah. Nope. >, < yeah. nope. >, ); plan @tests * 2; my &answer-flip = {my@a=<true yes yeah 1 0 nope no false>;my%h=@a Z=> reverse @a;S:ii/(@a)/{%h{lc $0}}/} for @tests -> ($a,$b) { is answer-flip($a), $b, "$a => $b"; is answer-flip($b), $a, "$b => $a"; } ``` Which prints out `1..26` on a line, followed by 26 lines of `ok ...` messages. [Answer] # Java, 332 274 205 bytes ``` String s(String p){String[]l={"True","true","Yes","yes","Yeah","yeah","0","1","nope","Nope","no","No","false","False"};for(int j=0;j<14;j++)if(p.matches(l[j]+".?"))return p.replace(l[j],l[13-j]);return"";} ``` Gotta love the uncreative Java golf! Credit to @Leaky Nun for helping! [Answer] Python 154 bytes ``` a=['True','True.','true','Yes','Yes.','yes','Yeah','Yeah.','yeah','0','False','False.','false','No','No.','no','Nope','Nope.','nope',1] a[a.index(i)+10] ``` [Answer] # Emacs Lisp 221 Bytes ``` (defun g(a b)(when(string-match a s)(throw s(replace-match b'()'()s)))) (defun f(s)(catch s(dolist(l'(("true"."false")("yeah"."nope")("yes"."no")("0"."1")))(let((a(car l))(d(cdr l))(case-fold-search t))(g a d)(g d a))))) ``` Ungolfed: ``` (defun g (a b) ;; when a is in s (dynamical scope) throws the replacement string (when (string-match a s) (throw s (replace-match b nil nil s)))) (defun f (s) (catch s ; catch replacement (dolist (l'(("true"."false")("yeah"."nope")("yes"."no")("0"."1"))) (let ((a(car l)) (d(cdr l)) ;; Emacs string-match ignores case, when case-fold-search is true. ;; The standard is t, but through customization/local variables ;; this can change. Therefore we set it explicitly. ;; We could have saved 20 bytes here... (case-fold-search t)) (g a d) (g d a))))) ``` The main "feature" here, is that `string-match` can be made to ignore case and that `replace-match` is somewhat intelligent with replacing. For instance, this would also work with TRUE and FALSE. We also exploit dynamical scope to save typing. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 113 bytes ``` $x=($s=(echo True False Yes No 0 1 Yeah Nope)|%{$_;$_|% *wer}|%{$_;"$_."}).indexOf("$args") $s[$x+4-8*($x%8-ge4)] ``` [Try it online!](https://tio.run/##XZFBa4MwFMfv@RQPec6k09BCD2VD2C47dpddxhgi9lkHos5Y5lA/u4upXU1zevnl9/6PJFX5Q7XKKM9HTCGEbsQ25KhCTklWwlt9IniJc0XwTgr2Jaxho8s403VFonc7jB4x6l1Y6aDhvHcwks4g5FdxoPY15Q7G9VE5gqH6wPZ@G@xWHFt3FxxpKz7HgbEnzkAvn3vTRM/3zExPLKm8YHnlzdlObbuZ7fTG1lfQdF9aRBq0sH6NVZQWkQZdrbW/WYTEmQmpaNljYGHByZSzKm1XzvKEmYAeXOjMOTYUJxnVz4XSL@wDUltR0tBB/xZGZ6UmdcobDe70J9oNRnCQz06Q0Pd/gni4tDpsGP8A "PowerShell – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 121 bytes ``` def f(i):a=[(w,w.title())[i<'a']+'.'[i[-1]>'.':]for w in'true yes yeah 1 false no nope 0'.split()];return a[a.index(i)-4] ``` [Try it online!](https://tio.run/##PVBLa8QgEL73V8xNpVnZ0J7Sx7HHnnop4kHYkQhBxcyS5tenvrKg32uG8RF3moN/OY4bWrDcicl8KL4NmyRHC3IhlHtnhulnJply6jLqz6wmbUOCDZxnlO4IO655mxlGsGZZEXzIKyJcmVzj4ogL/ZaQ7smDUUY6f8O/fNrlVR9l0uI85mGgnthPnseGxrII6gGdwS@unardm927HSv0RjO3UuPi5RlU8VUu@xA1smdkH9F3aFiNDw2ruVboTRFbpXHx8gyK0BPE5Dzx8tghf3ZhIY5/ "Python 3 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 32 bytes ``` l'.¡“0žä€¸€¸pe¥æ…܉¦ 1“#‡'.ýs.Ï ``` [Try it online!](https://tio.run/##yy9OTMpM/V9TVmmvpKBrp6BkX1n5P0dd79DCRw1zDI7uO7zkUdOaQzvAREHqoaWHlz1qWHZ4zqOGDYeWKRgC1SgfbnrUsFBd7/DeYr3D/f91/ocUlaZyuSXmFKdygZh6ELYeVwlIPA0sXgIWT4OIR6YWc/nlgyg9IK3HVQnk5@WDKD0grcdlwGUIlEzMAEoWpAKFgaw8EAskpgcW1AOL6oGF9QA "05AB1E – Try It Online") ]
[Question] [ I like to do programming challenges in my free time to teach myself and keep fresh, this one I can't seem to optimize though and it's driving me insane. The goal is essentially, "Given a number, return the numbers leading up to it as a palindrome." For example if you are given the input `5` the answer your program should return is: `123454321` The catch? You have to solve it in as few characters as possible. The minimum needed seems to be 41 characters and I can't condense it past 76. I have tried all sorts of solutions, here are a few: ``` # Note: "Palindromic_Number" is required. "def P(N):" will not work. def Palindromic_Number(N): a = '' for x in range(1,N+1): a += str(x) return a + a[::-1][1:] def Palindromic_Number(N): a = ''.join(map(str, range(1,N+1))) return a + a[::-1][1:] def Palindromic_Number(N): a = ''.join([str(x) for x in range(1, N+1)]) return a + a[::-1][1:] # This one uses Python 2.7 Palindromic_Number = lambda N: ''.join(map(str, range(1,N+1) + range(1,N+1)[::-1][1:])) ``` Does anyone have any ideas as to how I could shorten my code? I'm just looking for a point in the right direction where to look as this point. [Answer] You could try: ``` def Palindromic_Number(N): return int('1'*N)**2 ``` just preforms `11111 * 11111` which equals `123454321` 47 chars. --- Or, as a lambda: ``` Palindromic_Number=lambda N:int('1'*N)**2 ``` 41 chars. [Answer] In the last solution (that takes advantage of Python 2 style ranges) you could reduce this ``` range(1,N+1) + range(1,N+1)[::-1][1:] ``` in a couple of ways: 1. Instead of slicing the second range, create the reversed range directly as `range(N-1,0,-1)` 2. Making `N` come out of the second range allows changing `N+1` and `N-1` to `N` and `N`: ``` range(1,N) + range(N,0,-1) ``` [Answer] # [Python 2](https://docs.python.org/2/), 40 bytes ``` Palindromic_Number=lambda n:(10**n/9)**2 ``` [Try it online!](https://tio.run/nexus/python2#@x@QmJOZl1KUn5uZHO9XmpuUWmSbk5iblJKokGelYWigpZWnb6mppWX0v6AoM69EA1O5hpmm5n8A "Python 2 – TIO Nexus") (Includes test code to actually run the program.) I know that you claimed that 41 is the minimum, but it's actually possible to do it in 40. This uses the same strategy seen in the other answers, of squaring a repunit (a number made out of repetitions of the digit `1`). However, instead of using string operations to produce the repunit (and thus having to pay for `int` to convert string to integer), it generates the palindrome entirely arithmetically. The basic idea here is that 10*n* is a `1` followed by *n* `0`s; if we subtract 1 we therefore get *n* `9`s, and dividing by 9 gives us *n* `1`s. Because Python 2 rounds integer arithmetic downwards, we can omit the subtraction of 1 (as it'll leave the answer higher by ⅑ than it should, which is a fraction that will disappear in the rounding), and we'll still get the correct answer. [Answer] ~~`range` is a rather long name; with `lambda N,r=range:`/`def ...(N,r=range):` you can shave off a few characters if you~~ also remove all unnecessary whitespace. ]
[Question] [ Your task is to create many programs. The first outputs `1`, the second outputs `2`, etc. The higher you can go, the better! However, all of these programs must be made the same list of characters. You can choose which characters to put in the list. Each program can only use a character as many times as it appears in the list. For example, using the Python shell: ``` List of characters: +122 ------- Program 1: 1 Program 2: 2 Program 3: 1+2 Program 4: 2+2 (2 appears twice in the list) ``` It is impossible to make a program which prints `5` without reusing the `+` character, so there are a total of `4` programs possible with this list. (Only consecutive numbers starting from 1 count. We therefore ignore other numbers we can make, like 12.) ## Scoring * Let *N* be the number of programs. * Let *S* be the size of the shortest program, or 15, whichever is less. * Let *L* be the length of the list. Your score is *N* / Γ((*L*-*S*)/5), where Γ is the [gamma function](https://en.wikipedia.org/wiki/Gamma_function). In the example above, *N* is 4; *S* is 1; *L* is 4; the score is [4 / Γ((4-1)/5) = 2.686](http://www.wolframalpha.com/input/?i=4%2Fgamma%28%284-1%29%2F5%29). Highest score wins! Below is a Stack Snippet to help calculate your score: ``` var g=7,C=[0.99999999999980993,676.5203681218851,-1259.1392167224028,771.32342877765313,-176.61502916214059,12.507343278686905,-0.13857109526572012,9.9843695780195716e-6,1.5056327351493116e-7];function gamma(z) {if(z<0.5){return Math.PI/(Math.sin(Math.PI*z)*gamma(1-z));}else{z--;var x=C[0];for(var i=1;i<g+2;i++)x+=C[i]/(z+i);var t=z+g+0.5;return Math.sqrt(2*Math.PI)*Math.pow(t,(z+0.5))*Math.exp(-t)*x;}}function go(){var N=parseInt(jQuery('#programs').val()),S=parseInt(jQuery('#shortest').val()),L=parseInt(jQuery('#length').val());if(S>15){S=15;}jQuery('#score').val(N/gamma((L-S)/5));} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form><table><tr><td><label>Number of programs:</label></td><td><input id='programs' oninput="go()" value='0'/></td></tr><tr><td><label>Size of shortest program:</label></td><td><input id='shortest' oninput="go()" value='0'/></td></tr><tr><td><label>Size of list:</label></td><td><input id='length' oninput="go()" value='0'/></td></tr><tr><td><label>Score:</label></td><td><output id='score'>0</output></td></tr></table></form><p>Code from <a href="http://stackoverflow.com/a/15454784/3148067">http://stackoverflow.com/a/15454784/3148067</a></p> ``` ## Rules * You can use programs or functions. * You may use different languages for different numbers. * Each program must work by itself. For example, you can not assume that the first program will run before the second program. [Answer] # Pyth, Score of 1.664 \* 10^26 Since you only have `L` different chars to choose from, you can maximal generate `O(L!)` different programs. So lets build something really close: By indexing permutations of the alphabet: I use a following list of characters is: ``` abcdefghijklmnoppqrstuvwxxyzG." ``` With these characters I can generate 26!-1 different programs like this: ``` Program 1: x.pG"abcdefghijklmnopqrstuvwxzy Program 2: x.pG"abcdefghijklmnopqrstuvwyxz Program 3: x.pG"abcdefghijklmnopqrstuvwyzx ... Program 403291461126605635583999999: x.pG"zyxwvutsrqponmlkjihgfedcba ``` Notice I didn't use "abcdefghijklmnopqrstuvwxyz" (sorted alphabet), since I give an index of 0. So we got `N = 403291461126605635583999999, S = 15, L = 31`, which gives a score of `1.663767345141228e+26`. ### Explanation: ``` x.pG"... G G is pre-initialized with "abc...xyz" .p gives all possible permutations x "... the index of "..." in the permutation list ``` Notice, that none of the programs will actually run. Because of memory and time. # edit: You can even get way higher. For instance by using also the uppercase letters. Gives me a score of about `10^76`. # edit 2: a runnable version Since none of the programs above is actually runnable, here's one that works. ``` x.pSK""Kabcde ``` The programs are: ``` Program 1: x.pSK"abced"K Program 2: x.pSK"abdce"K Program 3: x.pSK"abdec"K ... Program 117: x.pSK"edbca"K Program 118: x.pSK"edcab"K Program 119: x.pSK"edcba"K ``` Here's an online [Demonstration](https://pyth.herokuapp.com/?code=x.pSK%22abced%22K&debug=0). ### Explanation: ``` x.pSK"abced"K K"abced" K = "abced" S sort it .p generate all permutations of sorted(K) x K index of K in the permutations. ``` `N = 119, S = 13, L = 13` gives a score of 0. But If we simply use a dummy char to the list we get `N = 119, S = 13, L = 14` and a score of 25.92 Of course we can use more chars than `abcde` for the permutation. If we use `n` different chars, we get `N = n!-1, S = 15, L = n+8`, which gives a score of `~n!/(n-7)!`. So we can get pretty much an unlimited score. [Answer] # **TI-84 BASIC, score 107.07** Character list (length 8): `12347+*^` Constructed programs: ``` 1 = 1 2 = 2 3 = 3 4 = 4 5 = 2+3 6 = 2*3 7 = 7 8 = 2^3 9 = 3^2 10 = 7+3 11 = 7+4 12 = 12 13 = 13 14 = 14 15 = 2*7+1 16 = 2^4 17 = 17 18 = 2*7+4 19 = 2^4+3 20 = 14+2*3 21 = 3*7 22 = 3*7+1 23 = 23 24 = 24 25 = 24+1 26 = 2*13 27 = 27 28 = 4*7 29 = 1+4*7 30 = 2+4*7 31 = 31 32 = 32 33 = 32+1 34 = 34 35 = 34+1 36 = 34+2 37 = 37 38 = 37+1 39 = 37+2 40 = 12+4*7 41 = 41 42 = 42 43 = 43 44 = 43+1 45 = 43+2 46 = 32+14 47 = 47 48 = 47+1 49 = 7^2 50 = 7^2+1 51 = 3*17 52 = 4*13 53 = 3*17+2 54 = 4*13+2 55 = 3*17+4 56 = 7*2^3 57 = 7*2^3+1 58 = 37+21 59 = 42+17 60 = 43+17 61 = 37+24 62 = 31*2 63 = 7*3^2 64 = 4^3 65 = 4^3+1 66 = 4^3+2 67 = 7*3^2+4 68 = 4*17 69 = 27+14*3 70 = 43+27 71 = 71 72 = 72 73 = 73 74 = 74 75 = 74+1 76 = 74+2 77 = 74+3 78 = 2*37+4 79 = 47+32 80 = 7^2+31 81 = 3^4 82 = 3^4+1 83 = 3^4+2 84 = 7*12 85 = 4^3+21 86 = 2*43 87 = 7*12+3 88 = 7*12+4 89 = 73+2^4 90 = 7^2+41 91 = 7*13 92 = 7^2+43 93 = 7*13+2 94 = 2*47 95 = 7*13+4 ``` [Answer] # CJam, 101023.64023653832850 > 10 400 000 000 000 000 000 000 000 ### Characters Each program consists of **9 + 63 486 × 1020** characters: * `""_e!\a#)` * **1020** copies of all Unicode characters in the range **0** – **65 535**, except `"\` and surrogates. ### Programs The structure of each program is: ``` "…"_e!\a#) ``` where `…` denotes a permutation of all **63 486** aforementioned Unicode characters. `_e!` computes all possible permutations of the characters in sorted order. `\a#` computes the index of the original permutation in the list of all of them. `)` adds **1** to that index to generate only positive integers. ### Scoring If the **1020** copies of each of the **63 486** characters were somehow different, there would be a total of **(63 486 × 1020)!** different ways to arrange them. However, for each of the **63 486** characters, this generates **1020!** identical permutations, since this is the number of ways the copy of this single character can be arranged. Therefore, the number of different permutations is **(63 486 × 1020)! / (1020!)63 486**. Plugging this number and the character count into [WolframAlpha](http://www.wolframalpha.com/input/?i=%28%2863486*10%5E20%29%21%2F%28%2810%5E20%29%21%5E63486%29%29%2Fgamma%28%289%2B63486*10%5E20-15%29%2F5%29) reveals the score from the top. ### Bonus Of course, enumerating all possible permutations isn't very efficient and even storing **6 × 1024** characters isn't possible on my computer. Using the [online interpreter](http://cjam.aditsu.net/ "CJam interpreter") and more efficient code, I can permute one copy of **1 000** characters in a few seconds for a score of [**3 × 102 189**](http://www.wolframalpha.com/input/?i=1000%21%2Fgamma%28%281027-15%29%2F5%29%3D). The highest number it produces is generated by the following code: ``` "㢣㢢㢡㢠㢟㢞㢝㢜㢛㢚㢙㢘㢗㢖㢕㢔㢓㢒㢑㢐㢏㢎㢍㢌㢋㢊㢉㢈㢇㢆㢅㢄㢃㢂㢁㢀㡿㡾㡽㡼㡻㡺㡹㡸㡷㡶㡵㡴㡳㡲㡱㡰㡯㡮㡭㡬㡫㡪㡩㡨㡧㡦㡥㡤㡣㡢㡡㡠㡟㡞㡝㡜㡛㡚㡙㡘㡗㡖㡕㡔㡓㡒㡑㡐㡏㡎㡍㡌㡋㡊㡉㡈㡇㡆㡅㡄㡃㡂㡁㡀㠿㠾㠽㠼㠻㠺㠹㠸㠷㠶㠵㠴㠳㠲㠱㠰㠯㠮㠭㠬㠫㠪㠩㠨㠧㠦㠥㠤㠣㠢㠡㠠㠟㠞㠝㠜㠛㠚㠙㠘㠗㠖㠕㠔㠓㠒㠑㠐㠏㠎㠍㠌㠋㠊㠉㠈㠇㠆㠅㠄㠃㠂㠁㠀㟿㟾㟽㟼㟻㟺㟹㟸㟷㟶㟵㟴㟳㟲㟱㟰㟯㟮㟭㟬㟫㟪㟩㟨㟧㟦㟥㟤㟣㟢㟡㟠㟟㟞㟝㟜㟛㟚㟙㟘㟗㟖㟕㟔㟓㟒㟑㟐㟏㟎㟍㟌㟋㟊㟉㟈㟇㟆㟅㟄㟃㟂㟁㟀㞿㞾㞽㞼㞻㞺㞹㞸㞷㞶㞵㞴㞳㞲㞱㞰㞯㞮㞭㞬㞫㞪㞩㞨㞧㞦㞥㞤㞣㞢㞡㞠㞟㞞㞝㞜㞛㞚㞙㞘㞗㞖㞕㞔㞓㞒㞑㞐㞏㞎㞍㞌㞋㞊㞉㞈㞇㞆㞅㞄㞃㞂㞁㞀㝿㝾㝽㝼㝻㝺㝹㝸㝷㝶㝵㝴㝳㝲㝱㝰㝯㝮㝭㝬㝫㝪㝩㝨㝧㝦㝥㝤㝣㝢㝡㝠㝟㝞㝝㝜㝛㝚㝙㝘㝗㝖㝕㝔㝓㝒㝑㝐㝏㝎㝍㝌㝋㝊㝉㝈㝇㝆㝅㝄㝃㝂㝁㝀㜿㜾㜽㜼㜻㜺㜹㜸㜷㜶㜵㜴㜳㜲㜱㜰㜯㜮㜭㜬㜫㜪㜩㜨㜧㜦㜥㜤㜣㜢㜡㜠㜟㜞㜝㜜㜛㜚㜙㜘㜗㜖㜕㜔㜓㜒㜑㜐㜏㜎㜍㜌㜋㜊㜉㜈㜇㜆㜅㜄㜃㜂㜁㜀㛿㛾㛽㛼㛻㛺㛹㛸㛷㛶㛵㛴㛳㛲㛱㛰㛯㛮㛭㛬㛫㛪㛩㛨㛧㛦㛥㛤㛣㛢㛡㛠㛟㛞㛝㛜㛛㛚㛙㛘㛗㛖㛕㛔㛓㛒㛑㛐㛏㛎㛍㛌㛋㛊㛉㛈㛇㛆㛅㛄㛃㛂㛁㛀㚿㚾㚽㚼㚻㚺㚹㚸㚷㚶㚵㚴㚳㚲㚱㚰㚯㚮㚭㚬㚫㚪㚩㚨㚧㚦㚥㚤㚣㚢㚡㚠㚟㚞㚝㚜㚛㚚㚙㚘㚗㚖㚕㚔㚓㚒㚑㚐㚏㚎㚍㚌㚋㚊㚉㚈㚇㚆㚅㚄㚃㚂㚁㚀㙿㙾㙽㙼㙻㙺㙹㙸㙷㙶㙵㙴㙳㙲㙱㙰㙯㙮㙭㙬㙫㙪㙩㙨㙧㙦㙥㙤㙣㙢㙡㙠㙟㙞㙝㙜㙛㙚㙙㙘㙗㙖㙕㙔㙓㙒㙑㙐㙏㙎㙍㙌㙋㙊㙉㙈㙇㙆㙅㙄㙃㙂㙁㙀㘿㘾㘽㘼㘻㘺㘹㘸㘷㘶㘵㘴㘳㘲㘱㘰㘯㘮㘭㘬㘫㘪㘩㘨㘧㘦㘥㘤㘣㘢㘡㘠㘟㘞㘝㘜㘛㘚㘙㘘㘗㘖㘕㘔㘓㘒㘑㘐㘏㘎㘍㘌㘋㘊㘉㘈㘇㘆㘅㘄㘃㘂㘁㘀㗿㗾㗽㗼㗻㗺㗹㗸㗷㗶㗵㗴㗳㗲㗱㗰㗯㗮㗭㗬㗫㗪㗩㗨㗧㗦㗥㗤㗣㗢㗡㗠㗟㗞㗝㗜㗛㗚㗙㗘㗗㗖㗕㗔㗓㗒㗑㗐㗏㗎㗍㗌㗋㗊㗉㗈㗇㗆㗅㗄㗃㗂㗁㗀㖿㖾㖽㖼㖻㖺㖹㖸㖷㖶㖵㖴㖳㖲㖱㖰㖯㖮㖭㖬㖫㖪㖩㖨㖧㖦㖥㖤㖣㖢㖡㖠㖟㖞㖝㖜㖛㖚㖙㖘㖗㖖㖕㖔㖓㖒㖑㖐㖏㖎㖍㖌㖋㖊㖉㖈㖇㖆㖅㖄㖃㖂㖁㖀㕿㕾㕽㕼㕻㕺㕹㕸㕷㕶㕵㕴㕳㕲㕱㕰㕯㕮㕭㕬㕫㕪㕩㕨㕧㕦㕥㕤㕣㕢㕡㕠㕟㕞㕝㕜㕛㕚㕙㕘㕗㕖㕕㕔㕓㕒㕑㕐㕏㕎㕍㕌㕋㕊㕉㕈㕇㕆㕅㕄㕃㕂㕁㕀㔿㔾㔽㔼㔻㔺㔹㔸㔷㔶㔵㔴㔳㔲㔱㔰㔯㔮㔭㔬㔫㔪㔩㔨㔧㔦㔥㔤㔣㔢㔡㔠㔟㔞㔝㔜㔛㔚㔙㔘㔗㔖㔕㔔㔓㔒㔑㔐㔏㔎㔍㔌㔋㔊㔉㔈㔇㔆㔅㔄㔃㔂㔁㔀㓿㓾㓽㓼㓻㓺㓹㓸㓷㓶㓵㓴㓳㓲㓱㓰㓯㓮㓭㓬㓫㓪㓩㓨㓧㓦㓥㓤㓣㓢㓡㓠㓟㓞㓝㓜㓛㓚㓙㓘㓗㓖㓕㓔㓓㓒㓑㓐㓏㓎㓍㓌㓋㓊㓉㓈㓇㓆㓅㓄㓃㓂㓁㓀㒿㒾㒽㒼"_${\(_3$#2$,m!*X+:X;@^}hX ``` Copying and pasting the code from above should work just fine. Using the Java interpreter, I can use one copy of all **63 486** characters and execute the code in under five and a half hours: ``` $ cjam <(echo '65536,2048,55296f+-:c"\"\\"-W%`"_${\(_3$#2$,m!*X+:X;@^}hX"') > test.cjam $ $ time test.cjam > /dev/null real 324m36.040s user 331m55.488s sys 0m54.971s ``` This method achieves a score of [**7.6 × 10230 732**](http://www.wolframalpha.com/input/?i=63486%21%2Fgamma%28%2863515-15%29%2F5%29%3D). [Answer] (redone as previous was loophole - sorry about that). (edited to fix score: N=8, due to gaps - forgot about that) **Unix/Korn Shell** (Score: 9.016) (going a very simple method, just trying to maximize the Gamma function) List is: (L=13) ``` echo 12345678 ``` 8 Programs: ``` echo 1 echo 2 ... echo 8 ``` so: ``` N=8 S=6 L=13 ``` Hopefully no loopholes this time around - I just crunched the formula and figured out where to maximize it. For my method, it maximized at S=6 and L=13. :) Wolfram Alpha tells me: ``` 8 / Γ((13-6)/5) = 9.016 ``` ]
[Question] [ Consider the set of 16-character strings containing only the [95 printable ASCII characters](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters). There are 9516 ≈ [4.4×1031](http://www.wolframalpha.com/input/?i=95%5E16) such strings. Imagine these strings are put into a list and sorted [lexicographically](http://en.wikipedia.org/wiki/Lexicographical_order) (which is the way most languages will sort a list of strings). What is the largest **contiguous** slice of this list you can find such that every string is a valid program in your programming language of choice whose output is the sole word `string`? All output should go to the same place for all programs; use stdout or a similar alternative. An optional trailing newline may be a part of the output, but otherwise nothing besides `string` should be printed for any of your 16-character programs. There is no input and all programs should run without erroring. The program **does not** have to terminate. The list of length 16 strings does not "loop-around" from `~~~~~~~~~~~~~~~~` to (16 spaces). Give your starting string and ending string and explain why every program-string that's in between them lexicographically outputs `string`. The submission with the largest slice wins. [Answer] # [///](http://esolangs.org/wiki////), 6634204313747905 > 958 From ``` string/.~~~~~/0 ``` to ``` string/0 /.~ ``` This relies on the program not being required to terminate. I started from a core-range of 958 much like the other solutions, from ``` string// ``` to ``` string//~~~~~~~~ ``` However, in this case, `//` is not a comment. In **///** everything that's not a slash is just printed (hence this always prints `string` before doing anything else). A slash then starts a substitution pattern of the form `/pattern/replacement/`. If only one or two `/` are found, then the program simply terminates. However, the above range obviously also includes strings with three or more slashes. The trick here is that the pattern to be searched for is empty, and substitutions are performed iteratively until the pattern cannot be found any more. Since the empty string can *always* be found, this substitution never terminates, and hence the program never gets around to print anything after the initial `string`. But since this doesn't rely on `//` being a comment, we can actually go a bit further! E.g. the previous and next string around this range, respectively, are: ``` string/.~~~~~~~~ string/0 ``` These still don't contain a full substitution instruction so they also only print `string` and then terminate. Let's see how far we can go! I'll focus on the upper end of the range (the lower end works analogously). What if we get another `/`? The first time this happens is ``` string/0 / ``` But that's still not a valid replacement pattern, so all is well. It looks like we need three slashes to break the magic. The first time we get three slashes is at ``` string/0 // ``` What now? Well, the pattern to be searched for is `0` (and a bunch of spaces), to be replaced with an empty string. That pattern is never found, so the substitution completes immediately. But luckily, there is nothing to print *afterwards* in the source code, so the result is *still* only `string`. Neat. :) So we need a valid substitution instruction *and* more source code afterwards to not print `string`: ``` string/0 // ``` And this is indeed the first code that doesn't work to spec, as it prints `string` followed by a space. So the last code that works is ``` string/0 /.~ ``` We can apply the same argument to the beginning of the range, the last failing code being ``` string/.~~~~~//~ ``` such that the first code that works is ``` string/.~~~~~/0 ``` [Answer] # [pyexpander](http://pyexpander.sourceforge.net/): 95^8 = 6634204312890625 ``` string$# ``` to ``` string$#~~~~~~~~ ``` Wow, it took forever to find the language I was looking for: one that outputs most source literals untouched and has a rest-of-line comment delimiter. This is still not theoretically optimal, as it's possible that another language like this exists, but with a one-character comment delimiter. However, I couldn't find one. [Answer] ## GolfScript: 95^7 = 69833729609375 ``` "string"# ``` to ``` "string"#~~~~~~~ ``` Everything from the `#` is a comment; the literal string is echoed at the end of execution. [Answer] # PHP, 95^7 = 69833729609375 ``` string<?# ``` followed by arbitrary characters. [Answer] # Microscript, 95^6=735091890625 `"gnirts"ah` (padded to 16 chars with trailing spaces) through `"gnirts"ah~~~~~~` [Answer] ## Windows Powershell: 95^7 = 69833729609375 ``` "string"# ``` to ``` "string"#~~~~~~~ ``` All characters from the # and following are part of a comment. Same as @PeterTaylor's GolfScript answer ]
[Question] [ Your program or function should output all the [36 4-perfect numbers](http://oeis.org/A027687/b027687.txt) in increasing order separated by newlines. An `n` positive integer is a `k`-perfect number ([multiply perfect number](http://en.wikipedia.org/wiki/Multiply_perfect_number)) if the sum of its divisors including itself (i.e. the [sigma function](http://en.wikipedia.org/wiki/Divisor_function) of `n`) equals `k*n`. For example `120` is a `3`-perfect number because `1 + 2 + 3 + 4 + 5 + 6 + 8 + 10 + 12 + 15 + 20 + 24 + 30 + 40 + 60 + 120 = 360 = 3*120`. ### Details * Your entry should actually produce the output and terminate on your machine before you submit your answer. (i.e. the program should terminate in a reasonable time) * Hardcoding is allowed. * Built-in functions or data closely related to the problem (e.g. sigma function) are disallowed. * This is code-golf but as the task is non-trivial without major hardcoding non-golfed entries are welcomed too. ([This](http://wwwhomes.uni-bielefeld.de/achim/mpn.html) is a great detailed page about the history of all multiply perfect numbers.) [Answer] # Prime factorization (Ruby ,~~570~~ 542 bytes) **Rev 0** Below is a table of the prime factorizations of the 36 required numbers (copied from Wolfram, hopefully with no errors.) Only 31 prime factors are involved if I have counted correctly, and some of these always occur together, for example 137\*547\*1093 and 683\*2731\*8191. It should be possible to condense the information in the table, or perhaps even employ a search strategy. This should beat simply compressing the numbers. Unfortunately the numbers are too big even for a 128-bit integer, which means I can't use C. Ruby and Python do support arbitrary precision integers. I have put the table in valid Ruby syntax, which makes it my first ever Ruby program! ``` puts 2**5 *3**3 *5 *7 puts 2**3 *3**2 *5 *7 *13 puts 2**2 *3**2 *5 *7**2 *13 *19 puts 2**9 *3**3 *5 *11 *31 puts 2**7 *3**3 *5**2 *17 *31 puts 2**9 *3**2 *7 *11 *13 *31 puts 2**8 *3 *5 *7 *19 *37 *73 puts 2**10 *3**3 *5**2 *23 *31 *89 puts 2**13 *3**3 *5 *11 *43 *127 puts 2**14 *3 *5 *7 *19 *31 *151 puts 2**13 *3**2 *7 *11 *13 *43 *127 puts 2**5 *3**4 *7**2 *11**2 *19**2 *127 puts 2**8 *3**2 *7**2 *13 *19**2 *37 *73 *127 puts 2**7 *3**10 *5 *17 *23 *107 *3851 puts 2**7 *3**6 *5 *17 *23 *137 *547 *1093 puts 2**14 *3**2 *7**2 *13 *19**2 *31 *127 *151 puts 2**5 *3**4 *7**2 *11**2 *19**4 *151 *911 puts 2**9 *3**4 *7 *11**3 *31**2 *61 *83 *331 puts 2**8 *3**2 *7**2 *13 *19**4 *37 *73 *151 *911 puts 2**25 *3**3 *5**2 *19 *31 *683 *2731 *8191 puts 2**17 *3**10 *7 *19**2 *23 *37 *73 *107 *127 *3851 puts 2**17 *3**6 *7 *19**2 *23 *37 *73 *127 *137 *547 *1093 puts 2**25 *3**4 *7 *11**2 *19**2 *127 *683 *2731 *8191 puts 2**25 *3**5 *7**2 *13 *19**2 *127 *683 *2731 *8191 puts 2**17 *3**10 *7 *19**4 *23 *37 *73 *107 *151 *911 *3851 puts 2**25 *3**10 *5 *19 *23 *107 *683 *2731 *3851 *8191 puts 2**17 *3**6 *7 *19**4 *23 *37 *73 *137 *151 *547 *911 *1093 puts 2**25 *3**6 *5 *19 *23 *137 *547 *683 *1093 *2731 *8191 puts 2**25 *3**4 *7 *11**2 *19**4 *151 *683 *911 *2731 *8191 puts 2**25 *3**5 *7**2 *13 *19**4 *151 *683 *911 *2731 *8191 puts 2**33 *3**4 *7 *11**3 *31 *61 *83 *331 *43691 *131071 puts 2**33 *3**10 *7 *11 *23 *83 *107 *331 *3851 *43691 *131071 puts 2**33 *3**6 *7 *11 *23 *83 *137 *331 *547 *1093 *43691 *131071 puts 2**37 *3**4 *7 *11**3 *31 *61 *83 *331 *43691 *174763*524287 puts 2**37 *3**10 *7 *11 *23 *83 *107 *331 *3851 *43691 *174763*524287 puts 2**37 *3**6 *7 *11 *23 *83 *137 *331 *547 *1093 *43691 *174763*524287 ``` **Rev 1** Just starting to gather some terms. ``` #683*2731*8191=15278451143, 137*547*1093=81908327, 107*3851=412057, 174763*524287=91625968981, 19**2*151*911=49659521, 83*331=27473, 11**3*31*61=2516921,37*73=2701,19*19=361 puts 2**5 *3**3 *5 *7 puts 2**3 *3**2 *5 *7 *13 puts 2**2 *3**2 *5 *7**2 *13 *19 puts 2**9 *3**3 *5 *11 *31 puts 2**7 *3**3 *5**2 *17 *31 puts 2**9 *3**2 *7 *11 *13 *31 puts 2**8 *3 *5 *7 *19 *2701 puts 2**10 *3**3 *5**2 *23 *31 *89 puts 2**13 *3**3 *5 *11 *43 *127 puts 2**14 *3 *5 *7 *19 *31 *151 puts 2**13 *3**2 *7 *11 *13 *43 *127 puts 2**5 *3**4 *7**2 *11**2 *19**2 *127 puts 2**8 *3**2 *7**2 *13 *19**2 *2701 *127 puts 2**7 *3**10 *5 *17 *23 *412057 puts 2**7 *3**6 *5 *17 *23 *81908327 puts 2**14 *3**2 *7**2 *13 *19**2 *31 *127 *151 puts 2**5 *3**4 *7**2 *11**2 *19**2 *49659521 puts 2**9 *3**4 *7 *31 *2516921 *27473 puts 2**8 *3**2 *7**2 *13 *19**2 *2701 *49659521 puts 2**25 *3**3 *5**2 *19 *31 *15278451143 puts 2**17 *3**10 *7 *19**2 *23 *2701 *127 *412057 puts 2**17 *3**6 *7 *19**2 *23 *2701 *127 *81908327 puts 2**25 *3**4 *7 *11**2 *19**2 *127 *15278451143 puts 2**25 *3**5 *7**2 *13 *19**2 *127 *15278451143 puts 2**17 *3**10 *7 *19**2 *23 *2701 *49659521 *412057 puts 2**25 *3**10 *5 *19 *23 *412057 *15278451143 puts 2**17 *3**6 *7 *19**2 *23 *2701 *49659521 *81908327 puts 2**25 *3**6 *5 *19 *23 *81908327 *15278451143 puts 2**25 *3**4 *7 *11**2 *19**2 *49659521 *15278451143 puts 2**25 *3**5 *7**2 *13 *19**2 *49659521 *15278451143 puts 2**33 *3**4 *7 *2516921 *27473 *43691 *131071 puts 2**33 *3**10 *7 *11 *23 *27473 *412057 *43691 *131071 puts 2**33 *3**6 *7 *11 *23 *27473 *81908327 *43691 *131071 puts 2**37 *3**4 *7 *2516921 *27473 *43691 *91625968981 puts 2**37 *3**10 *7 *11 *23 *27473 *412057 *43691 *91625968981 puts 2**37 *3**6 *7 *11 *23 *27473 *81908327 *43691 *91625968981 ``` **Rev 2, ~~570~~ 542 bytes (thanks to Martin for the improvement)** As this is my first Ruby program, I just stuck with the simple approach of continuing to gather terms. Compression of the numbers would be great if anyone knows how to do that. I could save a few more bytes by evaluating some of the literal-only expressions in the variable assignment part, but I decided to leave them for clarity. ``` e=361 f=e*e*137561 g=27473 h=2516921 j=2701 k=81908327*729 m=412057*59049 n=15278451143*2**25 p=g*43691*2**33*7 q=131071 r=91625968981*16 s=127 t=1024 w=250240 x=1467648 y=7439488 puts [30240,32760,2178540,23569920,45532800,142990848,510720*j,t*42833475,t*510840*s,t*149417520,t*3099096*s,15367968*e*s,x*e*j*s,w*m,w*k,t*429378768*e*s,15367968*f,8999424*g*h,x*j*f,n*397575,t*m*y*j*s,t*k*y*j*s,n*68607*e*s,n*154791*e*s,t*20608*j*f*m,2185*n*m,t*20608*j*f*k,2185*k*n,68607*f*n,154791*f*n,81*h*p*q,253*p*m*q,253*p*k*q,81*h*p*r,253*p*m*r,253*p*k*r] ``` [Answer] # CJam, 377 bytes All the characters are part of extended ASCII, so I'm counting this as a single byte per character ``` "Ò|+^ø¥©~öôxõÕÊïB.X}Ã+ç âà©¥;ØÓé@ä¦qØH®üzGOwCàæ/Â$ªh#þ>üJNDÂTR{^Ìý±OáÉÚ6ï®I?Çvqf³e1é^¶­[Y½5ãþ#_-__xF'IMØ*¬È6Vô+§mâ?µTJÉ9$·Ùöµ¨±Dac&¼'h,q÷ZwÎE^§Å{åÁûà\µ;óÛ¤{n'ÜGÐÓR!³¥èè>(~\"NbU*ötmù¦ªUe|Rñ¾!a9TYÇ&êë½ôâ··¨JÆ­#Ù&îCÎÍð4q<­ÌÏïj;Åd*òz(x ?ßâ%d8ƬÔUÎ=¶îÖÀ+mHH9â\"=PʱedèËU· /þr<ÆGR;|úÀè¶¡õrì@öÆ"255bBbAa/N* ``` I'm sure Stack Exchange will have swallowed some of the characters, so you might want to copy the code [from this pastebin](http://pastebin.com/6zHXexdT). [Test it here.](http://cjam.aditsu.net/) This solution is purely hardcoded. It interprets the code points of the characters as the digits of a base-255 number, gets the base-11 digits of that, splits on the digit `10` and joins the resulting arrays by newlines. [Answer] # JavaScript, 572 (?) bytes ``` _=>`@r>=V6R=bWn3s*Ch=%{Fg>QNM' |c6SMH>wF=* IElopM2Mw=?-,Knb7bW{\\=\rH3j=N9.3l*jm6Y(.wJP| tFR7vmvt/))*D.F) . n}Hk18KTn0a{E6 w1z0]\\o.jV"ytga25d+~VNP{0v:zq[d) |.]d,t6P5:;:*?9m[8sI>\\R"' wG*<#[^L/HFzAISvBDnmuy;+JNQj_n{[*d6D H#Ht sLt}\`T+DX3T6/17 guv,\\d8G!\\9;Wug[78\\Iw]5" r!~ZqN96Y\\99-g CoT_w.3SHF:p||;j*uwm+ 1mSXJ<bE1UT]\r:(QEJ3LGPM$8Le3WXCoU;3*jW.7:"5m7f"0S3k9Eko`.replace(/./gs,p=>p.charCodeAt().toString(2).padStart(7,0).slice(-7)).replace(/00|01.|1...|111$/g,d=>`0 12 3456789 `[parseInt(d,2)]) ``` Potentially slightly more than 572, but without TIO I'm not sure if a different interpreter I used is counting a few `0x80` bytes (two bytes in UTF-8) correctly. **Explanation:** Uses huffman coding, where between two and four bits map to each digit: ``` 0 00 1 010 2 011 3 1000 4 1001 5 1010 6 1011 7 1100 8 1101 9 1110 \n 1111 or 111 ``` Each character is ASCII, so I get seven bits per byte. Some, like ``` and `\` need two bytes, and `\0` (null) is represented with `0x80`. [Answer] # Deadfish~, 3758 bytes ``` {iiiii}icdddciiciicddddc{dddd}iic{iiii}icdciiiiicdcddddddc{dddd}iic{iiii}cdciiiiiicicdddcdcddddc{dddd}iic{iiii}ciciiciciiicc{d}iiicddc{dddd}iic{iiii}iiciccddcdciiiiiic{d}iicc{dddd}iic{iiii}dciiicddc{i}dddcc{d}ic{i}ddcddddciiiic{dddd}ddddddc{iiii}dciiciiiiciicdddddcicdciiicdddddcddc{dddd}iic{iiii}iicdciiiiicddcdddddciiiciiicicddddcddddcc{dddd}iic{iiii}iiiiccddcdcciiiicdddddcddciiicdcddc{dddd}iic{iiii}dciiiicddcdddcciiiciicdcddddciiiiciiiic{d}iic{dddd}iic{iiii}iicddddciiicdddciiicddciciciiiccddddddc{i}ddc{dddd}ddddddc{iiii}iiiiic{d}iiiciiiiciciicddcdddcciiiiiiccicdddc{dddd}ddddc{iiii}dc{i}dddc{d}iiiciiiiiicdddcddciiiiiiccdddddciciiciiic{d}iciiiiicic{dddd}ddddc{iiii}iiiicddddddc{i}ddccdcdddddciiiiiic{d}iiciicdcciiiiicddddddciiicdcddc{dddd}iic{iiii}dciiiciiiiicdddddcddcdcicicdciiiiicdccddcdddc{i}ddc{d}iiicddc{dddd}iic{iiii}cddciciiiiciiic{d}iiic{i}dddcdddciiicdddciicddcddcddc{i}ddc{d}iciiiic{dddd}ddc{iiii}ciiiiicddccdddddciic{i}dddc{d}icciiiiiciiiicdddddcddddciicdciiicddddc{i}ddc{dddd}ddddddc{iiii}iiiicddddccciiiiiicddcdcdddddciiiiiiciic{d}iiicciiiicddddciiiicddciiiiiic{d}iiic{dddd}c{iiii}iiiiicddddddcdciiiiiicdcdddddc{i}dddcddcddddcdciiiicdddc{i}ddc{d}icc{i}dddcddddcdddc{i}ddcc{dddd}ddddddc{iiii}cddciiiciiiiicddddddcddc{i}dddc{d}iiiccc{i}ddcdddddciiicdddcicddciiicdciicddcdcdcddcc{dddd}iic{iiii}iiiicdddciiciiicdddddcdddciicddciciiiiicccddddddciic{i}dddcdddddcdcddc{i}ddcdcdcicicdddcdddcdc{dddd}c{iiii}dciiiicicddddddciiiciiicicdddciiiicicdddddcciiicddddciiiiiic{d}iciciiiiiicdddciciiiic{d}iicdciiiiiciiciic{d}iiic{dddd}c{iiii}dciiiiicdddddciciiicddcdciiiiiicddcddddddcc{i}dcddciicddddddcdciiiiciicddddddciciiiiicddcicddddciicddddcdciiiic{dddd}ddc{iiii}iciiicdddciiiiic{d}iiic{i}ddcddddddciiiiiicddcddddciiicddddddc{i}dcddddddciiiiicdddcddcdddc{i}ddc{d}iiic{i}ddcdddddciiiicddcdcddddciiiicdddc{dddd}c{iiii}ciiciiiicddcddddcccicdddciiiccddciciiciiicdddcddc{i}dddcdddcddcdddcccdciiicdddc{i}dddcdddciiicddddddciiciiic{dddd}ddddc{iiii}ciiiiicdddddciiiccdddciiiiicddddddcdc{i}dcdccicdddddcdciiicicdcicddddcciiiiicicddddcdddddcciiiccicddddc{i}ddc{d}iic{dddd}iic{iiii}iiiicdddddcdciciiciciiccddddcciiiiiicddddddc{i}dddc{d}iicic{i}dddccdc{d}iiic{i}ddc{d}iiciicdciiicdddciiicddciciiciic{d}iiiciiiiic{dddd}ddddc{iiii}iiiicciiccddcdddddciiiiciicddddciiiiicdddcdddddciiicdddciiiiiicddcddddcciiiciiiiiic{d}iicdc{i}dcddddddcdddc{i}dddciic{d}iiiciicciiiic{d}iic{dddd}iic{iiii}iiiicdddcdddciiiiicddcdciciiciiccddddddcdciiiicddcddcc{i}dddciicddddcdddddc{i}ddcddddcddciiiiiicdddddciiicddddciciicdddddciiiiiciiiic{d}iiic{dddd}c{iiii}dciiicddcciiiicddddddciiiiiicddddddciiiiiicdddcdciiiicddcddddcciiiiicicdddcciiiiiicddddddcdcciciiiiiic{d}iic{i}ddcddcc{d}iiiccc{i}dcdddc{dddd}ddddc{iiii}dc{i}ddc{d}iiiciiiiiicddcddddccicdddcciiciciiicdddcddc{i}dddc{d}iiciiiiciiiiicc{d}iiiciiiiiicddddddciiiciiic{d}iiiciiccddciiiiicddcddddciiicdc{dddd}c{iiii}iiiciiicddddddciciciiiicddddciiiciic{d}iicciiiiciiicdddciicdddcdciiicdddciiiiiic{d}iic{i}ddc{d}iicciiiicdddddciiciiiciiicdciic{d}iic{i}ddc{d}ic{i}dddcddddcdciiiiiic{dddd}ddddddc{iiii}dciiicddc{i}dddc{d}iicc{i}ddccdddcdddcdddc{i}dcddciicdddddciiicddddcciiiiciicdddcdddcdc{i}dddc{d}iiic{i}dddc{d}ic{i}dcddciicdddddciiciic{d}iiicciiiiciiiicdddciic{dddd}ddddddc{iiii}cdciiiiciicddddddciiicdciiiiiicdcdddcdddciiiicddddddcicciiciiiiiicdddddcddciiiicic{d}iiic{i}dddciic{d}iciiiiicdddddciiiiiciicdddddcdciiiiicdddddciiicddciiicdddddc{i}ddc{d}iiciiicdc{dddd}c{iiii}iiiicdcddddciiciicdddddc{i}dddcddddddciiiiiicddcdddddciiciicciiiccddddciiiiiic{d}iiiciiiiiic{d}iiicdcicicdciiicddddciicicicccdddcciiiiiicddddddciiciiiiciicdddciicdddddccdciiiiiic{dddd}ddddddc{iiii}dciiiiciiiicdcddddcicciiic{d}iiiciiiiciiiicdddcddciiccdcddddcdciiiiciciiiicdcddddddcciiciiicccddddcicdcddciiiciicddddddc{i}dddcddcdddcdc{i}dddcdccddddddc{i}ddcdddciic ``` It had to be done. [Answer] # [Scratch](https://scratch.mit.edu/), 327 bytes (Illegitimate) [Try it online!](https://scratch.mit.edu/projects/514931746) I was really excited to submit this answer, but then I read the first rule, stating that my program must generate all 36 numbers before I can submit. However, this rule makes hard-coding the only viable option, which is not optimal. I decided to circumvent the several millennia necessary to satisfy this rule, and submitted an answer anyway! To make up for this heinous act, I will be explaining the code in depth here, in addition to on Scratch. ## Full code ``` when gf clicked delete all of[4 v delete all of[f v set[N v]to( forever change[N v]by(1 set[F v]to( repeat until<(F)=(N change[F v]by(1 repeat until<((N)/(F))=(round((N)/(F change[F v]by(1 end add(F)to[f v end set[S v]to( repeat(length of[f v set[S v]to((S)+(item(1)of[f v delete(1)of[f v end if<(S)=((N)*(4))>then add(N)to[4 v ``` ## Setup ``` when gf clicked Initiates the code delete all of[4 v Clears the list of 4-perfect numbers delete all of[f v Clears any residual factors from a previous run of the code set[N v]to( Sets the number that will be checked for 4-perfection to 0 forever Run the following code an infinite amount of times ``` ## Factorization ``` change[N v]by(1 Increments the number to be tested for 4-perfection set[F v]to( Resets the factor that will be tested on the number repeat until<(F)=(N Runs the following code when there is still a factor to be checked for change[F v]by(1 Increments the factor that will be tested on the number repeat until<((N)/(F))=(round((N)/(F Loops code until a valid factor is found change[F v]by(1 Increments the factor that will be tested on the number end Marks the end of the code that needs to loop add(F)to[f v Adds the valid factor to the list of factors end Marks the end of the code that needs to loop ``` ## Summation ``` set[S v]to( Resets the sum of the factors repeat(length of[f v Loops code for each factor in the list set[S v]to((S)+(item(1)of[f v Adds item 1 of the factor list to itself delete(1)of[f v Deletes the obsolete 1st item in the list, making the 2nd item the new 1st item end Marks the end of the code that needs to loop ``` ## 4-Perfection Check ``` if<(S)=((N)*(4))>then Runs code if the sum of factors is 4 times the original value add(N)to[4 v Adds the 4-perfect value to the list NB: "if", "repeat", and "forever", blocks don't need an "end" statement when they're at the end of a script. NB: Groupings ([], (), <>) don't need to be closed if they're at the end of a line. ``` Please understand that I have no intentions of undermining the integrity of the challenge, but I wanted to demonstrate the potential of non hard-coded programs. Scratch is a moderately verbose language- imagine how small a more golf-friendly language could be! [Answer] # Perl, 629 bytes (Not counting one line break added for legibility) ``` use bignum;$_="762K7FF8G213DECG167A6O2B6C68K885DEO5238CFOA36590COF77C22S239FB8CS5DD688ASA40BF4CBEKA54B500277O15A1AA76D5D18K3515C82E18268K479DC3635ACS3D2C86DAC7F142K8A2CE47EB04E2O3DA39DD49D1B489O2B29246D35B6E2_34983A6E0D56A03116W8112111C1388B007CAW535DB1D8191384C3E_BC1718A816B9CA38E_139CE2CE0C2A6520D7D64EAW1580287D7C721FC8E0EFE_30219245E63381BDAD34236W34C38D4A316E11A76BA62_1F166FEDE2AA3B8DEE71C2_4623D01AD5164B207D6A72_5F16A2BFB16257500DB6g2BCF9FAD6C4DE65CA22F8C6Eg6B83D96C6A0809DCDEC5BFF2g3F648C3210B25B8737B940492k1D3523B8D99B8761B6AFBE903D97Ak47AD5F744AA0CC4A843901F8DEAA6k"; s#(\w+?)([G-z])#print hex($1)<<(ord($2)-71),$/#ge ``` The numbers are hard-coded in hexadecimal with a bit of compression applied to the trailing zeroes. [Try it out here.](http://ideone.com/94tEJY) ]
[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 1 year ago. [Improve this question](/posts/8727/edit) Me and some other students were at a bar discussing programming languages, in particular the C programming language. At some point a first year student said he didn't need no damn pointers. Another student said that he couldn't use arrays either since "they're basically pointers". This led to a programming challenge: Implement a reverse polish notation calculator in C without using arrays and pointers. ## Description You must implement a RPN calculator that * operates on integers, * supports addition (+), * supports multiplication (\*). Your implementation * must not use pointers or arrays * you may use structs * the input is read from stdin * your lexer may use pointers and arrays (but it shouldn't be needed) * when EOF is read then print the top of the stack * the behavior can be as undefined as you want for malformed input * should be in a language sufficiently c-like that the "no-pointers and no-arrays" restriction has a sensible interpretation (please elaborate if you think people may not get it) The lexer could have a signature a la thisNote: this is not taken from my own code. Please tell me if there's an error or it looks unreasonable ``` typedef enum { val, op, eof } TYPE; typedef enum { add, mul } OPERATION; typedef struct { TYPE type; union { int val; OPERATION op; } dat; } token; token next(); ``` A solution using a stack with `push()` and `pop()` could look something like this: ``` token t; while ((t = next()).type != eof) { switch (t.type) { case val: push(t.dat.val); case op: switch (t.dat.op) { case add: int v1 = pop(); int v2 = pop(); push(v1+v2); case mult: int v1 = pop(); int v2 = pop(); push(v1*v2); } case eof: printf("Result: %d\n", pop()); } } ``` Other languages than C are also accepted, but the constraints should be comparable. It is hard to state the constraints in a way that fits all languages, but something like »all used data structures must have fixed size and fixed "depth"«. If there's any doubt please ask in the comments. I have a solution that I can post. After cleaning up the code a bit. I wrote it the morning after while hungover. [Answer] This is a stand-alone C version, it doesnt require any external lexer. It works recursivly, like [ratchet freaks solution](https://codegolf.stackexchange.com/a/8730/4626). All characters that are not `+`, `*`, `-` or numbers are treated as spaces. A `-` is treated as a space if it is not directly followed by a number. ``` #include <stdio.h> int rpn(int n1, int n2) { int c, sign = 1, skip = 0; if(n1 < 0) sign = -1; do { c = getchar(); if(c == '+') return n1+n2; if(c == '*') return n1*n2; if(c >= 48 && c <= 57) { if(!skip) n1 = n1 * 10 + sign * (c - 48); else n1 = rpn(sign * (c - 48), n1); } else { skip = 1; sign = 1; } if(c == '-') sign = -1; } while(c != EOF); return n1; } void main() { printf("%d\n", rpn(0, 0)); } ``` [Answer] This is pretty ugly, but I think it works. I've avoided using `null` to make it as obvious as possible that the references could be passed on the stack. I may rewrite this in the morning to have an extra token type of `NULL`. ``` import java.io.IOException; public class RPN { public static void main(String[] args) throws IOException { Token result = depth0(); if (result.type != Token.EOF) throw new IllegalStateException("Bad input"); System.out.println(result.value); } private static Token depth0() throws IOException { Token tok = Lexer.lex(); if (tok.type != Token.NUMBER) throw new IllegalStateException("Bad input"); return depth1(tok); } private static Token depth1(Token s1) throws IOException { while (true) { Token s2 = Lexer.lex(); switch (s2.type) { case Token.EOF: return new Token(Token.EOF, s1.value); case Token.NUMBER: s1 = depth2(s1, s2); if (s1.type == Token.EOF) return s1; break; default: throw new IllegalStateException("Bad input"); } } } private static Token depth2(Token s1, Token s2) throws IOException { while (true) { Token s3 = Lexer.lex(); switch (s3.type) { case Token.EOF: return new Token(Token.EOF, s2.value); case Token.OPERATOR: return new Token(Token.NUMBER, s3.value == Token.OP_PLUS ? s1.value + s2.value : s1.value * s2.value); case Token.NUMBER: s2 = depth2(s2, s3); if (s2.type == Token.EOF) return s2; break; default: throw new IllegalArgumentException("Bug in lexer"); } } } static class Lexer { private static boolean hasPushback = false; private static int pushback; private static int read() throws IOException { if (hasPushback) { hasPushback = false; return pushback; } // Assume input is in ASCII return System.in.read(); } private static void pushback(int ch) { if (hasPushback) throw new IllegalStateException(); hasPushback = true; pushback = ch; } public static Token lex() throws IOException { while (true) { int ch = read(); switch (ch) { case -1: return new Token(Token.EOF, Token.EOF); case '-': return new Token(Token.NUMBER, -lexInteger(0)); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return new Token(Token.NUMBER, lexInteger(ch - '0')); case '+': return new Token(Token.OPERATOR, Token.OP_PLUS); case '*': return new Token(Token.OPERATOR, Token.OP_TIMES); default: // Whitespace or comment break; } } } private static int lexInteger(int value) throws IOException { while (true) { int ch = read(); if (ch < '0' || ch > '9') { pushback(ch); return value; } value = value * 10 + (ch - '0'); } } } static class Token { public static final int NUMBER = 0; public static final int OPERATOR = 1; public static final int EOF = -1; public static final int OP_PLUS = 0; public static final int OP_TIMES = 1; public final int type; public final int value; public Token(int type, int value) { this.type = type; this.value = value; } } } ``` Sample usage: ``` $ javac RPN.java && java RPN <<<"1 2 3 4 5 ****2+" 122 ``` [Answer] use recursion: ``` enum TYPE { val, op, eof }; enum OPERATION { add, mul }; struct token{ TYPE type; union { int val; OPERATIOIN op; } } token parse(int val1,int val2){ token t; //next() is the lexer while((t=next()).type!=TYPE.EOF){ if(t.type==TYPE.op){//calculate the value return token(TYPE.val,t.op==add?val1+val2:val1*val2); }else if(t.type==TYPE.val){ //recurse and pass the top 2 values on the stack t= parse(val2,t.val); if(t.type==TYPE.eof)return t; else val2=t.val; }else{ return token(eof,val2); } } } ``` I returned token so I can stop the recursion cleanly [Answer] 2 uses of pointers are collected at the top, and **are permitted by the rules** as these are a necessary part of I/O at the level of file descriptors. Uses C99 compound literals and POSIX low-level file operations, reading and writing one byte at a time. There is also one implicit `FILE *` returned by `tmpfile()` which is immediately converted by `fileno()` to an integer. This code implements the RPN calculator as a [Semi-Thue system](http://en.wikipedia.org/wiki/Semi-Thue_system) that works like a *queue*. ("Thue" is pronounced /too-ay/, like "2 A".) It uses iteration and a tempfile to evaluate the formula left-to-right, examining up to 3 tokens, possibly reducing, and writing into a new temp file for the next iteration. It waits for enter before each pass. Terminate with an interrupt signal (`ctrl-C`). A simple extension would allow it to detect when a string is no longer reducing from one pass to the next, and terminate. ``` #define Read(f,x) read(f,&x,1) #define Write(f,x) write(f,&x,1),write(1,&x,1) #include <math.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <unistd.h> typedef union { enum tag {number, oper, eof} tag; struct { enum tag tag; int val; } num; struct { enum tag tag; char val; } op; } token; token input(int in){ char b; int a; char o; a=0; o=0; do { if (!Read(in,b)) { return (token){.tag=eof}; } if (b=='\n') { return (token){.tag=eof}; } if (b>='0'&&b<='9') { a*=10; a+=b-'0'; } else if (b=='+'||b=='*') { o=b; } } while(b!=32); if (o) return (token){.op.tag=oper, .op.val=o}; else return (token){.num.tag=number, .num.val=a}; } output(int out, token t){ char b; int c; switch(t.tag){ case number: c=t.num.val>9?(int)floor(log10((double)t.num.val)):0; //b = c + '0'; Write(out,b); for( ; c>=0; c--) { b = '0' + (t.num.val/(int)pow(10.0, c)) % 10; Write(out,b); } break; case oper: b = t.op.val; Write(out,b); break; case eof: b = '\n'; Write(out,b); return; } b = 32; Write(out,b); } int rpn(int in, int out) { token x,y,z; char b; read_x: //b='X';write(1,&b,1); x = input(in); //b='A'+x.tag;write(1,&b,1); switch (x.tag){ case eof: output(out, x); return EOF; case oper: output(out, x); goto read_x; } read_y: //b='Y';write(1,&b,1); y = input(in); //b='A'+y.tag;write(1,&b,1); switch (y.tag){ case eof: output(out, x); output(out, y); return EOF; case oper: output(out, x); output(out, y); goto read_x; } read_z: //b='Z';write(1,&b,1); z = input(in); //b='A'+z.tag;write(1,&b,1); switch(z.tag){ case eof: output(out, x); output(out, y); output(out, z); return EOF; case number: output(out, x); x.num.val = y.num.val; y.num.val = z.num.val; goto read_z; case oper: switch(z.op.val){ case '+': x.num.val = x.num.val + y.num.val; break; case '*': x.num.val = x.num.val * y.num.val; break; } output(out, x); goto read_x; } return 0; } main(){ int i=0,o; char b; token t; do { o = fileno(tmpfile()); rpn(i,o); i = o; lseek(i, 0, SEEK_SET); } while(Read(0,b)); } ``` In action: ``` ./2A 1 2 3 4 5 6 7 8 9 10 + + + + + + + + + 1 2 3 4 5 6 7 8 19 + + + + + + + + 1 2 3 4 5 6 7 27 + + + + + + + 1 2 3 4 5 6 34 + + + + + + 1 2 3 4 5 40 + + + + + 1 2 3 4 45 + + + + 1 2 3 49 + + + 1 2 52 + + 1 54 + 55 55 55 ``` [Answer] # [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation), 2 Bytes ``` do ``` Evaluates as RProgN. Any valid RPN is valid Syntax is RProgN by design, And RProgN is stack based. However, this prints the entire stack after running, not just the top of the stack. This can be resolved with: ``` do p w{ } ``` Which prints the top of the stack, then empties the stack. [Try it online](https://tehflamintaco.github.io/Reverse-Programmer-Notation/RProgN.html?rpn=do&input=%221%203%20%2B%202%20*%204%205%206%207%20%2B%20%2B%20%2B%20%2B%22) ]
[Question] [ Given two integers `m` and `n`, return the first `m` digits of `sqrt(n)`, with the decimal point. They will be given with a space in between. You only have to produce `m` digits: so if `m=5, n=500`, then the output will be `22.360`, not `22.36067`. **Do not use anything that will increase the precision of any operation.** Test Cases: `20 99` -> `9.9498743710661995473` `15 12345678` -> `3513.64170057221` `16 256` -> `16.00000000000000` `2 10000` -> `10` Shortest code wins. [Answer] ## Python, 143 chars ``` m,n=map(int,raw_input().split()) d=10**m n*=d*d a=0 b=n while a<b-1:c=(a+b)/2;a,b=[[c,b],[a,c]][c*c>n] print('%d.%0*d'%(a/d,m,a%d))[:m+(a/d<d)] ``` Computes the answer by multiplying `n` by `10^2m`, doing an integer square root (using binary search), then "dividing" the result by `10^m`. [Answer] # Mathematica 66 272 240 chars **New approach** This uses the same, reasonably efficient (59 chars), method for obtaining the smallest useful convergent of `Sqrt[n]`. It takes a slightly different approach for dividing the numerator by the denominator, accurate to `m` places. ``` t = ToString; q = QuotientRemainder; w = FixedPoint[(# + n/# )/2 &, 1, SameTest -> (Abs[#1 - #2] < 10^(-m) &)]; r = q[Numerator@w, k = Denominator@w]; h[{c_, d_, e_}] := {Append[c, q[d, e][[1]]], 10 q[d, k][[2]], k}; t@r[[1]] <> "." <> t@FromDigits@Nest[h, {{}, 10 r[[2]], k}, m][[1]] ``` **Example: Find the Square root of 5 accurate to 18 places** ``` n=5; m=18; <run the above code> (* out *) "2.236067977499789696" ``` By the way, the convergent, w, for the above case is given below. This is still long-winded but it works. --- **Old approach** The following 59 chars suffice to produce a fraction that will, in decimal form, solve the problem, assuming m, n are entered programmatically: ``` FixedPoint[(# + n/# )/2 &, 1, SameTest -> (Abs[#1 - #2] < 10^(-m) &)] ``` When m=18, n=5, here's the fraction: ``` (* out *) 562882766124611619513723647/251728825683549488150424261 ``` The trick is to convert this fraction into a decimal. The easy way is to use `N`; ``` N[%, m+1] (* out *) 2.236067977499789696 ``` However, `N` violates the rules by specifying the precision to work with. --- Back to the drawing board: ``` q = FixedPoint[(# + n/# )/2 &, 1, SameTest -> (Abs[#1 - #2] < 10^(-m) &)]; f[{a_, n_, d_}] := With[{q = QuotientRemainder[n, d]}, {Append[a, q[[1]]], q[[2]], d/10}] StringInsert[IntegerString@FromDigits@#[[1]], ".", -1/Log[Denominator@#[[3]], 10]] &[NestWhile[f, {{}, Numerator@q, Denominator@q}, Length@#[[1]] < m &]] ``` Unfortunately, it takes another 205 characters (by my reckoning) to generate a decimal expression from the fraction. Surely there must be a more direct way to divide one integer by another to m decimal places! [Answer] ## Haskell 126 ``` main=interact$(\[x,y]->(\s->if '.'`elem`s then(x+1)`take`s else x`take`s)$(show.sqrt.fromIntegral)y++cycle"0").map read.words ``` Darn `sqrt` not taking `Int`s, and `fromIntegral` being so long! [Answer] **C# 41 chars** ``` Math.Sqrt(n).ToString().Substring(0,m+1); ``` [Answer] **Version-1** C# ***364*** Characters (Short Version) ``` using System;namespace X{class T{static void Main(string[] a){int m=int.Parse(Console.ReadLine()),n=int.Parse(Console.ReadLine());Console.WriteLine("{2}",f(n,m));}static string f(long s,int l){decimal x=s;for(int i=0;i<20;x=(((x*x)+s)/(2*x)),i++);var b=x.ToString(string.Format("F{0}",l));return(x.ToString().Contains("."))?b.Substring(0,l+1):b.Substring(0,l);}}} ``` code can be ran from OneIDE - <http://ideone.com/9tZsD>. C# Normal Version ``` using System; namespace X { class T { static void Main(string[] a) { int m = int.Parse( Console.ReadLine()), n = int.Parse( Console.ReadLine()); Console.WriteLine("m:{0}, n:{1} -> {2}", m, n, f(n,m)); } static string f(long s,int l) { decimal x = s; for(int i = 0; i < 20; x = (((x * x) + s) / (2 * x)), i++) ; var b=x.ToString(string.Format("F{0}", l)); return(x.ToString().Contains("."))?b.Substring(0,l+1):b.Substring(0,l); } } } ``` [Answer] ## Pascal, 142 bytes This full `program` requires a processor supporting features of “Extended Pascal” (ISO standard 10206). The `program` will crash if `m` is negative. ``` program p(input,output);var n,m:integer;p:string(maxInt);begin read(m,n);writeStr(p,sqrt(abs(n)):1:m);write(p:m+ord(index(p,'.')in[1..m]))end. ``` Ungolfed: ``` program findFirstNDigitsOfSquareRootOfANumber(input, output); var number, digit: integer; print: string(maxInt); begin readLn(digit, number); { `Sqrt` only works on non-negative integers and always returns the principal root as a `real` value. The `writeStr` routine is defined by Extended Pascal. The `:1` specifies the minimum width of the given argument. The write routines in combination with a `real` argument accept a second format specifier (here `:digit`) that disables scientific notation and determines the number of post-decimal (i.e. fractional) digits. } writeStr(print, sqrt(abs(number)):1:digit); { The format specifier `:digit…` in combination with a `string` argument specifies the _exact_ width. We will need to take account of the radix mark (`'.'`) _if_ it is printed, though. } writeLn(print:digit + ord(index(print, '.') in [1..digit])); end. ``` It is not possible to request `maxInt` digits since one `char` value will be occupied by the radix mark (`.`). You will probably need to replace `maxInt` by a sufficiently small natural number, though. ]
[Question] [ There was a prior question about [golfing an HQ9+ compiler](https://codegolf.stackexchange.com/questions/84170/golf-me-an-hq9-compiler) that translates HQ9+ code into the language it is written in, but that was closed as a duplicate of [the interpreter challenge](https://codegolf.stackexchange.com/questions/12956/creating-a-hq9-interpreter) because converting an interpreter to a compiler is seen as trivial. This question is based on the closed one, but has some changes. Write an [HQ9+](https://esolangs.org/wiki/HQ9%2B) transpiler in a language of your choice. Your submission should be written in some language X, and should take input of HQ9+ source and output a program in another language Y. The `H` command prints `Hello, world!`. `Q` outputs the program's code. For this challenge, it must print the transpiled code, not the HQ9+ source, and must not use cheating quine methods. This deviates from the HQ9+ "specification," but is intended to further distinguish this challenge from the interpreter one. For the avoidance of doubt, using `eval`-type functions or methods such as JavaScript's `function.toString()` are *not* considered cheating for the purpose of this challenge. The `9` command prints the lyrics to "99 Bottles of Beer." You may use any reasonable variant of the lyrics. In theory, `+` increments the accumulator. However, because the accumulator cannot be addressed, `+` is effectively a no-op. `H`, `Q`, and `9` may, but are not required to, print trailing newlines. `+` must not produce any output, not even whitespace. Input must be case-insensitive; `hq`, `hQ`, `Hq`, and `HQ` are the same program. Behavior with unrecognized characters is undefined. ## Rules 1. Language X should satisfy the traditional definition of a language 2. Standard loopholes disallowed 3. Your solution must be testable 4. Y cannot be HQ9+ or an extension of HQ9+ 5. Score is calculated as length of transpiler, plus length of output for `H`, plus length of output for `Q`, plus length of output for `9`, plus length of output for `+`, plus length of output for `HQ9+` 6. Submissions compete by language pairs; and HQ9+ to JavaScript transpiler in Python does not compete with an HQ9+ to C transpiler also written in Python. [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2) (outputs RProgN 2), 190 + 17 + 9 + 116 + 1 + 140 = 473 bytes ``` l]`qEL²"«` .x="w?]`9EL²"$99{]]1-'%i J on the wall %i J! You take one down, pass it around %i J on the wall!'`J'bottles of beer'rF}Si` .y="w? '[^h9q]'Ør`h"'Hello, world!'p"r `9'yp'r`q"xp"r` . ``` [Try it online!](https://tio.run/##XY4xCsJAEEX7PcVkUaYwCtptIVaKiJ2VyMpGsprgkkkmK1HEe3gHO4@gB1ujpeV/n8f/XDIdiv4oBKdNNV2@nvL1MDA4j2Uz0Ub9SEepq9bDPnZzWAAV4DMLTeKc@IJIrOkEPjnatrKQUlPEUCZ1DbmHhOlUpOJfjNAscEfeO1sD7WFnLSPPbqvciMHluy1ws81UpfF9Z5NJnFvnKIaG2KURlpKFUXgpkU0lz21sP4cQZKv05Ac "RProgN 2 – Try It Online") Uses an ultra simple 99 bottles representation. Includes newlines between commands, though instances of `p` can be swapped for `w` to remove them at no extra cost. Conditionally includes a the chunk of code for 99 bottles and the quine only if they're needed. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d) (outputs [Actually](https://github.com/Mego/Seriously/blob/master/docs/commands.txt) or [Seriously](https://github.com/Mego/Seriously/blob/v1/commands.txt)), 14 bytes, score 23 ``` T`l9+`LN_ \B . ``` [Try it online!](https://tio.run/##K0otycxL/P8/JCHHUjvBxy@eK8aJS@//fw@uQC5LLm0uj0BLba6MQq6MQC6PQiAPAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Port of @KevinCruijssen's 05AB1E answer. ``` T`l9+`LN_ ``` Uppercase the input, change `9` to `N`, and delete `+`. ``` \B . ``` Insert `.`s between pairs of letters. (This also means that the output for `+` is `.`, but it's worth it for the golfiness.) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) (outputs [Actually](https://github.com/Mego/Seriously/blob/master/docs/commands.txt) or [Seriously](https://github.com/Mego/Seriously/blob/v1/commands.txt)), score: 20 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) + 2 for `H` + 2 for `Q` + 2 for `9` - 1 since a trailing `.` is not necessary + 0 for `+` + 5 for `HQ9+` ``` u9'N:áS'.ý ``` Output language is either [Actually](https://github.com/Mego/Seriously/blob/master/docs/commands.txt) or [Seriously](https://github.com/Mego/Seriously/blob/v1/commands.txt). It'll output `Hello, World!` and the quine with a single trailing newline, and 99 bottles of beer with two trailing newlines. [Try it online.](https://tio.run/##yy9OTMpM/f@/1FLdz@rwwmB1vcN7///3KLTUzgAA) [Try the output for `Hq9+h` in Actually](https://tio.run/##S0wuKU3Myan8/99DL1DPT8/j/38A). [Try the output for `Hq9+h` in Seriously](https://tio.run/##K04tyswvLc6p/P/fQy9Qz0/P4/9/AA). **Explanation:** *05AB1E:* ``` u # Uppercase all letters in the (implicit) input-string 9'N: '# Replace all 9s with "N"s á # Remove the "+"s by only leaving letters S # Convert the string to a list of characters '.ý '# Join it back together with "." delimiter # (after which the result is output implicitly) ``` *Actually / Seriously:* * `H`: Push "Hello, World!" to the stack * `N`: Push the entire 99 bottles of beer lyrics (with trailing newline) to the stack * `Q`: Push the program's source code to the stack * `.`: Pop and print a string with trailing newline * Implicitly print the trailing string on the stack which we haven't explicitly printed with a `.` ]
[Question] [ Consider: ``` c=(a,b)=>(+a||0)+(+b||0) ``` Yes, it is not good to solve it like that. But I want to shorten it even more. If `a` is a string and `b` is a string, then return `0`. If one is a number, return it. And if both inputs are numbers, then return the sum (if either string can be cast to a number, treat it as a number). I tried to shorten this more, but I just can’t. This is the specification for the task: ## Usage ``` node app.js ``` ## Expected behavior The program returns the sum of two numbers. If no numbers are provided, the result should be `0`. If only one number is provided, only that number should be returned. ## Tests ``` node app.js 4 5 # 9 node app.js 4 # 4 node app.js 4 a # 4 node app.js a 4 # 4 node app.js a b # 0 node app.js # 0 ``` ## Update It also needs to handle floats as well not only integers. This is my current code (only the code on line 1 should be optimized to be as small as possible): ``` c=(a,b)=>(+a||0)+(+b||0) const input1 = process.argv[2]; const input2 = process.argv[3]; const result = c(input1, input2); console.log(result); ``` [Answer] # JavaScript, ~~15~~ 14 bytes ``` c=a=>b=>~-a-~b ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/P9k20dYuydauTjdRty7pf0FRZl6JRrKGoSYQaf4HAA) [Answer] If you only need to handle integers, you can use bitwise operations to convert them into a numbers: ``` c=(a,b)=>(a|0)+(b|b) // Both ways shown fine ``` Or even shorter: ``` c=a=>b=>~-a-~b // (a-1)-(-b-1) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/P9k20dYuydauTjdRty7pf0FRZl6JRrKGoSYQaXLBuOqJ6qgCQHn1JHWgwH8A "JavaScript (V8) – Try It Online") This doesn't work for floats, but this trick seems unmentioned elsewhere, so I've left it here. ]
[Question] [ **This question already has answers here**: [Return each number from a group of numbers](/questions/8588/return-each-number-from-a-group-of-numbers) (21 answers) Closed 8 years ago. ## Goal: Your goal is to print out numbers within a given range (*Also including given values*). ## Input Format: The input will look like: `(int-int, int-int, ...)` `...` meaning the user can add as many `int-int` as they'd like. ## Other Info: * You will only have to handle *non-negative* integer numbers. * The first integer in `int-int` will always be smaller, or the same, then the next integer in `int-int` * The input will *always have at least two* `int-int` * Each `int-int` will followed by a comma and a space, except for the last one. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") meaning the shortest answer wins! ## Examples / Test Cases: * Example 1: * Input: `(10-13, 11-15, 0-3)` * Output: `10 11 12 13 11 12 13 14 15 0 1 2 3` * Example 2: * Input: `(1-5, 1-15)` * Output: `1 2 3 4 5 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15` * Example 3: * Input: `(1-2, 1-3, 1-3, 1-2)` * Output: `1 2 1 2 3 1 2 3 1 2` * Example 4: * Input: `(4-6, 0-1, 9-9)` * Output: `4 5 6 0 1 9` [Answer] ## [Minkolang 0.13](https://github.com/elendiastarman/Minkolang), 12 bytes ``` nd1+?.n~Lr$N ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=nd1%2B%3F%2En%7ELr%24N&input=%2810-13%2C%2011-15%2C%200-3%29) ### Explanation ``` n Take number from input (-1 if input is devoid of numbers) d1+ Duplicate and add 1 ?. If this is 0, stop. n~ Get number from input and negate it (because of the '-') L Pops b,a and pushes a,a+1,a+2,...,b-1,b r Reverses list $N Outputs whole stack as numbers ``` [Answer] # CJam, 19 ``` qS/{'.,Ser~),>~}%S* ``` Martin Büttner killed 2 bytes again, thanks :) [Try it online](http://cjam.aditsu.net/#code=qS%2F%7B'.%2CSer~)%2C%3E~%7D%25S*&input=(4-6%2C%200-1%2C%209-9)) **Explanation:** ``` q read input S/ split by space {…}% transform each string (containing a pair of numbers and some other chars) '., enumerate all characters smaller than '.' Ser replace them all with a space in the string ~ evaluate the resulting string, pushing the 2 numbers on the stack let's call them A and B ), create an array [0 1 … B] > slice it from A: [A … B] ~ dump it onto the stack S* join the resulting array with spaces ``` [Answer] # Julia, 75 bytes ``` s->print((j=join)(map(i->j(i," "),eval(parse(replace(s,"-",":"))))," ")) ``` This is an anonymous function that accepts a string and prints to STDOUT. To call it, give it a name, e.g. `f=s->...`. Ungolfed: ``` function f(s::AbstractString) # Replace dashes with colons in the input c = replace(s, "-", ":") # Parse as a tuple of UnitRange objects r = eval(parse(c)) # Join each range with spaces m = map(i -> join(i, " "), r) # Join into one string and print print(join(m, " ")) end ``` [Answer] ## Javascript (ES 2015), ~~86~~ 83 bytes ``` f=r=>{z="";r.replace(/(?:(\d+).(\d+))/g,(m,n,x)=>{do{z+=n+" "}while(n++<x)});alert(z)} ``` Live Demo: <http://codepen.io/anon/pen/BoeEGO?editors=001> --- **Edit 1**: saved 3 bytes changing the body of the inner function into `for(;n<=x;)z+=n+++" "` (and I feel good when the horizontal scrollbar of my snippet at last disappears :) ) ``` f=r=>{z="";r.replace(/(?:(\d+).(\d+))/g,(m,n,x)=>{for(;n<=x;)z+=n+++" "});alert(z)} ``` --- Ungolfed ``` f=r=>{ // define a function with 'r' arg z=""; // initialize a variable to collect // the output r.replace(/(?:(\d+).(\d+))/g,(m,n,x)=>{ // for each range // where (m=range, n=min, x=max) for(; n<=x; ) { // until min <= max z += n++ + " " // add to z the value and a space } }); alert(z) // alert the output } ``` --- ``` f("(10-13, 11-15, 0-3, 9-9)"); // Output: 10 11 12 13 11 12 13 14 15 0 1 2 3 9 ``` [Answer] ## Python 2, 125 bytes ``` import re print' '.join(map(lambda x:' '.join([str(y)for y in x]),eval(re.sub('(\d+)-(\d+)',r'range(\1,\2+1)',raw_input())))) ``` [Try it online](http://ideone.com/fork/YnDE68) I'm certain this could be golfed more... [Answer] ## CJam, 41 bytes (too long!) Definitely can be golfed, but its a start. Test it online [here](http://cjam.aditsu.net/#code=l'(%2Fe_')%2Fe_'%2C%2F%7B%5B'-'%20er~%5D2%2C.%2B%3A%2CW%25%3A-%7D%25e_'%20*&input=(1-2%2C2-4)). ``` l'(/e_')/e_',/{['-' er~]2,.+:,W%:-}%e_' * l e# Take string input '(/e_ e# Remove '( characters ')/e_ e# Remove ') characters ',/ e# Split on commas { }% e# Map over array... ['-' er~] e# Convert A-B to [A B] 2,.+ e# Convert [A B] to [A B+1] :,W% e# Convert [A B+1] to [[0,1,2, ... B][0, 1, 2, ... A]] :- e# Remove element 1 of the previous array from element 2 e_' * e# Format nicely e# CJam prints stack after execution ``` [Answer] # TeaScript, 18 + 1 = 19 bytes ~~20~~ +1 byte for "Inputs are arrays / lists?" checkbox Such abuse... ``` xße`r(${ls`-`}¬)`) ``` I've never abused JavaScript's casting more in my life. [Try it online](http://vihanserver.tk/p/TeaScript/#?code=%22x%C3%9Fe(%60r($%7Bls%60-%60%7D%C2%AC)%60%C2%A9%22&inputs=%5B%22(1-2,%201-3,%201-3,%201-2)%22,%22%22%5D&opts=%7B%22int%22:false,%22ar%22:true,%22debug%22:false,%22chars%22:false,%22html%22:false%7D) ## Ungolfed && Explanation My favorite part is JavaScript arrays when cast to a string have commas auto-inserted. We abuse this so the array elements are inserted as numbers *and* as separate arguments. So `1-2`, would become `['1','2']` but when string casted `1,2` and this can be put directly in a function. ``` xm(#e`r(${ls`-`}+1)`) // The checkbox makes the input like ['1-2','3-4'] xm(# ) // Loop through input e` ` // Eval string... r( +1) // range function... ${ls`-`} // Convert range -> args // See above for more details ``` [Answer] ## Python 3, 76 bytes ``` l=eval(input().replace(*'-,')) while l:a,b,*l=l;print(*range(a,b+1),end=' ') ``` The input is evaluated as a tuple by replacing each `-` with `,` ``` (10-13, 11-15, 0-3) --> (10,13, 11,15, 0,3) ``` Then, the first two elements of the list are repeatedly lopped off and the numbers between them are printed. Saved 2 bytes thanks to xsot. [Answer] # Mathematica, 80 bytes ``` Join@@BlockMap[Range@@FromDigits/@#&,StringCases[#,DigitCharacter..],2]~Row~" "& ``` [Answer] # [O](https://github.com/phase/o), ~~75~~ 74 bytes ``` I'(-')-", "/]{[[n'-/]{n#}d[$,.$.0=0={.@=0={;.@=0=}w;}{;;}?r]]{n{noTo}d}d}d ``` This makes logical sense to anyone who built the language (i.e. me). The logic behind this is intense and I'm just happy that I got it working. [Try it online](http://o-lang.herokuapp.com/link/W2knKC0nKS0iLCUyMCIvXXtbW24nLS9de24jfWRbJCwuJC4wPTA9ey5APTA9ezsuQD0wPX13O317Ozt9P3JdXXtue25vVG99ZH1kfWQ=/KDEwLTEzLCUyMDExLTE1LCUyMDAtMyk=) or [RUN EVERY TEST CASE AT THE SAME TIME](http://o-lang.herokuapp.com/link/W2lpaWlde1tuJygtJyktIiwlMjAiL117W1tuJy0vXXtuI31kWyQsLiQuMD0wPXsuQD0wPXs7LkA9MD19dzt9ezs7fT9yXV17bntub1RvfWR9ZH1kVXB9ZA==/KDEwLTEzLCUyMDExLTE1LCUyMDAtMykKKDEtNSwlMjAxLTE1KQooMS0yLCUyMDEtMywlMjAxLTMsJTIwMS0yKQooNC02LCUyMDAtMSwlMjA5LTkp) Explanation: ``` I'(-')-", "/] Format inputs into array { Iterate over each input range [[n'-/]{n#}d Split ranges into sets of numbers [$, Get the second number and get a range from 0 to it .$.0=0= Is the first number 0? {.@=0={;.@=0=}w;} True: Remove any unneeded numbers {;;}? False: Pop some random stuff that shouldn't have been on there to begin with r]] Reverse the range and close some array stuff or whatever {n{noTo}d}d} Format output }d ``` ]
[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/32207/edit). Closed 5 years ago. [Improve this question](/posts/32207/edit) Let's discover1 some bugs... Write the shortest complete program possible that, when run on a **stable** release of an implementation of a language, demonstrates a bug in that implementation. Please specify which release and platform was used. This is code golf, so the shortest code (in bytes) wins. * An implementation bug is any behavior that contradicts the language's official standard or specification. * This does not include bugs in the language's standard library. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid submission (measured in **bytes**) wins. 1 OK, you don't actually have to find the bug. But if you do, don't forget to file a bug report! :) [Answer] # Golfscript, 4 ``` 2-1? ``` This produces output of `1/2` in the interpreter downloaded from [golfscript.com](http://www.golfscript.com/) and `0.5`on [web golfscript](http://golfscript.apphb.com/). There aren't supposed to be floats in golfscript, but the latest compiler has this on line 82: `Gint.new(@val**b.val)` and it seems to miss a cast to int. [Answer] # [Taxi](https://bigzaphod.github.io/Taxi/), 256 bytes ``` 1 is waiting at Starchild Numerology.1 is waiting at Starchild Numerology.Go to Starchild Numerology:w 1 l 2 r 1 l 1 l 2 l.Pickup a passenger going to Equal's Corner.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:w 1 l.Go to Go More:n 2 l. ``` [Try it online!](https://tio.run/##lY6xDsIwDER/5Ta2SmXsihATCIkvsEoULExcnEQtXx9Kw4LEAItt@U53L9HEpbTgiJE4cfCghFMi6y8sZxzyzZmK@kfzk2mnSPpV6ka0EKxhy663NEfur3kAYaAYXfDO4PXVMMds75lkFbFRC87@sVaMz2cFeEvz3Ku5LiwQpTwB "Taxi – Try It Online") I'm not 100% sure this counts but, based on the [map of Townsburg](https://bigzaphod.github.io/Taxi/map-big.png), `Go More` is the 2nd left when heading north from `Equal's Corner`. However, the little dead-end road that is the 1st left (the one that `Starchild Numerology` is on) doesn't have any nodes on it. Thus, as far as the [official interpreter](https://bigzaphod.github.io/Taxi/taxi.cpp) is concerned, it's not a road. Thus, `Go More` is actually the *first* left. If you run the above program, you'll get: ``` error: cannot drive in that direction ``` [Answer] # [Haskell](https://www.haskell.org/) (GHC 8.0.2 on TIO), ~~10~~ 9 bytes -1 byte thanks to @Angs ``` f::() f=w ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P83KSkOTK822/P9/AA) I have no idea what's happening here. A constant with a type signature defined to be a nonexistent identifier causes an ICE ("impossible happened") on TIO Haskell. [Answer] # Bash, 11 bytes ``` $ bash --version GNU bash, version 4.2.47(1)-release (x86_64-redhat-linux-gnu) Copyright (C) 2011 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software; you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. $ $ $[2**63%-1] Warning: Program '/bin/bash' crashed. ``` [Answer] # Bash, 7 bytes ``` $ xxd bug.sh 0000000: 2431 3c3c 5f0a 01 $1<<_.. $ bash bug.sh xxd 2>&- 0000000: 0a . $ dash bug.sh xxd 2>&- 0000000: 01 . ``` [Answer] # SmileBASIC, 4 bytes ``` ?1;? ``` This should be equivalent to: ``` PRINT 1; PRINT ``` Printing the number `1` without a trailing linebreak, then moving to the next line. However, it throws the error `Type mismatch(PRINT:3)` after printing `1`. The bug is that PRINT only has 2 arguments, while the error refers to a third argument which doesn't exist. [Answer] # PHP 5.5, 31 bytes ``` (new GlobIterator("*"))->key(); ``` When it is executed in an empty directory, it throws: > > Fatal error: Uncaught exception 'LogicException' with message 'The parent constructor was not called: the object is in an invalid state ' in Command line code on line 1 > > > It shouldn't throw any exception. It doesn't throw any exception if the glob pattern (`*`) matches at least one file in the directory. It is also present in PHP 5.3 and 5.4. PHP 5.3 cannot parse the code above, it requires the object created by `new` to be stored in a variable before running any of its methods (35 chars after stripping the unneeded white space characters): ``` $x = new GlobIterator("*"); $x->key(); ``` It is bug [#55701](https://bugs.php.net/bug.php?id=55701) and it [has been fixed](https://github.com/php/php-src/pull/1880) in July 2016 for PHP 5.6 and 7.0. It was also present in these versions until it was fixed. The versions released after the fix (7.1 and 7.2) don't have this bug. It was not fixed for PHP 5.5 and older versions because they were already beyond their support phase at that time. [Answer] # Java 5 or 6, 12+ bytes ``` enum M{M;{/* Code here */}} ``` In Java versions 1 through 7, all1 Java programs should have an endpoint class containing a main-method: ``` class M{public static void main(String[]a){/* Code here */}} ``` And in Java 8 through 10 you should have this as well, or optionally an interface instead: ``` interface M{static void main(String[]a){/* Code here */}} ``` In Java versions prior to Java 7, it was due to a bug possible to use a static block instead like this: `class M{static{/* Code here */}}`, to run code without a main method. It will still give the following error to STDERR, but only after it has executed the code inside the static block: > > M > > java.lang.NoSuchMethodError: main > > Exception in thread "main" > > > In Java 5 and 6 this could also be done without static block in an `enum`, as displayed at the top of this answer, which is also mentioned on the [*Tips for Golfing in Java* page by *@OlivierGrégoire*](https://codegolf.stackexchange.com/a/140181/52210). Also mentioned on that tip page is that you can get rid of the error to STDERR by changing it to: ``` enum M{M;{/* Code here */System.exit(0);}} ``` This might be useful if a challenge states it isn't allowed to error and requires a full program (although in the current meta functions are allowed, and [errors to STDERR after you've already completed the challenge are also allowed](https://codegolf.meta.stackexchange.com/a/4781/52210)). *1. Note that [`java.applet.Applet`](https://docs.oracle.com/javase/7/docs/api/java/applet/Applet.html) or [`javafx.application.Application`](https://docs.oracle.com/javase/8/javafx/api/javafx/application/Application.html) classes can run independent without a main-method, although their general use is to be embedded inside another application.* [Answer] # J, 24 Bytes ``` (".@,quote)'(".@,quote)' ``` This works on all versions I've tried. Infinite recursion should throw a stack error, for example, in `$: 0`. However, the `".` verb (eval) seems to fly under the radar, and this crashes the interpreter with a segmentation fault. Based on the quine ``` (,quote)'(,quote)' ``` [Try it online!](https://tio.run/##y/r/X0NJz0GnsDS/JFVTHZn9/z8A "J – Try It Online") [Answer] # C++ (gcc 4 or 5) + Boost, 94 bytes I'm not sure exactly which versions of gcc this will or won't work on. The guy who [originally reported the bug](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=81321) says the bug is present in gcc4 and gcc5, so I will take his word on it. Personally, I tested it with 5.4.0 ``` #include <boost/any.hpp> #include <cstdarg> int a(const boost::any&x){}int b(va_list l){a(l);} ``` Attempting to compile this produces: ``` $ gcc gccbug.cpp gccbug.cpp:3:50: internal compiler error: Segmentation fault int a(const boost::any&x){}int b(va_list l){a(l);} ^ Please submit a full bug report, with preprocessed source if appropriate. See <file:///usr/share/doc/gcc-5/README.Bugs> for instructions. ``` ]
[Question] [ Your challenge is to write a routine, in x86 assembly, which takes a buffer containing 32-bit signed integers and writes a sorted list of the prime values to another buffer, then returns the number of values written to the output buffer. The winning solution is the one that uses the **least instructions**. Here's a pseudo-C example of the process: ``` int __stdcall SortedPrimes(DWORD* input, DWORD* output) { int ctr_in = 0; int ctr_out = 0; int val = 0; // copy primes to output buffer while((val = input[ctr_in]) != 0) { ctr_in++; if(isPrime(val)) output[ctr_out++] = val; } // you must implement this sort, too! sort(output); return ctr_out; } // for testing/illustration purposes only // you don't need to implement this part! void test() { int count = 0; int i = 0; int v = 0; // allocate buffers DWORD* input = (DWORD*)calloc(1024, sizeof(DWORD)); DWORD* output = (DWORD*)calloc(1024, sizeof(DWORD)); // fill input buffer with data input[0] = 0x12345678; input[1] = 0x57AC0F10; ... input[1022] = 0x13371337; input[1023] = 0; // terminating value is zero! // invoke your function! :] count = SortedPrimes(input, output); // dump output printf("Found %n primes.\n", count); while((v = output[i++]) != 0) printf("0x%x\n", v); free(input); free(output); } ``` Rules: * Assume a modern Intel CPU (e.g. Core i3) running in x86-32 mode. * Assume `__stdcall`, i.e. parameters pushed from right to left, `esp+4` is a pointer to `input`, `esp+8` is a pointer to `output`, callee is responsible for cleaning stack. * You cannot call any APIs or library functions - the solution must be in pure assembly. * The input buffer consists of 32-bit non-zero signed integers, followed by `0x00000000`. * The output buffer is allocated and zero'd before being passed to the function, and its size is the same as the input buffer. * Assume there are no negative inputs, i.e. the range is `0x00000001` to `0x7FFFFFFF`. * The sort must be lowest to highest, such that `output[0]` is the lowest value in the list. * Must give an empty output buffer when given an empty input buffer. * Must properly handle cases where all values are prime / no values are prime. * You may not use compiler macros. * The code must be able to process 1000 inputs in 60 seconds or less. * I'll accept answers in AT&T syntax, but I'd prefer Intel syntax for uniformity. * Winner is the code that has the **least number of instructions** (i.e. lowest number of lines of code), not the least number of characters. Assembly is pretty terse, so please add comments to your code where necessary. Enjoy :) [Answer] # 32 30 29 28 27 Instructions Changed my algorithm so we're not all trying to implement the same thing, and it's a little smaller than my earlier attempt. The code repeatedly searches through the input array, finding the smallest value, and replacing it with 0xfffffffd. It then tests if the found value is prime and outputs it if so. The code exits when the input has been completely replaced with 0xfffffffd. ``` pushad mov ecx, 0 ; zero output count and position mov esi, [esp + 8+32] ; load output array find_smallest: mov eax,-3 ; 0xfffffffd is larger than any valid input mov edi, [esp + 4+32] ; load input array find_smallest_loop: scasd jbe find_smallest_loop xchg eax,[edi-4] ; swap ecx with values that are smaller, values ; get replaced with 0xfffffffd as they are used cmp eax,1 je find_smallest ; skip inputs of 1 ja find_smallest_loop ; exit loop if a 0 is reached xchg eax,[edi-4] ; swap 0 with lowest value found mov [esi+ecx*4],eax ; store value in next output position mov ebx,2 ; ebx is divisor, start it at 2 test_next_divisor: ; primality test mov eax,[esi+ecx*4] cdq idiv ebx ; use signed division cmp eax,ebx cmovb edx,[edi-4] ; zero edx if prime to exit loop later on adc ecx,0 ; increment output & count if prime inc ebx test edx,edx jz find_smallest jns test_next_divisor ; exit if remainder is negative exit_function: mov [esp+28],ecx ; move count to eax position popad ret 8 ``` [Answer] ## 26 instructions I found this task for the first time only yesterday. sigh. I took @Sir\_Lagsalot's code and removed one xchg. The changes are too significant for a comment, so I've placed it here for review. ``` pushad mov ecx, -1 ; will zero output count and position using next instruction count_prime: inc ecx ; increment output & count if prime mov esi, [esp + 8+32] ; load output array find_smallest: mov eax,-3 ; 0xfffffffd is larger than any valid input mov edi, [esp + 4+32] ; load input array db 3dh, 50h ; mask next instruction on first pass find_smallest_loop2: xchg eax,[edi-4] ; swap ecx with values that are smaller, values ; get replaced with 0xfffffffd as they are used find_smallest_loop: scasd jbe find_smallest_loop mov ebx,1 ; ebx is divisor, will start it at 2 later ; but we need 1 right now cmp [edi-4],ebx je find_smallest ; skip inputs of 1 ja find_smallest_loop2 ; exit loop if a 0 is reached mov [esi+ecx*4],eax ; store value in next output position test_next_divisor: ; primality test mov eax,[esi+ecx*4] cdq inc ebx ; 2+ idiv ebx ; use signed division cmp eax,ebx jb count_prime test edx,edx jz find_smallest jns test_next_divisor ; exit if remainder is negative exit_function: mov [esp+28],ecx ; move count to eax position popad ret 8 ``` [Answer] ## ~~41~~ 29 instructions The code itself, NASM syntax: ``` global primes section .code primes: pushad mov esi, [esp + 32 + 4] mov dword [esp + 28], 0 ; primes counter read: add esi, 4 mov ecx, [esi - 4] jecxz return ; zero terminator cmp ecx, 1 je read ; omit 1 mov ebx, 2 ; initial divisor try_divisor: mov eax, ecx ; get original number from ecx mov edx, 0 div ebx ; divide cmp ebx, eax jg save ; divisor exceeds sqrt(n), so n is prime cmp edx, 0 je read ; not prime inc ebx ; next divisor jmp try_divisor save: ; prime number to store is in ecx inc dword [esp + 28] ; increase prime counter mov edi, [esp + 32 + 8] bubble: ; insert prime into output array add edi, 4 xchg ecx, [edi - 4] jecxz read cmp ecx, [edi - 4] jge bubble xchg ecx, [edi - 4] jmp bubble return: popad ret 8 ``` I borrowed a lot from Keith Randall's solution, but improved prime saving code. So, I guess, my code should be out of competition since it's not completely mine. [Answer] ## 35 31 instructions ``` .globl _primesort _primesort: pushal mov 36(%esp),%esi # load input ptr mov 40(%esp),%edi # load output ptr movl $0,28(%esp) # count primes in saved eax slot inputloop: add $4,%esi cmp $1,-4(%esi) jl return # 0 = input end marker je inputloop # special case for 1 mov $2,%ecx # trial divisor testloop: mov -4(%esi),%eax mov $0,%edx div %ecx cmp %ecx,%eax jl saveprime # n/d < d => d > sqrt(n) => no more trial division cmp $0,%edx je inputloop # found a divisor inc %ecx # next trial divisor jmp testloop saveprime: mov -4(%esi),%eax # prime mov 28(%esp),%ecx # index of new last element jecxz storeprime # at start of output array, just store it bubbledown: cmp %eax,-4(%edi,%ecx,4) jl storeprime # found spot to store it mov -4(%edi,%ecx,4),%edx mov %edx,(%edi,%ecx,4) # move larger element up one loop bubbledown # repeat until start of output array storeprime: mov %eax,(%edi,%ecx,4) incl 28(%esp) jmp inputloop return: popal ret ``` This code is AT&T syntax, and it uses `cdecl` instead of `stdcall`, but I think the only difference for the latter would be to replace the `ret` with `ret 0x8`. [Answer] ## 28 instructions Build with `nasm -f elf32`: ``` BITS 32 GLOBAL sortedprimes ;; int sortedprimes(int const *input, int *output) ;; Read a zero-terminated list of numbers from input. Copy only the prime ;; numbers to the buffer output, returning the count of numbers so ;; copied. The numbers in output are returned in sorted order. sortedprimes: ;; Within this function: ;; eax = the number currently being tested for primality; ;; ecx = the potential divisor being tested; ;; esi = the pointer to the next number to test for primality; ;; edi = a pointer into the output buffer; and ;; (eax on the stack) = how many numbers are in the output buffer. ;; Initialize the return value to zero, and point esi at the input buffer. xor eax, eax pusha mov esi, [byte esp + 36] ;; Retrieve the next number to be tested. If the number is one, it is ;; skipped. If the number is zero, the program has reached the end of ;; the buffer and exits. Otherwise the program starts testing ;; potential divisors, starting with 2. .nextnumber: lodsd mov ecx, 2 cmp eax, byte 1 jz .nextnumber jns .divloop popa ret 8 ;; Divide the number by a candidate divisor. If the quotient is less ;; than the candidate, the list of; potential divisors has been ;; exhausted, and the program jumps forward. If the remainder is ;; zero, however, then the number is composite, and it is discarded ;; and the program jumps back to get the next number. If neither is ;; true, then ecx is incremented and the next candidate is tested. .divloop: xor edx, edx div ecx cmp eax, ecx mov eax, [byte esi - 4] jl .prime inc ecx or edx, edx jnz .divloop jmp short .nextnumber ;; eax contains a prime. The count of primes is incremented, and eax ;; is temporarily placed into the output buffer at the initial position, ;; displacing whatever number was already there. This number is then ;; restored, edi is advanced and eax displaces the number at at the ;; next position. Thus continues until (a) a number higher than eax ;; is reached, in which case it is left there and the displaced ;; number is left in eax, to become the displacing number going ;; forward, or (b) the end of the list is reached, in which case the ;; last number displaced is just zero-padding, and it is discarded as ;; the program jumps back to test the next input number. .prime: inc dword [byte esp + 28] mov edi, [byte esp + 40] .insertloop: xchg eax, [edi] or eax, eax jz .nextnumber scasd jg .insertloop xchg eax, [byte edi - 4] jmp short .insertloop ``` @Sir\_Lagsalot is right that all of our solutions are starting to look the same. I was actually a bit dismayed when I finally read Alexander Bakulin's solution at how closely it resembled my own. I guess that's a side effect of targeting the challenge to a single language/platform. ]
[Question] [ Oplop is an algorithm to generate website specific passwords based on a master password and a keyword. It is described here: <http://code.google.com/p/oplop/wiki/HowItWorks> There's an online implementation here: <https://oplop.appspot.com/> My attempt in Q is 204 200 167 165 139 characters ignoring whitespace: ``` {d:.Q.A,.Q.a,(n:"0123456789"),"-_"; b:d 2 sv'6 cut(,/)0b vs'(md5 x,y),2#0x00; i:b in n;j:i?1b;k:(j _i)?0b; 8#$[0=0+/i;"1";8>j;();b j+(!)k],b} ``` EDIT: I achieved significant character savings by removing some redundant code from my Hex->Base64 conversion. 2012.03.07 - Cut out 2 more characters 2012.03.11 - Removed duplication and got accurate char count 2012.03.20 - Down to 141 **Criteria** Candidate functions/implementations should take two strings as arguments and return an 8 character password as defined in the algorithm. **Judging** Code golf so shortest code takes the prize. [Answer] ## Python - 198 166 152 150 ``` import base64,md5,sys,re b=base64.urlsafe_b64encode(md5.md5(sys.argv[1]+sys.argv[2]).digest()) r=re.findall('\d+',b)if all(not c.isdigit()for c in b[:8])else[''] print((r[0]if len(r)else'1')+b)[:8] ``` ``` import base64,md5,sys,re b=base64.urlsafe_b64encode(md5.md5("".join(sys.argv[1:])).digest()) print((''if re.search('\d',b[:8])else re.findall('\d+',b+'1')[0])+b)[:8] ``` ``` import base64,md5,sys,re b=base64.urlsafe_b64encode(md5.md5("".join(sys.argv[1:])).digest()) print(re.findall('(?:[^\d]{8,}(\d*)|)',b+' 1')[0]+b)[:8] ``` This was a fun one. Could be a lot shorter if not for the verbosity of the `md5` and `base64` modules. The third and fourth lines are the interesting ones. My favourite trick was using a list containing only an empty string to avoid having to use any real if statements. EDIT: Had to change from checking `c.isalpha()` to `not c.isdigit()` (added 4 characters) EDIT: Shaved off 32 characters. Many thanks to Ugoren! EDIT: Shaved off 14 more chars again many thanks to Ugoren. Used some regex trickiness ``` print(re.findall('(?:[^\d]{8,}(\d*)|)',b+' 1')[0]+b)[:8] ``` instead of ``` print((re.findall('^[^\d]{8,}(\d*)',b+' 1')+[''])[0]+b)[:8] ``` To save three chars. [Answer] ## Shell - 116 ``` echo -n $1$2|md5sum|xxd -r -p|base64|sed -re'y!+/!-_!;/^.{0,7}[0-9]/!{s/^([^0-9]*)([0-9]+)/\2\1/;t;s/^/1/}'|cut -c-8 ``` Depends on cut, md5sum and base64 from coreutils, xxd and GNU sed. [Answer] ## Ruby (113 110 chars) ``` require 'digest' b=Digest::MD5.base64digest(ARGV.join) puts "#{b} 1".sub(/(^\D{8,}(\d*))/,'\2\1')[0..7].tr'+/','-_' ``` ``` require'digest' b=Digest::MD5.base64digest(ARGV.join) puts"#{b} 1".sub(/(^\D{8,}(\d*))/,'\2\1')[0,8].tr'+/','-_' ``` I notice that all the non-Python languages have to do a translation of the + and / to be - and \_, respectively. It seems that Python's base64 is different/wrong? [Answer] ## PHP (126) ``` function f($m,$n){return substr(preg_replace('/^\D{8,}(\d+)/','$1$0',strtr(base64_encode(md5($m.$n,1)),'+/','-_').' 1'),0,8);} ``` Beautified: ``` function oplop( $master, $nick ) { return substr( preg_replace( '/^\D{8,}(\d+)/', '$1$0', strtr( base64_encode( md5( $master . $nick, true ) ), '+/', '-_' ) . ' 1' ), 0, 8 ); } ``` ]
[Question] [ ## Challenge (Easy) > > Write a function which takes an argument and returns the number of non-alphanumeric characters found. > > > ## Challenge (Hard) > > Write a function which takes an argument and returns the number of bytes used to store the number of non-alphanumeric characters found. (ie: include calculation for multi-byte characters.) > > > ## Rules / Notes * Alphanumeric in this case is defined as: `abcdefghijklmnopqrstuvwxyz` `ABCDEFGHIJKLMNOPQRSTUVWXYZ` `0123456789` * A null character should count as 0 characters, but as 1 byte when stored. `NUL` * Showing multi-byte support (if too complicated) only has to demonstrate one character set or language reference / codepage (if this actually matters. I don't know, so just putting it out there.) ## Winner Since this is code golf, the shortest code that correctly matches the challege wins. [Answer] # Perl, 14 characters ``` y/A-Za-z0-9//c ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 3 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) (Easy) ``` ├Dr ``` [Run and debug it](http://stax.tomtheisen.com/#p=c34472&i=This_i%24_A_T3st%21) **Explanation** ``` VL-% # Full program, unpacked VL # Push "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" - # Remove all elements in b from a. % # Length and implicitly print result ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 6 4 bytes ``` ḟØBL ``` [Try it online!](https://tio.run/##y0rNyan8///hjvmHZzj5/P//3wMokK8Qnl@Uk2IQb2ykCAA "Jelly – Try It Online") ``` ḟØBL ḟ reverse ḟilter: remove all of the input characters that are also in... ØB alphanumeric characters... L and get the Length of the resulting string! ``` **6-byte solution:** ``` ḟØWṖ¤L ``` [Try it online!](https://tio.run/##y0rNyan8///hjvmHZ4Q/3Dnt0BKf////ewBF81XC84tyUpTjAQ "Jelly – Try It Online") ``` ḟØWṖ¤L ḟ reverse ḟilter: remove all of the input characters that are also in... ØWṖ¤ the "word" character class with the underscore popped from it, taken as a nilad... L ...and take the length of the resulting string ``` [Answer] # D ## easy (29 chars) ``` count!"!isAlphaNum(b)&&b"(s); ``` ## hard (35 chars) `s` needs to be a `char[]` ``` s.length-count!"!isAlphaNum(b)"(s); ``` [Answer] # Groovy ## Easy: 26 25 30 characters ``` c={(it=~/[[^\00\w]_]/).size()} assert c("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789")== 2 assert c("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")==0 assert c("a-b-7*NNuah ~#77%")==7 assert c('_|') == 2 assert c('\0') == 0 ``` ## Hard: 47 characters ``` s={it.replaceAll(/[\w&&[^_]]/,'').bytes.size()} assert s("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789")== 2 assert s("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")==0 assert s("a-b-7*NNuah ~#77%")==7 assert s('_') == 1 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes (easy) ``` #(¬□ ``` [Try it online!](https://tio.run/##yygtzv7/X1nj0JpH0xb@///fIzUnJ19HITy/KCdFEQA "Husk – Try It Online") ### Explanation Pretty simple usage of `isanum` (`□`): ``` #(¬□) -- example: "Input!" #( ) -- count number of ( □) -- | is alphanumeric: [73,110,112,117,116,0] (¬ ) -- | not: [0,0,0,0,0,1] -- : 1 ``` [Answer] # [R](https://www.r-project.org/), ~~68~~ 42 bytes -26 bytes thanks to Giuseppe. ``` function(x)nchar(gsub('[[:alnum:]]',"",x)) ``` [Try it online!](https://tio.run/##FYtBC4IwGEDv/Qr9DLaBhlJYWB465alTESES6pxKcwu3hf36pe/4eG@0zDkFjmVG1LqXAk9E1F054laZCqM8T0ouzJAUBfIB/IkQyzBQw360jw/7bcR2X0Zb/eYL8czteb9kQLw0DVdzmjWcy/VDjpx6LyCzQmrDG9HqLqilEdoFt1dn/unKqxlwRQArckTLH4X2Dw "R – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) (easy) ``` žKмg ``` [Try it online.](https://tio.run/##MzBNTDJM/f//6D7vC3vS//9/tmdRiXFxydO10@sUAQ) **Explanation:** ``` žK # Push "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" м # Remove all occurrences of this second string from the input string g # Push and implicitly output the length of the result ``` --- # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) (hard) ``` žKмÇεDžy‹i1ë.²<5÷>н]O ``` Thanks to *@Mr.Xcoder* for helping me put two sub-solutions together with `D`, and explaining how `]` closes both the if-statement and foreach-loop. (I accidentally placed the `D` before the `ε` and used one `}` instead of two..) [Try it online.](https://tio.run/##ATYAyf8wNWFiMWX//8W@S9C8w4fOtUTFvnnigLlpMcOrLsKyPDXDtz7QvV1P///mvKJ0ZXN05a2XfiE) **Explanation:** ``` žK # "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" м # Remove all occurrences of this second string from the input string Ç # Convert each character to its unicode value εD # Foreach over this list i # If the current item ‹ # is maller than žy # 128 1 # Use 1 ë # Else .² # Use log_2 < # minus 1 5÷ # integer-divided by 5 > # plus 1 н # Take the head of the sublists ] # Close both the if-else and for-each (shorter version of `}}`) O # Sum everything together ``` 05AB1E doesn't have any builtins for knowing the amount of bytes a character costs, so I'm converting them to unicode values with `Ç` and use the following pseudo-code to determine their bytes: ``` if(unicodeValue < 128) return 1 else return log_2(unicodeValue-1)//5+1 # (where // is integer-division) ``` Pseudo-code inspired by [*@TheBikingViking*'s Python 3 answer](https://codegolf.stackexchange.com/a/83798/52210) for the [*Bytes/Characters* challenge](https://codegolf.stackexchange.com/questions/83673/bytes-character). [Answer] # MS-SQL, 85 bytes (easy) ``` SELECT SUM(1)FROM spt_values,t WHERE type='P'AND SUBSTRING(v,number,1)LIKE'[^a-z0-9]' ``` Handles strings up to 2047 characters. [Per our IO standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341), input is taken via a pre-existing table **t** with `varchar` field **v**. This must be run in the `master` database (which exists on every SQL server). This database has a system table `dbo.spt_values`, which, if we filter by `type='P'`, contains counting numbers from 0 to 2047. Join that to our input table to split each character into its own row, then count up those that match the `LIKE` filter (which supports character ranges). # MS-SQL, 85 bytes (hard) ``` SELECT SUM(2)FROM spt_values,t WHERE type='P'AND SUBSTRING(v,number,1)LIKE'[^a-z0-9]' ``` You also need to change the input table to an `nvarchar` field **v** instead of `varchar`. So yeah, this is kind of cheaty, because the [nvarchar data type uses 2 bytes for *every* character](https://docs.microsoft.com/en-us/sql/t-sql/data-types/nchar-and-nvarchar-transact-sql?view=sql-server-2017), even for normal ASCII characters. That means I don't have to distinguish between characters that *could* be stuffed into a single byte and those that can't. But it does strictly satisfy the challenge, since it reflects the number of bytes that SQL is actually using to store `nvarchar` strings. [Answer] # Javascript 1.8 ## easy (48 chars) `function f(s)(s.match(/[^a-z0-9]/gi)||[]).length` [Answer] ## PowerShell, easy, 44 ``` filter e{($args-replace"[a-z0-9]").Length} ``` If we stretch the definition of »arguments«, we can shorten it a bit more (**41**): ``` filter e{($_-replace"[`0a-z0-9]").Length} ``` but it then requires input to be sent via the pipeline. ## PowerShell, hard, 71 ``` function x{[text.encoding]::utf8.GetByteCount($args-replace'[a-z0-9]')} ``` Again, if we allow the pipeline we get it to **68**: ``` function x{[text.encoding]::utf8.GetByteCount($_-replace'[a-z0-9]')} ``` [Answer] # Scala ## Easy (43 chars) ``` def c(s:String)=s.count(!_.isLetterOrDigit) ``` ## Hard (58 chars) ``` def c(s:String)=s.filter(!_.isLetterOrDigit).getBytes.size ``` [Answer] # Python ## easy (39 chars) ``` f=lambda s:sum(1-i.isalpha()for i in s) ``` [Answer] # Brainfuck ## Easy (1397 chars) ``` >+[,[>+>+<<-]>>[<<+>>-]>-[<->+++++]<--->>>+<<<[>+>+<<-]>[<+>-]<<[>>+<<-]+>>>[>-]>[ <<<<->>[-]>>->]<+<<[>-[>-]>[<<<<->>[-]+>>->]<+<<-]>>>[-]<[-]<[-]<[-]<[-]<<[>>+>+<< <-]>>[<<+>>-]>>-[<<->>---------]>>+<<<[>+>+<<-]>[<+>-]<<[>>+<<-]+>>>[>-]>[<<<<->>[ -]>>->]<+<<[>-[>-]>[<<<<->>[-]+>>->]<+<<-]>>>[-]<[-]<[-]<[-]>----[<+>----]<++>>>+ <<<[>+>+<<-]>[<+>-]<<[>>+<<-]+>>>[>-]>[<<<<->>[-]>>->]<+<<[>-[>-]>[<<<<->>[-]+>>-> ]<+<<-]>>>[-]<[-]<[-]<[-]<[-]<<[>>>+<<<-]>>>[[-]<<[>>+<+<-]>[<+>-]>[<<<+>>>[-]]][- ]<[-]<[-]<<[>>>+<<<-]>>>[<<<->>>[-]]<<[>>+<+<-]>[<+>-]>[<<<[-]->>>[-]][-]<[-]<[-] <<[>>+>+<<<-]>>[<<+>>-]>>--[<<->>---]<<++++>>>>+<<<[>+>+<<-]>[<+>-]<<[>>+<<-]+>>> [>-]>[<<<<->>[-]>>->]<+<<[>-[>-]>[<<<<->>[-]+>>->]<+<<-]>>>[-]<[-]<[-]<[-]>--[<-> +++++]<----->>>+<<<[>+>+<<-]>[<+>-]<<[>>+<<-]+>>>[>-]>[<<<<->>[-]>>->]<+<<[>-[>-] >[<<<<->>[-]+>>->]<+<<-]>>>[-]<[-]<[-]<[-]<[-]<<[>>>+<<<-]>>>[[-]<<[>>+<+<-]>[<+> -]>[<<<+>>>[-]]][-]<[-]<[-]<<[>>>+<<<-]>>>[<<<->>>[-]]<<[>>+<+<-]>[<+>-]>[<<<[-]- >>>[-]][-]<[-]<[-]<<[>>+>+<<<-]>>[<<+>>-]>>----[<<+++>>--]>>+<<<[>+>+<<-]>[<+>-]<< [>>+<<-]+>>>[>-]>[<<<<->>[-]>>->]<+<<[>-[>-]>[<<<<->>[-]+>>->]<+<<-]>>>[-]<[-]<[-] <[-]<[-]<<[>>>+<<<-]>>>[<<<->>>[-]]<<[>>+<+<-]>[<+>-]>[<<<[-]->>>[-]][-]<[-]<[-]<[ <<+>>[-]]<----------]>--[<->+++++]<--<-[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>>>>>-[<->+++ ++]<---[<+>-]<.[-]++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>>>>>-[<->+++++]<---[<+ <+>>-]<.<. ``` All hand coded. It takes input until it gets a 0xA character signifying end of input (not counted). Only handles up to 255 nonalphanumeric input characters. [Answer] **Perl (easy) 27 characters** ``` sub _{$_=shift;(s/\W|_//g)} ``` **usage:** ``` say _('@abc_123ABC -("~ abc') ---> 8 ``` [Answer] **Ruby, easy, 32** ``` f=->s{s.scan(/[^a-z0-9]/i).size} ``` [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), Easy, 26 bytes ``` iEh$"0:A[a{"{16F@2k)S^|}~+ ``` [Try it online!](https://tio.run/##S8/PScsszvj/P9M1Q0XJwMoxOrFaqdrQzM3BKFszOK6mtk77/38FRSVlFVU1dQ1NLW0dXT19A0MjYxNTM3MLSytrG1s7ewdHJ2cXVzd3D08vbx9fP/@AwKDgkNCw8IjIqOiY2Lj4hMSk5JTUtPSMzKzsnNy8/ILCouKS0rLyisqqaqANAA "Gol><> – Try It Online") ### How it works ``` iEh$"0:A[a{"{16F@2k)S^|}~+ iEh Take input as char; if EOF, print the top as int and halt $ Move the input under the char counter "0:A[a{" Push six boundary chars {1 Pull the input to the top, and push 1 (XOR counter) (Stack: [char counter, ...boundary, input, XOR counter]) 6F | Repeat 6 times... @ Pull a boundary char to the top 2k) Copy the input char and compare (boundary > input) S^ XOR with the XOR counter (Stack: [char counter, input, XOR counter]) }~+ Move XOR counter to bottom, discard input, and add to the char counter Repeat indefinitely ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth) ## Easy, 17 bytes ``` l:z"[a-zA-Z0-9]"k ``` [Try it online!](https://tio.run/##K6gsyfj/P8eqSik6UbfKUTfKQNcyVin7/38FRSVlFVU1dQ1NLW0dXT19A0MjYxNTM3MLSytrG1s7ewdHJ2cXVzd3D08vbx9fP/@AwKDgkNCw8IjIqOiY2Lj4hMSk5JTUtPSMzKzsnNy8/ILCouKS0rLyisqq6praOgA) ## Hard, 30 bytes ``` /lsm.[\08.BCd:z"[a-zA-Z0-9]"k8 ``` [Try it online!](https://tio.run/##K6gsyfj/Xz@nOFcvOsbAQs/JOcWqSik6UbfKUTfKQNcyVinb4v//h/v3AgA) [Answer] # Java 10, 42 bytes (easy) ``` s->s.replaceAll("[A-Za-z0-9]","").length() ``` [Try it online.](https://tio.run/##dY5NigIxEIX3fYoyuEjABGFWgyj0AXSjK0WaGKNGY2y6SkGlvcbs3XsDrzNeo41/SzcF9ep99d5S77RcTleV8RoRutqFYwLgAtlipo2F3mN9CmB4nwoX5oCiFcUyiQNJkzPQgwBtqFB2UBU295FMvedslMqhloem/B2zBmNCeRvmtOCiaj3ofDvxkX4/2W3cFNaxwTtnNAYtXvH9PZJdq82WVB5P5AMPynB2u57JIv1f/k6nGhPPXt/dg4XDzNWzNBv8IH38ZVJWdw) **Explanation:** ``` s-> // Method with String parameter and integer return-type s.replaceAll("[A-Za-z0-9]","") // Remove all digits and letters .length() // And return the length ``` --- # Java 10, 102 bytes (hard) ``` s->{int r=0;for(var c:s.replaceAll("[A-Za-z0-9]","").split(""))r+=c.getBytes("utf8").length;return r;} ``` [Try it online.](https://tio.run/##fY@/TsMwEMb3PMVhMTiCWJVYACtIQWKkSztRVZFxncTFdSL7EihV@hrs7LwBrwOvERwoCwPL6f58d9/v1qITyXr1MEgjvIdboe0uAtAWlSuEVDAdy@8GSDpDp20JPgasXP3o4eZJqgZ1bXlQ9VEIHgVqCVOwkMLgk6vduOrSCS9qRzvhQF565lRjwvXMGEoWWXInkudJcrEkp4TEzDdGIw1Z7E5SyUqF11tUnpIWi/MwN8qWWHGnsHUWHO8HPjo37b0JzgeArtYr2IR3DtCLJYj4L/XPb7OtR7VhdYusCVI0llomKfl8fw22@PH2st8fBRr@r3peaZ/r4zzL52cef/V91A9f) **Explanation:** ``` s->{ // Method with String parameter and integer return-type int r=0; // Result-integer, starting at 0 for(var c:s.replaceAll("[A-Za-z0-9]","") // Remove all digits and letters .split("")) // And loop over the remaining characters r+= // Add to the result-sum: c.getBytes("utf8").length; // The UTF-8 bytes of the current character return r;} // Return the result-sum ``` [Answer] # [Haskell](https://www.haskell.org/), ~~58~~ 52 bytes (easy) -6 bytes, thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni?tab=profile) (inverting the test, using `elem` instead)! ``` f s=sum[1|c<-s,elem c":;<=>?@[\\]^_`"||c>'z'||c<'0'] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02h2La4NDfasCbZRrdYJzUnNVchWcnK2sbWzt4hOiYmNi4@QammJtlOvUodSNmoG6jH/s9NzMxTsFUoKMrMK1HQU0hTsLWxUUhPLXHOzytJzSsp/u8BNDtfRyE8vygnRREA "Haskell – Try It Online") ]
[Question] [ Write a program rotates some Cartesian coordinates through an angle about the origin (0.0,0.0). The angle and coordinates will be read from a single line of stdin in the following format: ``` angle x1,y1 x2,y2 x3,y3 ... ``` eg. ``` 3.14159265358979 1.0,0.0 0.0,1.0 1.0,1.0 0.0,0.0 ``` The results should be printed to stdout in the following format: ``` x1',y1' x2',y2' x3',y3' ... ``` eg. ``` -1.0,-3.23108510433268e-15 -3.23108510433268e-15,-1.0 -1.0,-1.0 -0.0,-0.0 ``` [Answer] # Perl, ~~112~~ ~~80~~ 78 ``` s/\S*//;$c=cos$&;$s=sin$&;s/([^ ,]*),(\S*)/($1*$c-$2*$s).",".($1*$s+$2*$c)/ge ``` Run on command-line as `perl -pe 'code here'`, `p` option counted in code size. For reference, here's my previous approach. But regexes are too damn powerful. ``` split/[ ,]/,<>;$_='A;Y,print$x*cos($a)-$y*sin$a,",",$x*sin($a)+$y*cos$a,$"whileX';s/[AXY]/\$\l$&=shift\@_/g;eval ``` [Answer] # C (124 Characters) ``` main(){double t,x,y,c,s;scanf("%lf",&t);c=cos(t);s=sin(t);while(~scanf("%lf,%lf",&x,&y))printf("%lf,%lf ",c*x-s*y,s*x+c*y);} ``` [Answer] # Python (157) ``` from math import*;f=float i=raw_input().split();a=f(i[0]) c=cos(a);s=sin(a) def p((x,y)):print"%f,%f"%(c*x-s*y,s*x+c*y), for l in i[1:]:p(map(f,l.split(','))) ``` [Answer] ## J, 58 (with one bug) ``` c=:charsub (r.@{.*}.)&.(".@('-_,j'&c :.('j,_-'&c))@stdin)_ ``` Sample run (note I've replaced the origin test case with some negative input, as that was actually a pain to get right with J's representation of negatives): ``` echo -n '3.14159265358979 1.0,0.0 0.0,1.0 1.0,1.0 -1.0,-1.0' | jconsole rotate.ijs -1,3.23109e-15 -3.23109e-15,-1 -1,-1 1,1 ``` There is one family of input that will not render exactly as asked (though calling it wrong would be debatable). Which one exactly is left as an exercise to the reader :-) [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 51 bytes ``` x←⎕⋄g←{(¯1 2⍴1↓x)×⍤1⊢⍵○⊃x}⋄∊⍉↑(⊂-/g⌽⍳2)⍪⊂',',¨+/g⍳2 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qKM97X/Fo7YJj/qmPupuSQeyqjUOrTdUMHrUu8XwUdvkCs3D0x/1LjF81LXoUe/WR9O7H3U1V9QClT7q6HrU2/mobaLGo64mXf30Rz17H/VuNtJ81LsKKKCuo65zaIU2UBgoBrLlP2cal7GeoYmhqaWRmamxqYWluaWCoZ6BjoGegQIQ6wDZYL4hlA/EAA "APL (Dyalog Extended) – Try It Online") Reduced by a lot with dzaima's help at [The APL Orchard.](https://chat.stackexchange.com/transcript/message/55704669#55704669) Apparently there's still room to save a few bytes, which I'll be golfing later. ## Explanation ``` x←⎕⋄g←{(¯1 2⍴1↓x)×⍤1⊢⍵○⊃x}⋄∊⍉↑(⊂-/g⌽⍳2)⍪⊂',',¨+/g⍳2 x←⎕ store input as x ⋄g←{ } define function g: ⊃x first element of x ⍵○ take sine & cosine of it based on argument ×⍤1⊢ multiply with each row of (¯1 2⍴1↓x) the points reshaped into pairs ⋄ finally, +/g⍳2 x sin theta + y cos theta ⊂',',¨ prepend comma to each ⍪ joined with (⊂-/g⌽⍳2) x cos theta - y sin theta ⍉↑ convert to matrix and transpose ∊ and enlist the elements ``` [Answer] # [Wolfram Mathematica](https://wolfram.com/mathematica), 35 bytes ``` RotationTransform@#[[1]]/@#~Drop~1& ``` OP's test case: ``` RotationTransform@#[[1]]/@#~Drop~1&@{3.14159265358979,{1.0,0.0},{0.0,1.0},{1.0,1.0},{0.0,0.0}} ``` > > {{-1., 3.23109\*10^-15}, {-3.23109\*10^-15, -1.}, {-1., -1.}, {0., 0.}} > > > If we instead use exact values, we can get an exact output: ``` RotationTransform@#[[1]]/@#~Drop~1&@{Pi,{1,0},{0,1},{1,1},{0,0}} ``` > > {{-1, 0}, {0, -1}, {-1, -1}, {0, 0}} > > > ]
[Question] [ # Objective Given two non-negative integers encoded in unbounded-length [Gray code](https://en.wikipedia.org/wiki/Gray_code), add them and output the result, where the result is also encoded in Gray code. # Gray code There are many equivalent formulations of Gray code, but here's an intuitive one. The Gray code encodes each non-negative integer as an infinite bit-string. Starting from encoding zero, as the enumeration goes, the least significant bit keeps cycling through `"0110"`. Each place of bit keeps cycling through what the previously significant bit cycles through, but doubled entry-wise. To summarize: ``` 0th LSB: Cycles through "0110" 1st LSB: Cycles through "00111100" 2nd LSB: Cycles through "0000111111110000" 3rd LSB: Cycles through "00000000111111111111111100000000" (And so on) ``` That gives the encodings of few non-negative integers as: ``` Integer = Gray code ("..." stands for infinitely many leading zeroes) 0 = "...00000" 1 = "...00001" 2 = "...00011" 3 = "...00010" 4 = "...00110" 5 = "...00111" 6 = "...00101" 7 = "...00100" 8 = "...01100" 9 = "...01101" ``` Note that, for each pair of integers differing by one, their Gray codes differ by only one bit. # I/O format Flexible. Standard loopholes apply. # Examples Here, inputs and outputs are Gray codes with their leading zeroes stripped off. ``` "" + "" = "" "1" + "1" = "11" "1" + "10" = "110" "10" + "1" = "110" "10" + "11" = "111" "111" + "111" = "1111" ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` ^\€ḄSH^$B ``` [Try it online!](https://tio.run/##y0rNyan8/z8u5lHTmoc7WoI94lSc/j/cuc/6UcMcBV07hUcNc60PtwMFVLgOtwPVRP7/Hx0dbRCrowAkQGS0IYg0RGbrKMCkQCwkWRhXRwEhAuZABcHisQA "Jelly – Try It Online") A monadic link taking a pair of lists of binary digits as its argument and returning a list of binary digits. Expects the Gray coding with all leading zeros removed other than for zero itself; returns a Gray coded number in the same format. ## Explanation ``` ^\€ | Reduce each by xor, collecting up intermediate results Ḅ | Convert from binary S | Sum H^$ | Xor with half B | Convert to binary digits ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 41 bytes ``` a=>b=>(t=e(a)+e(b))^t/2 e=t=>t&&t^e(t>>1) ``` [Try it online!](https://tio.run/##jcyxCoNAEITh3geRXUKMZ7/7EumFO7OKQW6DDnn9SzBdUhgYpvr47/EZt2GdHzhnv1kZpUTRJEoQo8gno8Tc49JVJhBFXaM3gmrgMnjefLFm8YlGavm9Bn7FOueJOubqC6TA@/2DDlPtzg5j4ZP7geUF "JavaScript (Node.js) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` €ηOÉJCOD;^b ``` Port of [*@NickKennedy*'s Jelly answer](https://codegolf.stackexchange.com/a/267311/52210), so make sure to upvote that answer as well! Input as a pair of lists of binary digits without leading 0s (where `0` could be either `[0]` or `[]`). [Try it online](https://tio.run/##yy9OTMpM/f//UdOac9v9D3d6Ofu7WMcl/f8fHW2oYxCrAyQNY2MB) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/R01rzm33P9zp5ezvYh2X9F/nf3R0dKxOdCwQRxsACQMwyxBIGCJYOlBRHQOEOIStA@OBWDpQOjYWAA). **Explanation:** ``` € # Map over each inner list of the (implicit) input-pair: η # Get its prefixes O # Sum each inner prefix-list É # Check for each sum whether it's odd J # Join each inner list of binary digits together to a string C # Convert each from a binary-string to a base-10 integer O # Sum the pair together D; # Push a copy of this sum, and halve it ^ # Bitwise-XOR the sum and halved sum together # (where both are treated as floored integers, ignoring any `.5` decimals) b # Convert this from a base-10 integer to a binary-string # (which is output implicitly as result) ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes ``` ≔⍘ΣEE²S↨²Eι﹪Σ…ι⊕첦²θ⭆θ¬⁼ι§⁺0θκ ``` [Try it online!](https://tio.run/##LYxBCoMwEEX3niK4mkAK6taVlS6ysAieIMSg0pioSUp7@tRJXQwf/p/35CwOaYWOsXFumQzchVODPxYzwRBW6MSWrmKEmy34a6KUEfzEHuflDDsGbRPUfqVW7WxTz4081KqMVyOsFMGK0isZ2Wmd9afSw9@Msp2Rp/Xw2IPQDhWN52ZUH@h1cJAXOWKMvJKmjrEsiqws4@2tfw "Charcoal – Try It Online") Link is to verbose version of code. Uses bit strings for I/O. Explanation: Somewhat limited by the lack of a bitwise XOR function. ``` ≔⍘ΣEE²S↨²Eι﹪Σ…ι⊕첦²θ ``` For each input, get all of its prefixes, take the digit sum modulo `2`, and interpret the results as base `2`. Then convert the sum back to base `2`. ``` ⭆θ¬⁼ι§⁺0θκ ``` Compare each bit with the previous and output `0` if they the same and `1` if they differ. ]
[Question] [ Define the (unnormalised) [Willmore energy](https://en.wikipedia.org/wiki/Willmore_energy) of a surface as the integral of squared mean curvature over it: $$W=\int\_SH^2\,dA$$ For surfaces topologically equivalent to a sphere \$W\ge4\pi\$, and \$W=4\pi\$ iff it is actually a sphere. Thus the energy quantifies how spherical a surface is. In September 2020 [I asked on MathsSE](https://math.stackexchange.com/q/3822237/357390) how to simplify the Willmore energy of an ellipsoid with semi-major axes \$a\ge b\ge c\ge0\$. Two days later I had done it myself: > > Define > $$A=a^2,B=b^2,C=c^2,\varphi=\cos^{-1}\frac ca$$ > $$g=\sqrt{(A-C)B},m=\frac{(B-C)A}{(A-C)B}$$ > Then > $$\color{red}{\begin{align}W=\frac\pi{3ABC}&\Big(C(5AB+2AC+2BC)\\ > &+2(AB+AC+BC)E(\varphi,m)g\\ > &+BC(AB+AC+2BC-A^2)F(\varphi,m)/g\Big)\end{align}}$$ > > > Here \$F\$ and \$E\$ are the [elliptic integrals](https://en.wikipedia.org/wiki/Elliptic_integral) of the first and second kinds respectively. (Note that as with all my elliptic integral/function answers on MathsSE the argument convention is as in Mathematica and mpmath, where \$m\$ is the *parameter*.) Later on I derived a much cleaner and order-agnostic formula in terms of [Carlson's symmetric integrals](https://dlmf.nist.gov/19.16) – \$A,B,C\$ keep their meanings: $$W=\frac\pi3\left(3+4\left(\frac1A+\frac1B+\frac1C\right)R\_G(AB,CA,BC)-(A+B+C)R\_F(AB,CA,BC)\right)$$ I was inspired to write this question after writing answers to the [ellipse perimeter](https://codegolf.stackexchange.com/a/257777/110698) and [ellipsoid surface area](https://codegolf.stackexchange.com/a/257775/110698) questions that use the symmetric integrals. In the former case it actually saves one byte over an answer using the classic formula. ## Task Given an ellipsoid's semi-axes \$a,b,c\$, which you may assume are sorted and positive, output the ellipsoid's Willmore energy with a relative error of at most \$10^{-3}\$. You may use either formula above or something else entirely like explicitly integrating the squared mean curvature. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); fewest bytes wins. ## Test cases ``` (1, 1, 1) 12.5663706143592 (2, 1, 1) 15.4516066443266 (2, 2, 1) 16.9023119660317 (3, 2, 1) 21.2244261324396 (2, 2, 2) 12.5663706143592 (6, 1, 1) 34.2162831541838 (6, 5, 1) 70.4793621781325 (13, 9, 6) 15.9643343585267 ``` [Answer] # JavaScript (ES6), 195 bytes Quite obviously not the right tool for the job, at least without any specialized library. The only math builtins used here are \$\sin\$, \$\cos\$ and \$\operatorname{hypot}\$. The precision can be improved by using a smaller increment (the \$i\$ in the code). The version below uses \$i=10^{-2}\$ so that it doesn't time-out on TIO. But as a result, the relative error is \$\approx10^{-1}\$. ``` with(Math)f=(a,b,c)=>{i=1e-2;for(F=G=p=0;S=sin(p+=i),P=S*i*i/12,p<PI;)for(q=0;q<2*PI;G+=P*Q)F+=P/(Q=hypot(a*b*S*cos(q+=i),c*a*S*sin(q),b*c*cos(p)));return(4/a/a+4/b/b+4/c/c)*G-(a*a+b*b+c*c)*F+PI} ``` [Try it online!](https://tio.run/##dYzdSsQwEEbvfZLMJDU2uxakO3vZshdClz5BElubZWnSHxURn72meydWBmb4zhy@i37Xkx1dmJPevzTL8uHmjj3ruYOWmBZGWKDjl6O0SVTe@pEVVFKgh7ymyfUscHIgKqrRoZOpEuFQnXJYxSFKw0FhzCWnCs9QxCPZmbrP4Gem0WCN1k9suJVY1DGvpQMIg/b2CgCQj838NvZsL7XUfC@NNHFbaQHLJNZobtDw6AMWvDp9L9b3k78291f/ylqWijgAd7@p@oeqDbrbpKur/tBsszcTjxs03YknkQEsPw "JavaScript (Node.js) – Try It Online") ### Formulas This is derived from the second formula given in the challenge and the following formulas [from this page](https://dlmf.nist.gov/19.23#E6_5) for Carlson's symmetric integrals: $$R\_F(x,y,z)=\frac{1}{4\pi}\int\_{0}^{2\pi}\int\_{0}^{\pi}\frac{\sin\theta\:d\theta\:d\phi}{(x\sin^2\theta\cos^2\phi+y\sin^2\theta\sin^2\phi+z\cos^2\theta)^{1/2}}$$ $$R\_G(x,y,z)=\frac{1}{4\pi}\int\_{0}^{2\pi}\int\_{0}^{\pi}(x\sin^2\theta\cos^2\phi+y\sin^2\theta\sin^2\phi+z\cos^2\theta)^{1/2}\sin\theta\:d\theta\:d\phi$$ [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 63 bytes -1 byte and fixed a bug thanks to [@att](https://codegolf.stackexchange.com/users/81203/att). ``` Pi/3(3.-Tr[s=#^2]CarlsonRF@@(t=##&@@s/s)+4Tr[1/s]CarlsonRG@@t)& ``` `CarlsonRG` and `CarlsonRF` are new functions in Mathematica 12.3, so this does not work on TIO. ]
[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/168450/edit). Closed 5 years ago. [Improve this question](/posts/168450/edit) Does anyone have any suggestions as to how I could shorten this program? ``` _=map(ord,raw_input());_=[10if y==88else 0if y==45else 58-_[x-1]if y==47else y-48for x,y in enumerate(_)];t=0;exec('t+=sum(_[:2+(_[0]+_[1]>=10)]);_=_[2-(_[0]==10):];'*10);print t ``` [Run it online](https://tio.run/##Lc3RCoMgGAXg@z2Fd9lK0mjLFe45BJGf2IwFy8KM5dO3im7O4Xw3Zwz@M9h8XUH0zYgH905d84POjrPHcVyDUIx2LQpCcG6@k0HnKm7HunECaiFMn1oeGkjB28GhJQ2os8jYuTeu8QZDrC9e0Nos5oUjn4hp7jGoKk@2pDoBxfRTMBrr/RpUTg4XO1W6jq5b16PrrEd@XWWZPYgknGfkLqXk7A8) I'd like to write a bowling calculator. I'm fairly proficient in python so I chose that language. The trick is that the input string is made up of frames not split by white-space and the spares, strikes, and misses are marked by `/`, `X`, and `-` respectively. (note that there are no `0` in the code, `-` is used instead) Here is an example line `X7/9-X-88/-6XXX81`, this line would have a score of `167`. As you can see, most of my characters are spent on mapping these special characters to their actual bowl scores. I do this by taking their `ord` values and then replacing the `X` and `-` with `10` and `0` respectively. I then find the `/` rolls and set their value as ten minus the previous roll. After this, I calculate the final game score by looping over 10 frames (the size of a line of bowling), chunking the line array based on if the frame was a strike spare or normal roll, and then reducing the array going forward. I feel like this is the best way to perform this challenge as a golf challenge, but I'm not sure if I'm reducing it enough. [Answer] # 1. The portion `2+(_[0]+_[1]>=10)` could be rewritten as `2+(_[0]+_[1]>9)` to save two bytes. In a similar vein `2-(_[0]==10)` can be rewritten as `2-(_[0]>9)`, since `10` is the only possible value greater than `9`. ``` a=map(ord,raw_input());a=[10if y==88else 0if y==45else 58-a[x-1]if y==47else y-48for x,y in enumerate(a)] t=0;exec('t+=sum(a[:2+(a[0]+a[1]>9)]);a=a[2-(a[0]>9):];'*10);print t ``` [Try it online!](https://tio.run/##Lc3RCoMgGIbh812FZ@lKyqhlhbsOQWT8bMaEZWHG6upbi04@eJ@Tb1zDe3D5toHoYcSDfyUevg/rxjlgQloQimW2Q6sQnJvPZNBZRXlUySmohTJ9anXoSgveDR4tyYqsQ8bNvfEQDAaiL0FkrVnME0chFtPcY1BNHu@b6RgU0/ea6P8xqJweukOj2@jKMtKO3rqAwrbJKq2ppJyn9Cal5OwH "Python 2 – Try It Online") (I also renamed `_` to `a`, because even though it's code-golf we don't have to make it unreadable) # 2. You can also use a dictionary instead of conditionals to saves some bytes. ``` a=raw_input();a=[{y:ord(y)-48,'X':10,'-':0,'/':58-ord(a[x-1])}[y]for x,y in enumerate(a)] t=0;exec('t+=sum(a[:2+(a[0]+a[1]>9)]);a=a[2-(a[0]>9):];'*10);print t ``` [Try it online!](https://tio.run/##HY3dCsIgAEbvewrv1DaZjn6cYs8hiISU0S7mhjmaRM9uWzfn4nwcvimn5xjaUpyK7n3twzQnhKVT5pPFGO8oY3LgNdRQMFpDAsXKBoojJ9vqzEKYxV@T7WOMYKkz6APwYR58dMkjh@0uKSr94m8Ipkq95mGNRFutpLZyhtlLh@326ExL/nYVwkq4ZxTLKfYhgVSKPjcd0YTzhpy01pz9AA "Python 2 – Try It Online") # 3. Don't `enumerate`. `enumerate` tends to be too long for it's own good. Here you want to get the last character, which can better be acheived with a `zip`. ``` a=raw_input();a=[{y:ord(y)-48,'X':10,'-':0,'/':58-ord(x)}[y]for x,y in zip('-'+a,a)] t=0;exec('t+=sum(a[:2+(a[0]+a[1]>9)]);a=a[2-(a[0]>9):];'*10);print t ``` [Try it online!](https://tio.run/##HY3dCsIgAEbvewrv1FTmRj/OYc8hiITUIi9yYo5m0bOvrZtzcb4DXyz5PoRmnp1K7nX2IY4Z4c4p8ylySFdUMNsJCjWUNaeQQbmwgnIv2LpO@GuKvQ0JTLQAH8DbR7RUxFGH7SYr3vVTf0EwE/UcH8gZ2ZCF3BJnantqsV3PnGnY3y5C2g5ua467mHzIIM@zPlYt00yIih201qL@AQ "Python 2 – Try It Online") --- If you combine this with @user202729's two tips you get 149 bytes. ``` a=raw_input();a=[[10,0,58-ord(x),ord(y)-48]['X-/'.find(y)]for x,y in zip('-'+a,a)] t=0;exec't+=sum(a[:2+(a[0]+a[1]>9)]);a=a[2-(a[0]>9):];'*10;print t ``` [Try it online!](https://tio.run/##Hc1LDsIgAEXRuatgBliw0PihJbgOEkIM0TYykBKksXXz2Dp5NzmTF5f8HENTilPJfW4@xCkjLJ0yhjPCyEnQMT3QjMmWBdOjsAZqWsPD4MMmdhgTmMkCfABfHxGksHLEYbvLisl@7u8wV@o9vZAzXVOty2zlDLfXFtvtyZmG/nWFzkq450zG5EMGuRR9qVuqqRA1PWutBf8B "Python 2 – Try It Online") --- Here's another version that is also 149 bytes: ``` a=raw_input();a=[['-123456789X'.find(y),58-ord(x)][y=='/']for x,y in zip('-'+a,a)] t=0;exec't+=sum(a[:2+(a[0]+a[1]>9)]);a=a[2-(a[0]>9):];'*10;print t ``` [Try it online!](https://tio.run/##Hc3BDoIgHIDxe0/h7Q8pKZaKOnoONsYaS10cQka4pJc36/IdfpfPxfCYbbltmnv9vhnrloBwr7mUQGh5vlR1w1oBp8nYAUWcVYzMfkArVjJyDjmoafbJmsXE2ORjHAICqc40VofAi35cxzuElL@WJ9KyK9O9hUq1pOraYvU7aVmSv@7QqR6OtOidNzYkYdtEk7dEEMZyUgshGP0C "Python 2 – Try It Online") [Answer] # 146 bytes Based on Cat Wizard's ["another version"](https://codegolf.stackexchange.com/revisions/168451/6). Basically I include `/` into the string so `find` returns `0` (falsy value), then use `or` to replace that `0` with the desired result. ``` a=raw_input();a=[('/-123456789X'.find(y)or 59-ord(x))-1for x,y in zip('-'+a,a)] t=0;exec't+=sum(a[:2+(a[0]+a[1]>9)]);a=a[2-(a[0]>9):];'*10;print t ``` [Try it online!](https://tio.run/##HY1LDsIgFAD3noIdIMUWtP/Uc5AQYl5sG1lICdLYevla3Uwysxm/xsfk5LZBF@B9s87PkdAWOk1wyoU8X/KirGqFT6N1PVnpFFBe8yn0ZKGUi3H3JVmRdehjPcEcM0iAmkPssnZYhjuOrHvNTwK6kWxnZhhoYa41Nb8NaMn/dQ@NafFRZK0P1kUUt02Vac0Vr6qUF0qpSnwB "Python 2 – Try It Online") Explanation: `x or y` == `x if x else y`. So: ``` '/-123456789X'.find(y)or 59-ord(x) == '/-123456789X'.find(y) if '/-123456789X'.find(y) else 59-ord(x) == '/-123456789X'.find(y) if '/-123456789X'.find(y) != 0 else 59-ord(x) == '/-123456789X'.find(y) if y != '/' else 59-ord(x) ``` [Answer] # Shorten the conditional using `str.find` Compare: ``` Mine: [10,0,58-_[x-1],y-48]['X-/'.find(chr(y))] Mine (char): [10,0,58-ord(a[x-1]),ord(y)-48]['X-/'.find(y)] WW's: {y:ord(y)-48,'X':10,'-':0,'/':58-ord(a[x-1])}[y] Original: 10if y==88else 0if y==45else 58-_[x-1]if y==47else y-48 ``` [Answer] # Remove `()` around parameter of `exec` `exec` is a command, not a function. This saves 2 bytes. [Answer] Is there a reason why you need to use `raw_input()` and not replace it with `input()` and wrap the input string in quotes e.g. "X7/9-X-88/-6XXX81"? That would save 4. ]
[Question] [ This question is similar to [Do the circles overlap?](https://codegolf.stackexchange.com/questions/135960/do-the-circles-overlap), except your program should return True if the circumference of one circle intersects the other, and false if they do not. If they touch, this is considered an intersection. Note that concentric circles only intersect when both radii are equal Input is two x, y coordinates for the circle centres and two radius lengths, as either 6 floats or ints, in any order, and output a boolean value, (you may print True or False if you choose) test cases are in format (x1, y1 x2, y2, r1, r2): these inputs should output true: ``` 0 0 2 2 2 2 1 1 1 5 2 2 0.55 0.57 1.97 2.24 1.97 2.12 ``` these should output false: ``` 0 0 0 1 5 3 0 0 5 5 2 2 1.57 3.29 4.45 6.67 1.09 3.25 ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 20 bytes Uses [Anders Kaseorg's formula](https://codegolf.stackexchange.com/a/136009/43319): 0≤(*x*₁​−*x*₂)²​−(*r*₁​−*r*₂)²+(*y*₁​−*y*₂)²≤4​*r*₁*r*₂ Takes (*x*₁, *r*₁, *y*₁) as left argument and (*x*₂, *r*₂, *y*₂) as right argument. ``` (-/2*⍨-)(≤∧0≤⊣)4×2⊃× ``` [Try it online!](https://tio.run/##ZVDBTsMwDL33K3xsEQ1JVrcqH4DEnR@oWMWQqnVqUqk7IyGYNInbTpxAgv/Yn@RHiu0K6CBR7Pg9@8VOtWnS5bZq2rtxvF77unP1rQ@PL3F6Yc/C/jNN4vD8Hp4@NLvdW5IdDzbsHo6HcQz713gw57A1MFhydDoKO5tcRtFEEkB0Eg@WYMpIhPCr2tVwv9703oFbtX2zhLb3FILv@nqqNkBrAbIysTkbK1fkDM03PWVMTmqQ6/7y@GtZwcoLCgtYKFtCpjKEXOUFGKVLxlB6gBtpR1ONhp/voYh2ZMiaGcoxRlohkkpZgGb5Gc2YVYZKlc0m@auqcaKPJ/qa5jb/XkXRl6a/uyxntMzAncsgXw "APL (Dyalog Unicode) – Try It Online") The overall function's structure is a fork (3-train) where the tines are `-/2*⍨-` and `≤∧0≤⊣` and `4×2⊃×`\*. The middle tine takes the results of the side tines as arguments. The side tines use the overall function's arguments. Right tine: `×` multiply the arguments (*x*₁*x*₂, *r*₁*r*₂, *y*₁*y*₂) `2⊃` pick the second element (*r*₁*r*₂) `4×` multiply by four (4​*r*₁*r*₂) Left tine: `-` subtract the arguments (*x*₁​−*x*₂, *r*₁​−*r*₂, *y*₁​−*y*₂) `2*⍨` square ((*x*₁​−*x*₂)², (*r*₁​−*r*₂)², (*y*₁​−*y*₂)²) `-/` minus reduction i.e. alternate sum\* ((*x*₁​−*x*₂)²​−((*r*₁​−*r*₂)²​−(*y*₁​−*y*₂)²)) Now we use these results as arguments to the middle tine: `0≤⊣` is the left argument greater than or equal to zero `∧` and `≤` the left argument smaller than or equal to the right argument? --- \* due to APL's right associativity [Answer] # Mathematica 67 bytes This checks whether the area of the intersection of two disks is positive. ``` RegionMeasure@RegionIntersection[{#,#2}~Disk~#3,{#4,#5}~Disk~#6]>0& ``` [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 17 bytes ``` (+/∧.≥+⍨)⎕,|0j1⊥⎕ ``` [Try it online!](https://tio.run/##RUtBCsIwELzvK/ao1K5J2m3Ic0olUilU6EnwrFVQvPiEou/aj8QELTLMMjM7U@@7fHOou36bN109DG0T5P5sezk9FMh49mGRrWV8kVymTG7vZfyujmqn5TpFGWIleFCo0KCBRPCgMYFnq4gZ47GoyVk0ZEr4Kf0tYIIGxmK2/J/rtCzIOCypZKyosjFTLmX8AQ "APL (Dyalog Classic) – Try It Online") expects two lines of input: `x1 y1 x2 y2` and `r1 r2` `⎕` read and evaluate a line `0j1` imaginary constant i=sqrt(-1) `0j1⊥` decode from base-i, thus computing: i3x1 + i2y1 + i1x2 + i0y2 = -i x1 - y1 + ix2 + y2 = i(x2-x1) + (y2-y1) `|` magnitude of that complex number, i.e. distance between the two points `⎕,` read the two radii and prepend them, so we have a list of 3 reals `(+/∧.≥+⍨)` flat-tolerant triangle inequality: the sum (`+/`) must be greater than or equal to (`≥`) the double of each side (`+⍨`), and all these results must be true (`∧.`) [Answer] # [Python 3](https://docs.python.org/3/), ~~56~~ 55 bytes ``` lambda X,Y,x,y,R,r:0<=(X-x)**2+(Y-y)**2-(R-r)**2<=4*r*R ``` [Try it online!](https://tio.run/##bU1RC8IgGHzvV/io9inO6cKYf8KnDXpZxCioNWQP89ebM1bEguM47o67MUzX51DG3p7ivXucLx1qoIUZAjjwR1Fb3LCZUCr3uGVhEQw75hdRW0U9dXH0t2HCPRaAEuQHhOzWqAD0ht5EgutkJj6kAjeJJZfqq4ufcr4Q61S5ifS/iyKPl1waQIqrVKh4le@Eyb4mJL4A "Python 3 – Try It Online") [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), 20 bytes ``` ~@- 2?@@- 2?+@@+2?>! ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/v85BV8HI3gFMajs4aBvZ2yn@/2@ka6Rraq@tYKRgpGsMonWN7I204BSYARMFAA "GolfScript – Try It Online") Takes arguments in the following form `r1 r2 x1 y1 x2 y2` Implements the formula below ![(x2 - x1)^2 + (y2 - y1)^2 <= (r1 + r2)^2](https://i.stack.imgur.com/Nh4x4.gif) GolfScript **Does not** inherently support floating point types. See this post for more details about passing floats <https://codegolf.stackexchange.com/a/26553> My original intention was to use GolfScript's zip and fold operations. # [GolfScript](http://www.golfscript.com/golfscript/), 26 bytes ``` 1:a;~zip{{a*+2?-1:a;}*}/+> ``` [Try it online!](https://tio.run/##S8/PSStOLsosKPn/39Aq0bquKrOgujpRS9vIXhfEr9Wq1de2@68cHV2kUKFQGQulYv9HRxsqGCkYx0abKJgqmMXGAgA "GolfScript – Try It Online") [Answer] # JavaScript, 52 bytes ``` (X,Y,x,y,R,r)=>4*r*R/((X-x)**2+(Y-y)**2-(R-r)**2)>=1 ``` Some how Based on [Anders Kaseorg Python solution](https://codegolf.stackexchange.com/a/136009/44718) [Answer] # [Scala](http://www.scala-lang.org/), 59 bytes **This might be golfable.** ``` val u=(a-x)*(a-x)+(b-y)*(b-y) (q-r)*(q-r)<=u&u<=(q+r)*(q+r) ``` [Try it online!](https://tio.run/##bY5LCoMwFEXHdRUPByVWhag4EVNo6bSLiJqCJcRviiKu3SZWK4hcuBxCDvc1KeV0KpI3S1t40lwA61omsgZuZTkYp4y9IBctqxv1AdHoUciEMydZoVuhX6FeoVrAiu5FwRkVZJg@lIMkiLqddZnbRonbK9ZtoMqtFeuOiTzLmKDKnl9UT6NhlLW6hQtkYsDgL3GvYNrbjdjBjv@LZW2GBzrhkeE5OuHe0Bt4doKjDTw7wd4Ijzf0//C/MU5f "Scala – Try It Online") # [Scala](http://www.scala-lang.org/), 66 bytes I do like this one, but sadly the previous was shorter. I hate Scala for forcing defining parameter type... ``` var p=math.pow(_:Double,2) val u=p(a-x)+p(b-y) p(q-r)<=u&u<=p(q+r) ``` [Try it online!](https://tio.run/##bY7RCoIwFIav21McuogNNZbhTWRQdNszxDEXGWubU8uInt20XEHIf/PB@T/@UxxQYqOTsziUsMNMgahLodIC1sY8yCgVR8hUKWzRFigutrpKpPATB7WDuwPrIO@BLTZaS4EqfjRXtGDiC5anqdE3unfdkJErSqhiQzGomWdoEtwZMTQPLFvG1aRatqfcs6x5EmJs@5JUdMyBQ9gnWMHY@73Kfe6HnzD2M2bQJRoyZn6X6N/oNvjbmQ9t8Lcz/zei4Y2uH303ns0L "Scala – Try It Online") ]
[Question] [ Given a number `n`, you must output a [golden spiral](http://en.wikipedia.org/wiki/Golden_spiral) with the number of quarter turns being `n`. The spiral must be completely black and the background must be completely white. This must be output as a φ⌊n/4⌋\*4 by φ⌊n/4⌋\*4 PNG file (you may output a PPM and convert it later). The shortest code wins. The radius of the smallest quarter turn should be φ-3. In geometry, a golden spiral is a logarithmic spiral whose growth factor is φ, the golden ratio.That is, a golden spiral gets wider (or further from its origin) by a factor of φ for every quarter turn it makes. [Answer] ## Mathematica, 169 bytes All those annoying options. :( ``` f=Export[p=GoldenRatio;"a.png",ParametricPlot[p^(2t-3){Cos[a=t*Pi],Sin@a},{t,0,#/2},PlotRange->{r={m=-p^(#-3),-m},r},PlotStyle->Black,Axes->1<0,ImageSize->p^#~Floor~4]]& ``` This function saves the spiral to `a.png` in wherever your current working directory is. The result of `f[9]`: ![enter image description here](https://i.stack.imgur.com/fJbki.png) The result of `f[12]`: ![enter image description here](https://i.stack.imgur.com/2JRGP.png) I hope I understood all the bits about the scaling correctly. There's not a whole lot to say about the code. I'm using `ParametricPlot` to draw curve as a parameterised function in `t` which advances by `1/2` for each quarter turn. The rest is done in the options: * `PlotRange->{r={m=-p^(#-3),-m},r}` makes sure we have an square aspect ratio which *just* covers the outermost point of the spiral. * `PlotStyle->Black` overwrites Mathematica's blue default colour. * `Axes->1<0` is just `Axes->False` (and turns off the axes, who knew!). * `ImageSize->p^#~Floor~4` sets the correct dimensions in pixels, by noticing that `⌊n/4⌋*4` just means "`n` rounded down to the nearest multiple of `4`". [Answer] # Python 3 - 290 269 This will get crushed by any kind of built-in parametrics, but I figured I'd post it as an example of a point-by-point solution. Edit: Thanks for the golfing tips! If you have any more, please make them. ``` from math import * from PIL import Image as I, ImageDraw as D n=eval(input()) G=(1+5**.5)/2 w=int(G**(4*(n//4))) i=I.new("RGB",(w,w),"white") d=D.Draw(i) k=pi/180 d.line([(G**(j/90)*cos(j*k)+w/2,G**(j/90)*sin(j*k)+w/2)for j in range(n*90)],fill=0) i.save("s.png","PNG") ``` ]
[Question] [ # Penalty shootout Welcome to CG world cup. Your job: Code a penalty shooter and goal keeper! --- ## Rules of the game: The goal is 700 cm wide and 200 cm tall. If I have to make a rectangle out of it, the goal is ABCD where A is `(0,0)`, B is `(0,200)`, C is `(700,200)`, D is `(700,0)`. The shooter gives me the coordinate where he will aim. However... there is wind, so your ball final destination may be modified up to 50 positive or negative. Here's what I'm trying to say... ``` windX= randint(-50,50) windY= randint(-50,50) theFinalCoordinateOfTheBallX= coordinateThatBotGiveX + windX theFinalCoordinateOfTheBally= coordinateThatBotGivey + windY ``` The goal keeper gives me the coordinate where he aims. If the distance of the ball final coordinate and the coordinate of the goal keeper is less then 50 cm (using Pythagoras), the ball is saved by the keeper, otherwise it's a goal. (Note: It is very possible that you did not make a goal, because you MISS the goal. This is possible due to the wind factor. So aiming for (0,0) is not really good idea.) Each of you has 10 attempts to become goal keeper and shooter. --- ## Communication protocol: You will receive this from STDIN > > R Sx Sy Gx Gy > > > `R`-> Round # (Starts from 1 to 10) `Sx` -> The x coordinate where the opponent aim when they shoot in previous round (Seperated by comma) `Sy` -> The y coordinate where the opponent aim when they shoot in previous round (Seperated by comma) `Gx` -> The x coordinate where the oppenent aim when they are goal keeper in the previous round (Seperated by comma) `Gy` -> The y coordinate where the opponent aim when they are goal keeper in previous round (Seperated by comma) Example: > > 3 57,81 29,90 101,50 27,85 > > > Meaning This is round 3 In round 1: When your opponent is shooter: He aims for `(57,29)`. In round 2 he aims for `(81,90)` In round 1: When your opponent is goal keeper. He aims for (101,27). In round 2 he aims for `(50,85)` Another example: > > 1 > > > This is round 1 No game yet! Prepare your bot for this kind of situation! Your bot, must give me from STDOUT this: > > Sx Sy Gx Gy > > > `Sx` -> My x coordinate of where do I aim when I'm the shooter this round. `Sy` -> My y coordinate of where do I aim when I'm the shooter this round. `Gx` -> My x coordinate of where do I am when I'm the goal keeper this round. `Gy` -> My y coordinate of where do I am when I'm the goal keeper this round. Example: > > 81 25 71 98 > > > This means you aim for `(81,25)` when shooting and `(71,98)` when become goal keeper. ### All numbers that you will receive is integer. Your program must output integer too. Floating number is not tolerated --- ## Deciding champion: Win worths 3 points. Draw worths 1 point. Lost is a null. After single-round robin, The 4 top high scoring bot will do double-round robin. Among this 4 bots, the champion will be crowned. --- ## Technical details: The program runs on Windows 7, using Python 2.7.2 Unfortunately, due to my programming skill, I can only receive entry from Python and C. (To Java users, my deepest apology) I'm confident that I can accept entry from C++ and Fortran. I will try when someone gives me a submission in that language... C programs will be compiled *manually* using this command: > > gcc programFile.c -o programFile > > > The same thing occurs to Fortran and C++, but since I haven't try, I'm not sure what precisely is the command. Note: Since using Python 2.7.2, you may want to use `raw_input` instead of `input` Your program may not use/modify/access external source. (Internet, environment variable, making file, accessing folder, external number, etc) ## Your program must be deterministic, and please dont over kill random() =p You may make multiples entry, but please dont help each other.. Make sure you give your bot a name... --- ## FAQ: > > Q: Is goals inclusive or exclusive? > > > A: **Inclusive.** So if your ball lands at `(0,0)` and it's out of the goal keeper's reach, it's counts as a goal. (Well irl, it will hit the post) > > Q: What is the time limit? > > > A: **1 second** > > Q: What happened if my ball ends at (x,-y) > > > A: **No goal** Well, irl you cant aim downwards below the ground. > > Q: But can my program outputs negative number? > > > A: **Absolutely** > > Q: Any controllers so I can train my bot? > > > A: **[Here](https://github.com/KerenzaDoxolodeo/PenaltyShootoutCodeGolf)** > > Q: Does my program run 'on and off' or it will keep running until it gets and EOF? > > > A: **On and off** On a new round, I will call your bot and pass the necessary info. After you gave my your coordinate, it's done job. --- Good luck, you will need it.. [Answer] ## RandomBot, Python ``` from random import seed,randint seed(raw_input()) print "%d %d %d %d" % (randint(50,650), randint(50,150), randint(50,650), randint(50,150)) ``` As long as there are no predictable bots to beat, I believe this should be fairly optimal (of course, you could just seed the PRNG yourself to figure out what I'll be doing, but writing a bot to specifically kill one other bot isn't exactly sportsmanship, right? ;)). Obviously, this isn't good at catching, but without anyone to beat, I can't tell how to predict them. [Answer] ## Center, Python This bot acts just as I would: It stays in the center when being the goal keeper (jumping is hard), and when shooting it does the exact opposite: it aims for one of the corners. It doesn't care what happened in previous rounds and thus is a good victim for bots that do take this information into consideration. ``` import random random.seed(raw_input()) corners = [[50,50],[50,150],[650,50],[650,150]] corner = random.choice(corners) print "%d %d %d %d" % (corner[0], corner[1], 350, 100) ``` [Answer] ## Averager (Python) This is my second serious answer on this site and my first KOTH. Be kind, good sirs. Yes. The code looks pretty. ``` rl = lambda l: map(int, l.split(",")) avg = lambda l: sum(l)/len(l) def take_input(): r = raw_input() t = True if len(r.split()) == 1 else False (rno, sx, sy, gx, gy) = (r,'0','0','0','0') if t else r.split() return (int(rno),) + tuple(map(rl, [sx, sy, gx, gy])) def g(d): return((avg(d[1]) + 350)/2, (avg(d[2]) + 100)/2) def s(d): return (abs((avg(d[3]) - 350)/2), abs((avg(d[4]) - 100)/2)) def out(d): print "%d %d %d %d" % (s(d) + g(d)) out(take_input()) ``` Halp and tast k? [Answer] ## CenteredRandom (Python) ``` from random import randint, seed, choice rl = lambda l: map(int, l.split(",")) avg = lambda l: sum(l)/len(l) avg2 = lambda l, x: avg(l[:-x]) if x < len(l) else avg(l) corners = choice([[50,50],[50,150],[650,50],[650,150]]) def take_input(): r = raw_input() seed(r) t = True if len(r.split()) == 1 else False (rno, sx, sy, gx, gy) = (r,'0','0','0','0') if t else r.split() return (int(rno),) + tuple(map(rl, [sx, sy, gx, gy])) def enemy_is_center(d): return len(d[3]) > 2 and len(d[4]) > 2 and d[3][-2:] == [350, 350] and d[4][-2:] == [100, 100] def s(d): return (100,100) if enemy_is_center(d) else (randint(50, 650), randint(50, 150)) def g(d): return (corners[0], corners[1]) if enemy_is_center(d) else (randint(50, 650), randint(50, 150)) def out(d): print "%d %d %d %d" % (s(d) + g(d)) out(take_input()) ``` ]
[Question] [ The objective of this question is to create a program that pushes your computer's internal fan speed to its maximum RPM. Upon exiting the program, your fan should return to the normal operating RPM. **Rules:** 1. You may not perform a CPU intensive task in order to modify the fan's speed. 2. Exiting the program may be via user input, a timeout period, or a response to a `SIGTERM` or `SIGEXIT` signal. 3. Avoid [the standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/10844). [Answer] # OSX + Bash + [smcFanControl](https://github.com/hholtmann/smcFanControl), 91 bytes This relies on the third-party [smcFanControl](https://github.com/hholtmann/smcFanControl) suite to do the hard work **and is therefore more of a proof-of-concept** than a serious answer. **Real** answers could pick apart the smcFanControl source code and do this without third-party help. [smcFanControl.app](http://www.conscius.de/smcfancontrol_2_2_2.zip) is assumed to be installed in `/Applications`. ``` p=/Ap*/smcFan*/C*/R*/smc\ -k # Path to CLI utility f()($p'FS! ' -w000$1) # function to set fan mode f 3 # Set fan speeds to "forced" mode eval $p\ F{0,1}"Tg -w5DC0;" # Set fan 1 and 2 to 6000 RPM target speed read # wait for keyboard input f 0 # Return fans to "auto" mode ``` Comments added for explanation, but not included in score. [Answer] # GLXGEARS - 8bytes First thing I thought of was `yes`, or `yes` in parallel. As we are not allowed to use the CPU to control the speed, let's use the GPU: ``` glxgears ``` [Answer] # Reboot, 6 bytes ``` reboot ``` Just after a boot, the fans start spinning at max rpm because the power is turned on to the fan, before the BIOS loads any real time controllers that will base the speed of the fan on the temperature of the processor. This also keeps the processor from getting excessively hot if you were to try the alternative... which would be to keep the fan off until those controllers were loaded and basing the fan speed on processor temp. More of a safeguard than anything. The processor is starting to work the moment you turn the computer on, but the BIOS still needs time to load. <https://superuser.com/a/427723/246895> (Does not work on every pc, but is confirm the OP) ]
[Question] [ Given a string, mark which parts in the string repeat in box brackets, and write how many times it does so before the box. Example:`st st st Hello ThereThere` `st`(with a space after) repeats 3 times, `There` repeats 2 times, and `l` repeats 2 times in `Hello`, so the output will be: `3[st ]He2[l]o 2[There]` There is no space between `[st ]` and `Hello` because the space in the string is being taken up by the repeating part. `[st ]`, 3 times with a `Hello` after it would be `st st st Hello`, which is what the string has. Other examples: `st Hello st st Bye` -> `st He2[l]o 2[st ]Bye` `Bookkeeper` -> `B2[o]2[k]2[e]per` `/\/\/\\\\\\\\/\/\/` -> `3[/\]6[\]3[\/]` Shortestest code wins. EDIT: To clarify the choice of selections, choose the **largest possible** repeating section, and try and leave as little non-repeating characters as possible. Do not nest boxed-in sections. [Answer] ## Perl, 36 bytes ``` #!perl -p s!(.+)\1+!@{[$&=~/\Q$1/g]}."[$1]"!eg ``` [Try it online!](https://tio.run/##K0gtyjH9/79YUUNPWzPGUFvRoTpaRc22Tj8mUMVQPz22Vk8pWsUwVkkxNR2oqkQBgjxSc3LyFUIyUotSwQSXU35@dnZqakFqERdcGqLUqTL1X35BSWZ@XvF/3QIA "Perl 5 – Try It Online") --- ## PHP 5.6, 68 bytes Same code in PHP. Requires the command line option `-F`, and relies on deprecated `/e` modifier. ``` <?=preg_filter('/(.+)\1+/e','substr_count("\0","\1")."[\1]"',$argn); ``` [Answer] ## scala, 102 chars ``` print("(?!\\s)(.+)\\1+".r.replaceAllIn(readLine,m=>m.matched.size/m.group(1).size+"["+m.group(1)+"]")) ``` **Output** ``` st st st Hello ThereThere -> 3[st ]He2[l]o 2[There] st Hello st st Bye -> st He2[l]o 2[st ]Bye Bookkeeper -> B2[o]2[k]2[e]per /\/\/\\\\\\\\/\/\/ -> 3[/\]2[\\\]3[\/] ``` [Answer] ## C, 224 205 203 199 195 193 chars The string is given as program parameter. As usual, use double quotes if your string contains spaces, and for empty strings - calling the program without any parameter crashes, but calling with `""` works. Output for test cases is: ``` st st st Hello ThereThere => 3[st ]He2[l]o 2[There] Bookkeeper => B2[o]2[k]2[e]per /\/\/\\\\\\\\/\/\/ => 3[/\]2[\\\]3[\/] ``` which looks correct to me regarding "choose the largest possible repeating section". Code: ``` l,r,f,i;char*c;main(a,b)char**b;{l=strlen(c=b[1]);for(;putchar(*c);c++)for(a=l;--a;f=0)for(r=a;!f;r+=a){for(i=0;i<a;)f|=r>l||c[i]-c[r+i++];if(f*r>a)c[a]=0,printf("\b%i[%s]",r/a,c),c+=r-1,a=1;}} ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~40~~ ~~37~~ 24 bytes ``` (.+)(\1)+ $.($#2*__)[$1] ``` -13 bytes thanks to *@Neil*. [Try it online](https://tio.run/##K0otycxLNPz/X0NPW1MjxlBTm0tFT0NF2UgrPl4zWsUw9v//4hIFCPJIzcnJVwjJSC1KBRMA) or [verify all test cases](https://tio.run/##K0otycxLNPyvquGe8F9DT1tTI8ZQU5tLRU9DRdlIKz5eM1rFMPb//@ISBQjySM3JyVcIyUgtSgUTXHAxiLxTZSqXU35@dnZqakFqEZd@DAhCAZjDlZiUnJKaBkTpGZnIbAA). (NOTE: Slightly different results for some test cases in comparison to the challenge description, but still the same as the accepted answer, so I assumed both are valid.) **Explanation:** ``` (.+)(\1)+ # Look for the repeated sections (where the repeated string is captured in # group 1, and every time it's repeated in group 2) ``` Example: in the input `"st st st Hello ThereThere"` it will find the capture group 1 and 2 as: `"st "` & `["st ","st "]`; `"l"` & `["l"]`; and `"There"` & `["There"]` respectively. ``` $#2 # Get the amount of times group 2 was repeated *_ # Converted to unary (that amount of '_') _ # + 1 (with an additional '_' added) $.( ) # Convert that unary back to a number again by taking the length [$1] # And append the match of the first capture group between block-quotes # after the number ``` Example: `"st st st "` will become `"3[st ]"`; `"ll"` will becomes `"2[l]"`; and `"ThereThere"` will become `"2[There]"`. So `"st st st Hello ThereThere"` is now the intended result `"3[st ]He2[l]o 2[There]"` (which is output implicitly). [Answer] # [Perl 5](https://www.perl.org/) `-p`, 41 bytes ``` s|(.+)\1+|(length($&)/length$1)."[$1]"|ge ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4RkNPWzPGULtGIyc1L70kQ0NFTVMfwlQx1NRTilYxjFWqSU8FKi1RgCCP1JycfIWQjNSiVDDB5ZSfn52dmlqQWsQFl4YodapM/ZdfUJKZn1f8X7cAAA "Perl 5 – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 82 bytes ``` [regex]::Replace($args,'(.+)\1+',{$a,$g=$args|% gr* "$($a.Length/$g.Length)[$g]"}) ``` [Try it online!](https://tio.run/##TZBPa8MgGIfv@RQS7Iyra1hyCxRGTj3sNHYzMkr7zkDCzDRjHWk@e/aqXZj/0Iffo/IO5husa6HvF/pO9mRapAUNF1VVLzD0xxNk9Gi1EyzbbXnzuGViokdB9T7g64Zoe5@kFFO7Z/jQY5tTfdtxSbVKZ77MSfKUJQSbyJgbSRwHfNSQ1xYshIUJVkrk6gCF7JUhhQxcMf7PjVa8of5BiUQalEIiVoGvTm1M1wEMYH22LqRRhexwgvJszeWN77cWDj5fyrzBLCJVyib3f@HkSjZkCh51gsJlgNMIZ6wefYvUgvvqRwR3WFTqAvQ1ivwBPleJV3/pNJmXXw "PowerShell – 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/2291/edit). Closed 1 year ago. [Improve this question](/posts/2291/edit) Write a program that calculates amicable numbers, starting from [0,0], intil the maximum value for an integer is reached in the language you chose to write it in. Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive integer divisor other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.) A pair of amicable numbers constitutes an aliquot sequence of period 2. A related concept is that of a perfect number, which is a number which equals the sum of its own proper divisors, in other words a number which forms an aliquot sequence of period 1. Numbers that are members of an aliquot sequence with period greater than 2 are known as sociable numbers. For example, the smallest pair of amicable numbers is (220, 284); for the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110, of which the sum is 284; and the proper divisors of 284 are 1, 2, 4, 71, and 142, of which the sum is 220. If you want more information on amicable numbers, here's a link to [Wikipedia's entry](http://en.wikipedia.org/wiki/Amicable_number) on the subject. NOTE: It cannot use pre-determined tables of which are and which are not amicable numbers EDIT: I suppose I should have said how I will determine the winner: Your score will be calculated by this formula: `Total_characters_of_code / Up_votes = Score` I will select an answer on Sunday, May 1. The lowest score wins! [Answer] ## Golfscript (51 50 chars) ``` 2{.{:a,(\{.a\%!*+}/}:^~1$>{..^^={[..^](\p}*}*).}do ``` The core is the override of `^` as `:a,(\{.a\%!*+}/` which finds the aliquot of the number on the top of the stack (call it `n`) by the grossly inefficient approach of considering every number from `1` to `n-1` to see whether it's a factor. [Answer] # C (gcc), 162, 158, 146, 138 chars ``` s(n){int x=1,i=2;for(;i<=sqrt(n);++i)if(n%i==0)x+=i+n/i;return x;}main(i,a){for(;;)a=s(i),((a>i)?s(a):0)==i++?printf("%d,%d\n",i-1,a):0;} ``` compile with gcc using `gcc amic.c -o amic -lm -include math.h` To shorten it any further I suspect the algorithm would have to change. *Edits:* 162->158: Consolidated the variable `b` into the printf conditional. 158->146: Utilized main to declare `a` instead of using a global var, also using implicit `int` of the parameter *and* return type for the function `s(n)` 146->138: Add Lowjacker's suggestion of removing the cast to double. Thanks! [Answer] ### Scala (120 chars): ``` def d(n:Int)=(1 to n-1).filter(n%_==0) def i(x:Int,y:Int)=x!=y&&d(y).sum==x (1 to Int.MaxValue).filter(x=>i(x,d(x).sum)) ``` [Answer] ## Ruby 1.9, 126 124 Not quite a serious answer, but it's *theoretically* correct. If you're *really* patient, and have *lots* of RAM, it should eventually print every pair of amicable numbers. ``` s=->n{eval (1...n).select{|i|n%i==0}*?+} i=0 loop{Thread.new(i+=1){|j,k=j|loop{s[k+=1]==j&&s[j]==k&&printf("%d,%d\n",j,k)}}} ``` ]
[Question] [ I found this task [here](http://www.spoj.pl/SHORTEN/problems/FIBSUM/). > > Given the ith (1<=i<=35) Fibonacci > number F(i) calculate the sum of the > ith till i+9th number > F(i)+F(i+1)+...+F(i+9) and the last > digit of the i+246th one F(i+246) > > > I have been trying to solve this using python and some tricks(Binnet's formula and a tricky recurrence): ``` f=lambda n:((1+5**.5)**n-(1-5**.5)**n)/(2**n*5**.5) exec"n=input();print int(55*f(n)+88*f(n+1)+f(n+6)%10);"*input() ``` but I didn't yet managed to squeeze thought the give source code limit which is 111 and mine is 115,any hints how to improve my solution? I am a rather newbie to python so any sort of help resulting in a successful solution will be much appreciated. Thanks, PS:After posting the same question in [stackoverflow](https://stackoverflow.com/questions/5565845/sum-of-fibonacci-numbers) I thought that this should be more appropriate here as this site is precisely for Puzzles and Codegolf. [Answer] # GolfScript 28 26 characters Since the problem is here we might as well golf it. Anyone who plan on participating on spoj.pl better close their eyes while they read this. ``` ~](;{11.@5+{.@+}*;.10%+n}% ``` It basically says: For all input, start with the numbers 11 and 11, do input+5 Fibonacci iterations, discard the highest of the two results, add itself mod 10 to the lowest result, done. As a formula this can be describes as `11*Fib(input+6) + (11*Fib(input+6)) mod 10`. Why does this work? It is simply a condensed way of calculating two second identities in the same run, one could start at [0 1] and [55 89], do a run on both of the same length and subtract the first result from the second to get the sum of a series of 10 Fibonacci numbers, but one may as well do the subtraction on the initial sets, thus getting the set [55 88], that can be stepped back a few steps to [11 11] which is short to write. The Fibonacci series mod 10 has a period of 60, so `Fib(i+246) mod 10 = Fib(i+6) mod 10`. [Answer] # Python, 99 98 93 characters ``` F=[0,1] exec'F+=[F[-2]+F[-1]];'*300 exec'G=F[input():];print sum(G[:10])+G[246]%10;'*input() ``` [Answer] # Perl, 78 ``` sub F{$c=shift;$c>1?F($c-2)+F($c-1):$c}$_=<>;$x=F($_+11)-F($_+1);print$x+$x%10 ``` This makes use of my observation that * the sum of `F(i)` to `F(i+9)` is equal to `F(i+11) − F(i+1)` — proof: ``` F(i) + F(i+1) + F(i+2) + F(i+3) + F(i+4) + F(i+5) + F(i+6) + F(i+7) + F(i+8) + F(i+9) = F(i+2) + F(i+4) + F(i+6) + F(i+8) + F(i+10) = F(i+2) - F(i+3) + F(i+5) + F(i+6) + F(i+8) + F(i+10) = -F(i+1) + F(i+7) + F(i+8) + F(i+10) = -F(i+1) + F(i+9) + F(i+10) = -F(i+1) + F(i+11) ``` * `F(i+246) mod 10` is equal to `(F(i+11) − F(i+1)) mod 10` (discovered by experimentation; no idea how to prove this) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 31Sb+ÅfƤ+ ``` Port of [*@Timwi*'s Perl answer](https://codegolf.stackexchange.com/a/2007/52210), so make sure to upvote him as well! [Try it online](https://tio.run/##yy9OTMpM/f/f2DA4Sftwa9rhtkNLtP//twAA) or [verify the first \$[0,n]\$ test cases](https://tio.run/##yy9OTMpM/X9skp@9ksKjtkkKSvZ@/40Ng5O0D7emHW47tET7v85/QwMA). A straight-forward implementation would be **11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)** instead: ``` 9ÝƵ‘ª+Åf`θO ``` [Try it online](https://tio.run/##AR0A4v9vc2FiaWX//znDnca14oCYwqorw4VmYM64T///OA) or [verify the first \$[0,n]\$ test cases](https://tio.run/##ASwA0/9vc2FiaWX/xpJOPyIg4oaSICI/Tv85w53GteKAmMKqK8OFZmDOuE//LP8xMA). **Explanation:** ``` 31S # Push 31 as a list of digits: [3,1] b # Convert both to a binary string: [11,1] + # Add each to the (implicit) input-integer: [i+11,i+1] Åf # Get the n'th Fibonacci number for each: [F(i+11),F(i+1)] Æ # Reduce the pair by subtracting: F(i+11)-F(i+1) ¤ # Get its last digit (without popping) + # And add it to the result # (after which it is output implicitly) 9Ý # Push a list in the range [0,9]: [0,1,2,3,4,5,6,7,8,9] Ƶ‘ # Push compressed integer 246 ª # Append it to the list: [0,1,2,3,4,5,6,7,8,9,246] + # Add each to the (implicit) input-integer: # [i,i+1,i+2,i+3,i+4,i+5,i+6,i+7,i+8,i+9,i+246] Åf # Get the n'th Fibonacci number for each ` # Pop the list, and push all values separated to the stack θ # Pop the last number (the F(i+246)), and only leave its last digit O # Sum all values on the stack # (after which the resulting sum is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ƶ‘` is `246`. ]
[Question] [ It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, [visit the help center](/help/reopen-questions). Closed 12 years ago. # The Setup --- [Here you can find the full text of *The Tragedy of Macbeth*](http://shakespeare.mit.edu/macbeth/full.html). If you view the source, and save it as text, you will notice it comes out to 206,244 total characters (including the whitespace at the end of the html). # The Challenge --- Write a program which compresses the text linked above into the smallest possible text file which can then reproduce the original text **exactly** (including the whitespace). # The Rules --- Your program cannot have any prior knowledge of the text it is compressing. The goal however is still to compress this specific text, so don't worry if it sucks at other text as long as it does the best job possible on *Macbeth*. The program must take either "compress" or "decompress" as the first parameter and the text file as the second command line parameter. The compressed output has to be a text file, and it has to be UTF16. The compressed output when decompressed must match exactly the original file in a character for character comparison. The program needs to finish in a reasonable amount of time. If it takes longer than a few seconds, please list the average running time with your submission. # The Scoring --- The only score is the number of characters in the compressed output. The score only counts if the decompress matches the original in a character for character comparison. [Answer] ## Pseudo-code, compresses Macbeth to 0 bytes Counter-example (yeah, almost joke) submission intended to point out the flaws with the question. (the C# was a bit long both in source size and resulting output) ``` if argument is "compress" compare entire input file to the Tragedy of Macbeth if equal, then output empty file else if input is non-empty, then RLE-encode input stream on chr(127) only and output that else [if input is empty] then RLE-encode a string of zero times chr(127) else if argument is "decompress" if input is empty then output the Tragedy of Macbeth else RLE-decode input file on chr(127) only and output back ``` With this approach, Macbeth is brought down to as short a file as possible. Other text input is usually passed untouched, at worst gains a byte per chr(127) which tend not to occur in actual text. [Answer] **Python, compresses to 40,304 bytes.** Similar to Mark's answer, but uses bzip2 instead of zlib (usually better for plain text.) ``` import bz2 as z,sys;print getattr(z,sys.argv[2])(open(sys.argv[1]).read()) ``` Call like so: ``` python macbeth.py macbeth.txt compress > macbeth-compressed.txt python macbeth.py macbeth.txt uncompress > macbeth-uncompressed.txt ``` Results: ``` thomas@jupiter:~$ python macbeth.py macbeth.txt compress | wc -c 40304 ``` [Answer] # C#, 1 byte compressed I've hardly ever used C#'s file manipulation capabilities, so I'll try not to screw this up too badly: ``` class Program { //args[0]: "compress" = compress mode, anything else = extract mode //args[1]: filename of source //args[2]: filename of target static void Main(string[] args) { byte[] info; using (FileStream fs = File.Open(args[1], FileMode.Open)) { //read the source file info = new byte[fs.Length]; fs.Read(info, 0, (int)fs.Length); } byte[] macbeth; using (WebClient client = new WebClient()) { //get the real MacBeth macbeth = client.DownloadData(@"http://shakespeare.mit.edu/macbeth/full.html"); } if (args[0] == "compress") { //is this also MacBeth? if (Encoding.Default.GetString(macbeth).Equals(Encoding.Default.GetString(info), StringComparison.Ordinal)) { //yep, write a dot using (FileStream fsOut = File.Create(args[2])) { byte[] infoOut = new UTF8Encoding(true).GetBytes("."); fsOut.Write(infoOut, 0, infoOut.Length); } } else { //nope, better just copy it File.Copy(args[1], args[2]; } } else { //is it a dot? if (info.Length == 1 && info[0] == Convert.ToByte(".")) { //yep, write MacBeth using (FileStream fsOut = File.Create(args[2])) { fsOut.Write(macbeth, 0, macbeth.Length); } } else { //nope! just copy the file File.Copy(args[1], args[2]); } } } } ``` Compresses MacBeth *all the way down to a single byte.* While admittedly cheesy, this is **technically** within the rules (I checked). [If it's good enough for Jon Skeet](https://stackoverflow.com/questions/284797/hello-world-in-less-than-20-bytes/284898#284898), it's good enough for me. Holy smoke, talk about a tiny file size, huh? And it's lossless! I'm going to make a million dollars. ]
[Question] [ One of your acquaintances has a hobby of making make-shift electrical gadgets using various types of batteries. However, since they're thrifty, they want to use as few batteries as possible for their projects. This challenge uses several types of batteries; your job is to output the fewest number of batteries that will output a given voltage when chained together. ### The batteries you'll be using Here are the types of batteries you will be using, along with their ID numbers (I assigned those for this challenge) and their output voltages: 1. AA 1.5V 2. Button battery 3V 3. Li-ion battery 3.7V 4. 9V battery 9V 5. Car battery 12V Batteries can also be half-charged, meaning that their voltage is half of what it is fully charged (I've removed any batteries who's half-voltages are the voltages of any full batteries): 6. ½ AA .75V 7. ½ Li-ion 1.85V 8. ½ 9V battery 4.5V 9. ½ Car battery 6V ### The rules * Input `i` must be a float where `1 ≤ i ≤ 100`, and where `i` has 1 or 2 decimal digits. * Output must be a list of the *fewest number* of battery ID numbers (as listed above) that, when combined, will output the voltage, **or** an empty list (or any other empty value) if the voltage can't be produced using the above batteries. Alternatively, the list can consist of the *voltages* of the batteries used; however, the voltages **must** correspond with one of the batteries above. Here are some test cases (the numbers aren't very large right now because of the time it takes to run the code for large numbers): ``` input: 1.5 output: [1.5] input: 2 output: [] or None input: 7.5 output: [6, 1.5] input: 15 output: [12, 3] ``` This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so the fewest bytes wins! [Answer] # [JavaScript (Node.js)](https://nodejs.org), 98 bytes ``` f=(v,s=[],...y)=>s[v*7|0]?'':eval(s)+v?f(v,...y,...[1.5,3,3.7,9,12,.75,1.85,4.5,6].map(e=>s+-e)):s ``` [Try it online!](https://tio.run/##bcxBDoIwEIXhvRehI8OECgXFVA5CWDTYGg1SYk0TE@9e2626mcWX/81NeeWmx3V9Fos96xCMZB6dHEYkohfIkxv8tn2XY59lnfZqZg5y35tYpSCdgZPACitq8YB8h9QK5LQXWEdvRrqrlen4KC80QOfCcTPZxdlZ02wvzLA4B/jG@h@W1PwiT2H4AA "JavaScript (Node.js) – Try It Online") Return voltages splitted by `-` ``` f=(v,s=[],...y)=> // s,...y as testing buffer s[v*7|0]?'': // The longest outputLength/input case, -0.75, need *6.67 eval(s)+v? // not equal? f( // continue v, ...y, ...[1.5,3,3.7,9,12,.75,1.85,4.5,6].map(e=>s+-e)) :s ``` [Answer] # [Python](https://www.python.org), ~~170~~ 169 bytes ``` from itertools import* f=lambda i:next(filter(None,(next((x for x in product([1.5,3,3.75,9,12,.75,1.85,4.5,6],repeat=n)if sum(x)==i),0)for n in range(int(i/.75)+2))),()) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NY47DoJAEIZ7T7HljI4oKIomXMELGAuUXZ0EdskyJHgWGxpNPJK3EXx0f_5XvtujusrF2a67N2KmyetpvCsVi_biXFErLivnZTwyaZGVxzxTvLW6FTBc9B3YOasJPg60yjivWsVWVd7lzUlgHwYxLWgRrGPaUBjRIMIgiWnZB6sDeV3pTFKLbFTdlNBimjLSHIcrO1z5zJ41sBXgWb_GSYSIBIhf4B_3n_8N) 10 bytes could be saved by replacing `range(int(i/.75)+2)` with `range(41)`, but then it may not find the correct solution if `i>30`. I prefer the longer version, since it is correct for any (numeric) input. Note: it is *extremely* inefficient, but it eventually terminates for every input. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 25 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` •UyмµñFb₃^•₅в20/₃иæé.ΔOQ ``` Outputs a list of the voltages of the batteries, and `-1` if it can't find a result. [(Don't) try it online.](https://tio.run/##yy9OTMpM/f//UcOi0MoLew5tPbzRLelRU3McUOBRU@uFTUYG@kDuhR2Hlx1eqXduin/g///GAA) (Will time out for all test cases.) If we remove the `é` it can be somewhat tested, but it won't output the required shortest result anymore: [try it online](https://tio.run/##yy9OTMpM/f//UcOi0MoLew5tPbzRLelRU3McUOBRU@uFTUYG@kDuhR2Hl@mdm@If@P@/oQEA). (And might still time-out.) And with only `•UyмµñFb₃^•₅в20/₃иæ` we can see all the possible powerset lists: [try it online](https://tio.run/##yy9OTMpM/f//UcOi0MoLew5tPbzRLelRU3McUOBRU@uFTUYG@kDuhR2Hl/3/DwA). **Explanation:** ``` •UyмµñFb₃^• # Push compressed integer 540570253786318174620 ₅в # Convert it to base-255 as list: [30,60,74,180,240,15,37,90,120] 20/ # Divide each by 20: [1.5,3,3.7,9,12,0.75,1.85,4.5,6] ₃и # Cycle-repeat this list 95 times # (95 is the lowest 1-byte constant above 40, which is required to # reach the maximum to support input 30 with the lowest voltage 0.75) æ # Pop and push its powerset é # Sort it by length .Δ # Find the first inner list which is truthy for: # (or -1 if none were truthy) O # Sum the list Q # Check if it's equal to the (implicit) input-float # (after which the result is output implicitly) ``` [See this 05AB1E tip (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/questions/96361/tips-for-golfing-in-05ab1e) to understand why `•UyмµñFb₃^•` is `540570253786318174620` and `•UyмµñFb₃^•₅в` is `[30,60,74,180,240,15,37,90,120]`. [Answer] # [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 126 bytes Recursive brute-force solution. Throws exception if no solution is found. ``` lambda n:(g:=lambda i,s=0,l=[]:[l]*(s==i)if s>=i else[b[0]for a in[12,9,6,4.5,3.7,3,1.85,1.5,.75]if(b:=g(i,s+a,l+[a]))])(n)[0] ``` [Try it online!](https://tio.run/##PczBagMhFAXQdfIVbzfavAyZTm0SwfyIdeG0On1gdVALDSHfPjVQurlwuZezXOtniuNpyatXb2uwX9OHhSjZLNVfISzqgEFpI3UwT6woRZw8lIsicKE4PemD8SlD@0Y9POMZX/GlFzj2Rxxx6E@ihcD@KAx5Nkk1s4buLIadtoZzw1nkzVgfCDUEso2zYwMOgsvtpuarXDLFynx3ozvsL3DzjPi949uN@3l3S/3fY4KSwnelFOHBtX/H118 "Python 3.8 (pre-release) – Try It Online") [Answer] # [Python 3 (PyPy)](http://pypy.org/), 95 bytes Returns a singleton list containing the solution. Based on [friddo's answer](https://codegolf.stackexchange.com/a/245689/64121). ``` f=lambda i,*l:sum([f(i,*l,ord(b)/20)for b in'ð´xZJ<% '],[])[:1]if i>sum(l)else[l][sum(l)>i:] ``` [Try it online!](https://tio.run/##Jc0xDoIwFMbx3cUbmLc07TMlCsalUQ7gEWw6QKD6klKagoncysET6MEqxO37hl/@YRrvvT9kYQpTSvbsqq5uKiC5dWp4dEJbsWzZx0bUuCv2aPsINZDn39fn/bxeTmyz5kZqg1rlhixQuUCHrRta7Yz@v5KUSYul2UKs/K0VucyPqFYAIZIfBWdFA1kJbODAYO7CHEfE9AM "Python 3 (PyPy) – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 29 bytes ``` » 3J↔kṫ₅uR»₈τ20/41ẋfṗÞṡ'∑⁰=;h ``` [Don't try it online!](https://vyxal.pythonanywhere.com/#WyJUIiwiIiwiwrsgM0rihpRr4bmr4oKFdVLCu+KCiM+EMjAvNDHhuotm4bmXw57huaEn4oiR4oGwPTtoIiwiIiwiMTAiXQ==) (it times out) Add `vøḋ` to the end if it can't be returned as list of rationals instead of decimals. `vøḋ` will return a list of strings, tho. Returns `0` if it can't find a solution. You can somewhat test it without the `Þṡ`, but it won't return the optimal answer: [Try it Online!](https://vyxal.pythonanywhere.com/#WyJUIiwiIiwiwrsgM0rihpRr4bmr4oKFdVLCu+KCiM+EMjAvNDHhuotm4bmXJ+KIkeKBsD07aCIsIiIsIjEwIl0=) **Extremely** slow. Port of 05AB1E. ## How? ``` » 3J↔kṫ₅uR» # Push compressed integer 557746805944978070136 ₈τ # Convert to base 256: [30, 60, 74, 180, 240, 15, 37, 90, 120] 20/ # Divide each by 20: [1.5, 3.0, 3.7, 9.0, 12.0, 0.75, 1.85, 4.5, 6.0] 41ẋ # Repeat that list 41 times: [[1.5, 3.0, ...], [1.5, 3.0, ...], ...] f # Flatten it: [1.5, 3.0, ..., 1.5, 3.0, ..., ...] ṗ # Powerset Þṡ # Sort by length (this is what slows it down so much) ' ; # Filter for: ∑⁰= # The sum of this list is equal to the input h # Get the first item ``` ]
[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/200821/edit). Closed 3 years ago. [Improve this question](/posts/200821/edit) ## **There are 5 different "special characters": % & # $ !** These special characters are in a string with numbers. Like so: "5 ! 60%2$5.3" **(valid)**. You must determine the validity of the string and there are certain rules in order to determine validity of the string. **Rules:** * These special characters can exist in a string, however they cannot be next to each other (ignoring spaces). For example: + "!%" is **invalid** + "% %" is **invalid** + "# % $" is **invalid** * The *only exception* to the rule above is with the exclamation mark. Only one exclamation mark may be after another special character. These assume there are numbers before and after the special characters. For example: + "!!" is **valid** + "!!!" is **invalid** + "$!" is **valid** + "$!!" is **invalid** + "!$" is **invalid** * If a special character is at the end of the string, there MUST be a number after it (ignoring spaces). If a special character is at the start of the string, there MUST be a number before it. For example: + "5!" is **invalid** + "5!5" is **valid** + "5#!5" is **valid** + "%5" is **invalid** * The *only exception* to the rule above is with the exclamation mark. There does not need to be a number before the exclamation mark assuming there is a number after it. For example: + "!5" is **valid** + ”!!5" is **invalid** + "5!!5” is **valid** * If there is a string with only numbers, that string is valid, if there is a space between the space is invalid. For example: + "2 5" is **invalid** + "25" is **valid** * If a string only contains operators it is automatically invalid. For example: + "!#%" is **invalid** + "#" is **invalid** ## **Extra Examples of Strings that are VALID** * "5%!5" * "!5 !5 %!5" * "5.4 $ 2.9 !3.4 &! 89.8213" ## **Extra Examples of Strings that are INVALID** * "5%%5" **(reason: two "%%")** * "!5!!!!!!!!%%%5" **(reason: way too many operators next to each other)** * "!5 !5 !" **(reason: no number after the last "!")** * "2.0%" **(reason: no number after "%")** * "!6.9#" **(reason: no number after "#")** * "$6.9&" **(reason: no number after "#" AND no number before "$")** A number is a run of 0-9 digits with a possible . to indicate decimals. **You can assume you will only get a string with either numbers and/or these special characters inside. You can also assume the numbers will not have floating zeros like 9.000 or 0004 or 00.00. Treat a single zero as any other number, so for example 0$0 is valid. You can assume you won't receive an empty string.** Game winning criteria objective: code-golf (If you want a more difficult challenge try using python3 without using eval or exec.) This was originally planned. [Answer] # [Raku](https://github.com/nxadm/rakudo-pkg), 41 bytes ``` {?/^[\s*\!?\s*\d+\.?\d*\s*]+%<[%&#$!]>$/} ``` [Try it online!](https://tio.run/##LYvNCoMwEITveYpdzOagsLaxEYXWPIixpaBCwf5gTlL67GlCOwzDNzDzmtalDvcN1AwnCG9bnnvnc4c25Vg4tm7MIw8FHXtSmcShk@Un@OsGnE4dyAvMzxWW22PywRAagQaiExk@gATNLWAVUSE0LTd6XwlDlIb4F/1q@qHQvCOBNbeZkDHVFw "Perl 6 – Try It Online") Checks if the input matches against a regex. ### Explanation: ``` {?/^ $/} # Check if the input is [ ]+ # A series of \!? # An optional ! followed by \d+\.?\d* # A number \s* \s* \s* # Interspersed with optional whitespace % # Joined by <[ ]> # Any of %&#! # The special characters ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~46~~ ~~45~~ ~~44~~ 43 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Commands) [*Crossed out `&nbsp;44&nbsp;` is no longer 44 :)*](https://codegolf.stackexchange.com/questions/170188/crossed-out-44-is-still-regular-44) ``` þ'.ªžQ7£`)5L.Þ:DÔƵKå≠s2K¤s¬4%s•8мZ_r•₄вå≠`P ``` -2 bytes thanks to *@ExpiredData*. Outputs `1` for truthy and `0` or a positive integer for falsey (NOTE: only `1` is truthy in 05AB1E, so [this is completely fine with the truthy/falsey definition of the meta](https://codegolf.meta.stackexchange.com/a/2194/52210)). [Try it online](https://tio.run/##yy9OTMpM/f//8D51vUOrju4LND@0OEHT1Efv8Dwrl8NTjm31Prz0UeeCYiPvQ0uKD60xUS1@1LDI4sKeqPgiIONRU8uFTWAFCQH//5vqmSioKBjpWSooGgOZaooKFpZ6FkaGxgA) or [verify all test cases](https://tio.run/##LY2/SgNBEIf7eYqZ3E4kIENu9zbepUljFwttRUgipLASXBAOLEQkYCvWIv5pxEpIF1LcYeo8w73IOXfJMMx@@5tlv@swu7ya13e3@aiD1eIZO6O8LtcHUnz/rc@Oio9pLw/@RMrX4XH5slmOy6/q6S3YcfEZip@EQ3X/nm5X55MbherhcfvbPpie1oe9i9oj4aDP1nhx4MmDj3RoW0VuEbUb8pKgQSsZklPsEqaZpDZ2QJSCkzgBbCveHRqDISAGRoYIGY1GTaahURmwalAVka7Vxo2N9sW7ayMnsNJnoIFkERidXXCtwYP@@A8). **Explanation:** Unfortunately 05AB1E doesn't have any regexes. So instead I'll: Convert the input to something that's easier to work with: ``` þ # Only leave the digits of the (implicit) input-string '.ª '# Convert the number to a list of digits, and append a "." to this list žQ # Push a constant with all printable ASCII characters (range [32,126]) 7£ # Only leave the first 7: ' !"#$%&' ` # Push them all separated to the stack ) # Wrap everything on the stack into a list 5L # Push a list [1,2,3,4,5] .Þ # Extend the trailing item infinitely: [1,2,3,4,5,5,5,...] : # Replace all characters in the (implicit) input-string with these # We now have a number consisting only of the digits [1,2,3,5], # where 1 is a digit or "."; 2 are spaces; 3 is "!"; and 4 is one of "%&#$" # i.e. "5.4 $ 2.9 !3.4 &! 89.8213" → 1112521112311125321111111 ``` After which it's easier to check whether it complies to all the rules: Rule 5: check that there are no two numbers with spaces in between: ``` D # Duplicate the number Ô # Connected uniquify them (i.e. 1112521112311125321111111 → 1252123125321) ƵK # Push compressed integer 121 å≠ # And check that the number does NOT contains 121 as substring ``` Remove all spaces. And then rules 3 and 4: check that the input ends with a digit, and starts with a `"!"` or digit: ``` s # Swap to get the number at the top again 2K # Remove all 2s (the spaces) ¤ # Push the last digit (without popping the number itself) s # Swap again ¬ # And push the first digit (without popping the number itself) 4% # And take modulo 4, so 1 remains 1, and 5 becomes 1 ``` Rules 1 and 2: check that it does not contain `"!S"`/`"!!"`/`"!!!"`/`S!!` (where `S` is one of the special characters `"%&#$"`): ``` s # Swap to get the number at the top again •8мZ_r• # Push compressed integer 35055333533 ₄в # Convert it to base-1000 as list: [35,55,333,533] å≠ # Check for each that the number does NOT contain it as substring ` # And push all four checks separated to the stack ``` And finally check if all were truthy: ``` P # Then take the product of all values on the stack # (after which this is output implicitly as result) ``` [See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `ƵK` is `121`; `•8мZ_r•` is `35055333533`; and `•8мZ_r•₄в` is `[35,55,333,533]`. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 72 bytes ``` $_=!/^[%#&\$]|^!!|([%#&!\$]\s*){3}|[%#!&\$]\s\*[%#&\$]|\d\s+\d|\D$/&&/\d/ ``` [Try it online!](https://tio.run/##PYvLCsIwEEX38xUzNAk@MNHUkXbhzr8w1k1dCMUW687468aJUuFyuYc5M1zuHaekzntyzVEXJqhTbIjiLAMJhXExf5avKEzmx5MX2jAuQxvDQTljXGhdSqw1A2uUJibCKRkxB7xda6CdrQtQ0kbs/zUvtltU6G2NVMo0hFVtK78poQCPDF7k78O7Hx7X/jam1dB9AA "Perl 5 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 103 bytes A function that does nothing if the string is valid, and raises `SyntaxError` if the string is invalid. ``` import re r=re.sub def f(s):exec(r("[%&#$!]","+",s)+";1or["+r(" ","",r("!","*",r("[%&#$]",",",s)))+"]") ``` [Try it online!](https://tio.run/##XY7BboMwDIbveQonkAoGilpYqsLUHfcEu1U9dMWokdqAknQrT88ctl2WQ/z7/z/LHqdwGWw9z@Y2Di6AQ@b2DpW/f7AOe@gzn7f4wHPmMnGQqyTlR1GKQpQ@L8TLZnAHUVAEZIqSBCfxtKiFjnAZ4Zzwo8j/9vjJs35w4MHY2CgfOmNbRsYeYufMmOWQ0EG34RPB4hdcjUU4BQgXBLQdg@AmmlhupDI6Y0PmS7F/hXd3R0EmPs44hvZf@na6eopnDRy2a1mlWtWMa1ZppiVVToGGqLR6hhQq1QCvSa447Bq1qzY1gTKC/PfJnzbOcVaptWR8q5qEpfR/Aw "Python 3 – Try It Online") ## Explanation The idea is to exploit Python `eval` or `exec`, which can check if a string is a syntactically valid Python expression. This approach is longer than simply using regex to check, but I'll still post it since it's rather interesting. Given a string, I want to transform it in a way such that only valid strings map to syntactically valid Python expressions. Specifically, I want to keep the numbers unchanged, and map the 5 special characters to Python operators. Unfortunately, I wasn't able to find a simple mapping that works. Instead, I have to use 2 different transformations: **1) Replace all special characters with `+`.** For example `!1.2 $ 3.4 &! 56.78` becomes `+1.2 + 3.4 ++ 56.78`. If the result is valid Python, then the original string satisfies the last 2 rules (there must be at least 1 number, at least 1 operator between 2 numbers, and cannot end with an operator). Note that since `+` is both binary and unary, chained sequence of `+` is still valid Python. **2) Remove all spaces, map `!` to `*`, map all other special characters to `,`, and enclose everything within a pair of `[]` brackets.** For example `!1.2 &! 3.4 !! 56.78` becomes `[*1.2,*3.4**56.78]` which is a list construction expression. This way: * `n ! n` (where `n` is a number) becomes `n*n`, a valid product expression. * `n # n` becomes `n,n`, aka valid list elements. * `! n` becomes `*n`, which is valid Python since `*` is interpreted as [splat/unpack operator](https://stackoverflow.com/a/34767282) during list creation. * `n #! n` becomes `n,*n`, again valid list elements (where the later element is a splat expression). * `n !! n` becomes `n**n`, which is just the valid power operator. * `n ## n` becomes `n,,n` which is invalid. * `n !# n` becomes `n*,n` which is invalid. * `n #!! n` becomes `n,**n` which is invalid. * `n !!! n` becomes `n***n` which is invalid. This satisfies the first 4 rules. Note that although a valid string will produce **syntactically valid** Python expression, trying to `exec` or `eval` the resulting expression will potentially raises `TypeError`, since the splat operator can only applied to container types, not numeric types (e.g `*5` is syntactically valid, but if evaluated will raise `TypeError`). To get around this problem, I prepended `1 or` to the resulting list expression, aka `1 or [...]`. This way, the list construction will not be evaluated due to boolean short-circuiting. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 59 bytes ``` s=>/^!?\d+(\.\d+)?( *([%$#&!] *!?) *\d+(\.\d+)?)*$/.test(s) ``` [Try it online!](https://tio.run/##tVTbbtpAEH3nK2YFRpimJkAdhVYpqtRWQkrbh9C@NK0YzADbmF3kXW5fT2ftVE3wQqJKBcmyzlz2nDPj/YVrNEkml/al0hPaT6/25upt66fo305eNG4jfob9BjQb34NatS5@QFP0Q2g@CIbNWiuyZGzDhPtWC67lHYHRryuJVkanFKV61piOYhBwcR50anHUHYWPguGbSoULh3MyXLmkRGIKyRwzTCxlBhJUQFtpLEgFCMZmUs3OYK43tKYM7Jx2LkdpC2MCRVsLVgNhMgfNwQwacqa0K@LumJAJI/ioM@6Ji2VKh0zbIALoHHB0cAB@vMp4rRT5qwq0Snd8WkJLK7Vy5JgWZKuUAMd6TSANbKSd5zDnpbjAPHOB2V0EX1y5VuUQP3ZOMk7ZJ0BVqC05@JRa4VUljuC1Y/CRNkedGUzdMA/JOi/QFk6oCehp/vpn5k4gwaevN8NcN6jVYuyk5wZI65v0k8cYi5l95kFjmmrGpT3paSxKRsQiLmNVDxjE/22PhrmmiSYD7ltRRBPXw6PPVw9ozGrhrC28cQYe@n/SFREf3YMHHYsBFDJyvcURxo2EB3Yf5tQ1pnJyBvJxtZs6q7AbIlUMNEc4KFVecZJiB8oD6cSn1regkxPlHItSGdBLytBqvrl4Ix2tldXOyARTTnsOD1ENSjyqfhoftjZDfuZ9jFvjm5yTKfxCdubbu@vB@8PdCzy7J/iSjsEXiaNX7oqLeiC6/FoXcNmLLjvt7j@TGnz20wp8tMT9L/CFO9F52S1xEfWqJbTGaN1PWfA/QUOHFxjj7VG4/w0 "JavaScript (Node.js) – Try It Online") This should be valid for all cases above. Assuming that floating decimal point won't occur. ]
[Question] [ # Find the most important character The challenge is to write a program that outputs the most occurrent character in the input string, excluding these bracketing characters `()[]{}`. Each submission should consist only of non-trivial\* characters. Each solution is scored using the formula in the scoring section. Bracketing characters are allowed in the program, but may not be selected by the program as the most occurrent character. In cases where letters occur with the same frequency, any or all of the characters may be returned. \*Non-trivial is defined in this case to be a character that contributes to the functionality of the program. If the character can be removed without influencing how the program runs, it is a trivial character. ## Scoring Score is determined as follows: $$(\frac{n\_{char}}{n\_{total}}) \* 100(\%) $$ With nchar being the number of occurrences of the most frequent character in the input, and ntotal being the total number of non-trivial characters in the input. With this scoring criteria, all scores should be within the range \$[0,100]\$ Highest scoring solution per language wins. ## Input Solutions should take in any valid string as input. A convenient method of determining the most occurrent character in the program itself would be to use the program's source code as input to the program itself. The program does not have to check for non-trivial characters, as they should not be included in the program source. ## Output A single character with the highest percentage occurrence. Each solution should be capable of outputting standard ASCII, as well as the language's codepage (if applicable). ## Errata Creative solutions are encouraged. Boring solutions with long padded strings substituted in for numbers are discouraged. Standard loopholes are disallowed. ## Examples Program: `aabbbc` Output: `b` --- Program: `aabb` Output: `a` or `b` or `ab` --- [Sandbox Link](https://codegolf.meta.stackexchange.com/a/18537/41195) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 99.999999999999999957% ``` 1111111111111111111 ... (9352835025086960662 1's total) ... 11111g₅B.V ``` `g` gets the length of the large integer literal. Obviously this is too long for TIO, so [try a version using 9352835025086960662](https://tio.run/##yy9OTMpM/f/f0tjUyMLY1MDI1MDCzNLMwMzM6FFTq5Ne2P//GiCQmJiYlJQMAA) instead of the equivalent 1111...1111g. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 55.85% (or much more) ``` s=>eval(Buffer((g=n=>n?[+[n&127n],...g(n>>7n)]:[])(0b1001111010011001001100101001101110111000110111101100111110110111101111011110111011010111010011000001111111101101011110001010011011101110001110110111101111111111001011010111101101110111000111011011110111101010000111110011110111000110101100110011101011111011101101110110111001011011111110111110110101001010100010111101011011010111101111011101111011110111011010101000110010111000111100001110110011100001100101111001001011101110011n))+'') ``` [Try it online!](https://tio.run/##fZFNboMwEIX3PYXZ1J6QuONsIjWCSl30EoiFAZtQIRMFGrWnp/zYwaioSGbG82aeP/CnvMs2v1XX7mCaQvU66tsoVndZs/cvrdWNsTIyUWzekjAxz@J4Mumec14yE8cnA@lrkgLDTCCK4cEp4hLmRNjlNmJWXWaj95qq6Bmibfe1yW/jhLWnHUJ/7t@B2dPhLUjoDNDRWzuBK0/0jnsQL9wzs2V3Jiu2he7PD0GLgR68g31Q@S32LpbPFcIAhJRCnzembWrF66ZkmlEpsyzLKcDThrBR/lHyEgTBqAxSoUhENAkJpedVZz7W2dgAe8KmhLfXuupYDrxWpuwu5EAEkBcyaba0IwMr8K75qL5VwY4A5/4X "JavaScript (Node.js) – Try It Online") This is a 'fair' version, in that only the payload binary data is included (7 bits per character). But the score could be made arbitrary large by padding each encoded character with as many zeros as desired. They would still be 'non-trivial' as per the challenge rule, as removing any of them would break the decoding. The binary string is decoded as: ``` s.replace(m=o=/[^(){}[\]]/g,c=>(o[c]=-~o[c])<m?0:m=o[O=c])&&O ``` [Answer] # [PHP](https://php.net/), 75% ``` foreach(count_chars($argn)as$c)$o[]=$c*'1111111111111111111111111111111111111111001111111111111111111111111111111111111111111111111010111111111111111111111111111110101111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111'[$i++];arsort($o);echo chr(key($o)); ``` [Try it online!](https://tio.run/##K8go@G9jXwAk0/KLUhOTMzSS80vzSuKTMxKLijVUEovS8zQTi1WSNVXyo2NtVZK11A2JBAYGhqQCA0MDiuTpAtSjVTK1tWOtgeGTX1SioZKvaZ2anJGvkJxRpJGdWgkS0LT@Pxqc1AzOf/kFJZn5ecX/dd0A "PHP – Try It Online") Ungolfed: ``` // table of valid input chars - ASCII 0-255 // index is the ASCII number, and 1 or 0 if it is valid $valid_chars = '1111111111111111111111111111111111111111001111111111111111111111111111111111111111111111111010111111111111111111111111111110101111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111'; // get input string and aggregate count of each letter $counted_chars = count_chars( $argn ); // iterate through each foreach( $counted_chars as $ascii => $count ) { // multiply count by either 1 if valid or 0 if not $out[] = $count * $valid_chars[ $ascii ]; } // sort resulting list descending arsort( $out ); // display the ASCII value of the "most popular" valid char echo chr( key( $out ) ); ``` Counts the frequency of each character and uses a lookup table to to determine if a given character is excluded (example: `()[]{}`) from being counted. Sorts by frequency and returns the "most important" remaining char. Note: PHP's [`count_chars()`](https://www.php.net/manual/en/function.count-chars) only counts ASCII chars `0-255` which corresponds to the array of valid chars, so is not arbitrarily or unnecessarily long. Using a lookup table of flags to test the validity of a result is, while not the most efficient in this case, a valid and commonly-used programming practice. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), tends to 50% ``` '""{}[]()"'""м.M"J".V"".V"".V".V ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fXUmpujY6VkNTCci6sEfPV8lLSS9MCYb1wggqQVUOAA "05AB1E – Try It Online") You can keep appending `".V"` before the final J, any part of this string can't be removed and hence none of the characters themselves are non-trivial. Hence this tends to 50% of the program being " as you add more `".V"` Note: you couldn't have a single char command to tend to 66% inside the brackets like `"J"` as it can likely be shortened to `""` [Answer] # [C (gcc)](https://gcc.gnu.org/), 13.2% `;` ``` float m;a[256];l;t;c;n(char*s){bzero(a,1024);l=0;for(;*s;){a[*s]++;s++;l++;};m=0;t=0;for(;t++<255;)if(a[t]>m)c=t,m=a[t];m*=100;printf("%c %f\n",c,m/l);} ``` This version doesn't pad the end with semicolons. It only contains a few unneeded ones to push up my score to the next percent. Feel free to add semicolons up until you get 100%. [Try it online!](https://tio.run/##zY9NDoIwFIT3PUWDMWkBFYm4eeJFgEV9WG3SH0OrCwlnx5povIKTfIvJzObD1QVxnqV2IlADoimrfQcaAiBYhlcxpJ6Pp@d5cEzk26LccdB1AdINDFIPfBRN6rssAx/RkQlM3MP3E7LsUFYVcCWZaEJ3NBzrkJv6XcCk9bYo4DYoGyRLlkiXsrVJjrnZaA7TvFAW9b0/04MPvXLr65GQ@KVGKMseTvWcjITGWJb8h0T7sWht@/NIOJBpfgE "C (gcc) – Try It Online") ]
[Question] [ The code: ``` function L(){N=null;E=[N,N];t=this;h=E;t.u=i=>h=[i,h]; t.o=_=>h==E?N:h[+!(h=h[1])];t.e=(i,l)=>h=(l||h)==E?[i, E]:[(l||h)[0],t.e(i,(l||h)[1])];t.s=_=>{o="";while(i=t.o()) {o+=i+","}return o}} ``` For my response to this (old) question: <https://codegolf.stackexchange.com/a/196783/72421> (my linked answer has a commented version of the code and some disclaimers about valid inputs and outputs) I'm looking for suggestions on how to golf it further. I feel the last function is especially verbose. I managed to make every other function a single expression so I didn't need curly brackets or a return statement, but couldn't figure out how to make the last one not require a while loop. [Answer] I think the best way to get rid of the curly brackets is to go recursive. ### Original function (46 bytes) ``` t.s=_=>{o="";while(i=t.o()){o+=i+","}return o} ``` ### Recursive version (29 bytes) ``` t.s=_=>(i=t.o())?i+[,t.s()]:i ``` The `i+[,t.s()]` trick saves a byte over `i+','+t.s()`. Because you stop when `t.o()` returns `null`, the result of your original version always ends with a comma. In the new version, we actually append `null` at the end (that's the `:i`) but it's coerced to an empty string because of the above trick, leading to the same behavior. [Answer] ## Shortening `t.s` ### Favor recursion over while loop Given your `t.s` function ``` t.s=_=>{o="";while(i=t.o()){o+=i+","}return o} ``` Observe that `o` is a simple accumulator, so we can easily convert the loop into a recursive function. There are several ways to write the recursive function: ``` // explicit accumulator, aka tail-recursion t.s=(o="")=>(i=t.o())?t.s(o+i+","):o // implicit accumulator, shorter, saves 15 bytes from OP's code t.s=_=>(i=t.o())?i+","+t.s():"" ``` ### [Free commas](https://codegolf.stackexchange.com/a/113405/78410) `i+","+t.s()` can be shortened to `i+[,t.s()]`, saving 1 byte. ## Shortening the rest ### Initialize the second parameter of `t.e` to `h` The function `t.e` is using `(l||h)` several times, just to handle the initial call. JS's default argument is very permissive, so we can do this: ``` // instead of t.e=(i,l)=>h=(l||h)==E?[i,E]:[(l||h)[0],t.e(i,(l||h)[1])]; // do this t.e=(i,l=h)=>h=l==E?[i,E]:[l[0],t.e(i,l[1])]; ``` ### Simplify base case Instead of `E=[N,N]`, simply `E=[]` works too. This has several golfing opportunities regarding string coercion: * `h==E` is equivalent to `h==[]`, and `[]` coerces to `""`. Anything that stringifies into something other than `""` is greater than `E`, so we can rewrite `h==E?A:B` into `h>E?B:A`. * `h` is now a linked list where `3::2::1::nil` looks like `[3,[2,[1,[]]]]`, which exactly stringifies into `"3,2,1,"`. So we can simply coerce `h` to string: `t.s=_=>h+""`, or even better, `t.s=_=>h+E`. ### Array unpacking We can slightly do better here too: ``` // instead of t.o=_=>h>E?h[+!(h=h[1])]:N; // do this t.o=_=>h>E?([a,h]=h,a):N; ``` And this also applies to `t.e`: ``` // instead of this t.e=(i,l=h)=>h=l>E?[l[0],t.e(i,l[1])]:[i,E]; // do this t.e=(i,[a,l]=h)=>h=l?[a,t.e(i,l)]:[i,E]; ``` I chose `l?` because whenever `h` is nonempty, `l` is a reference so it always evaluates to true. If `h` is empty, both `a` and `l` become `undefined`. Side note: I found that the OP's code actually works with falsy list items, because the only real comparison is `h==E`, that is, comparing ~~stringification~~ reference of whole array. Whatever `E` is, `h==E` cannot be true if the list `h` has at least one item, since ~~its string will have at least one more comma than `E`'s~~ the reference becomes different. ## Final result, ~~125~~ 121 bytes ``` function L(){h=E=[];t=this;t.u=i=>h=[i,h];t.o=_=>h>E?([a,h]=h,a):null;t.e=(i,[a,l]=h)=>h=l?[a,t.e(i,l)]:[i,E];t.s=_=>h+E} ``` [Try it online!](https://tio.run/##lZHBbiIxDIbvPEU6p0SkdIAbkeE0txXStscRqkZTd5M2nawmSdEK5tmpAwMSpYvELfb/2/7svFWfla9b8zfcN@4Fd6@xqYNxDfvFxWYJTbRWFVAu5XKlAgRtvNJQqDCKYGCuoTRSkzJy8JxCKBbLmS6Hd1yDLscrkTQEbqQVSed2u9Ui2aiwWM3KQ6LMV5J8ZOvjvtKnrhsHWabW2lgyAI3iQmzcEMwwk1nXYohtw1zXnbMTJZQn5v/wzosFLyvKgJaVmO237XkpbSm9p7YLig58VhB0Qj/S6WHR7SwG9loR4AsD9sxgzjYs6NatWdG2ruVCsU4NkssaH8jT4DpRqsHg4YE9hap@HyRlFPlYqP41JXn/pIUZALAp2277MfyoRT75bpv8YDtq4yta2v5cPsGxtQmaBOv/MbT4gU04js9v5c2/2/IrTPnNvL8jRjwY8XRMvLzST5fAyx2uHXN6M9wjfmLr8fKvJ5dX9H2nbConciyz8261a7yzOLLuD8@eYl2j93cZCbsv "JavaScript (Node.js) – Try It Online") ]
[Question] [ **This question already has answers here**: [Cover up zeroes in a list](/questions/65770/cover-up-zeroes-in-a-list) (61 answers) Closed 4 years ago. Given a non-empty list of decimal digits (`0`, `1`, ..., `9`), replace each zero by the most recent nonzero, if possible. **Example 1**: given ``` 1 4 3 0 0 7 5 5 0 3 ``` the output should be ``` 1 4 3 3 3 7 5 5 5 3 ``` Note how the first two zeros are replaced by `3`, which is the most recent (i.e. rightmost) nonzero. Similarly, the last zero is replaced by `5`. **Example 2**: given ``` 0 0 4 0 0 5 0 ``` the output should be ``` 0 0 4 4 4 5 5 ``` Note how it is not possible to replace the first two zeros, because there isn't a nonzero number to the left ot them. ### Additional rules * Input can be taken by [any reasonable means](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Format is flexible as usual. In particular, it can be a list of numbers, an array, a string representation of an array, a string of digit characters ... * [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Shortest code in bytes wins. ### Test cases Input, then output ``` 1 4 3 0 0 7 5 5 0 3 1 4 3 3 3 7 5 5 5 3 0 0 4 0 0 5 0 0 0 4 4 4 5 5 0 0 0 0 0 0 0 0 0 1 0 1 4 2 1 0 4 2 1 1 8 0 0 0 6 8 8 8 8 6 ``` [Answer] # JavaScript (ES6), ~~22~~ 21 bytes ``` A=>A.map(x=>A=x||~~A) ``` [Try it online!](https://tio.run/##bY9BDoIwEEX3nqLLkozQ2oJsasI5jIsGwWiQEjGGBeHqdUpjIpT5m0n@e5P2oT@6L1/37r1vzbWytbKFOhXxU3d0wEUN4zhNRWRL0/amqeLG3GhNzxwkCGCYI6QYBuISRSRJiG9cfJOC2K1kp8lZRtFpflD2jQuKW9ofTpYaC/AQ/eHhZb4Fz5f5GpZwAB4@BGHfBEI@f5VBtlRQyMEns18 "JavaScript (Node.js) – Try It Online") ### Commented ``` A => // A[] = input array A.map(x => // for each value x in A[]: A = // update A to: x || // either x, if it's not equal to 0 ~~A // or A coerced to an integer otherwise ) // end of map() ``` Because we're re-using the input array \$A[\:]\$ to store the last non-zero value, two special cases arise if the 2nd part of the condition is executed on the 1st iteration: * if \$A[\:]\$ is a singleton array containing \$0\$, `~~A` is equal to `~~0` * if \$A[\:]\$ is an array of several elements (starting with \$0\$), `~~A` is equal to `~~NaN` which gives the expected \$0\$ in both cases. [Answer] ## Mathematica, ~~19~~ 17 bytes ``` f@x_:=f@0=x;Map@f ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n65g@z/NoSLeyjbNwcC2wto3scAhDSSqEFCUmVfioKUBFtHk4krXd6jmqjbUUTDRUTDWUTAAI3MdBVMwArKNa3W4qiHCJjB5kAxCGMKE8g1BNFChEZAJlbKAaQMis1qu2v8A) Inspired by [kglr's answer](https://mathematica.stackexchange.com/a/206836/12025) to a question on Mathematica Stack Exchange, which I assume was the inspiration for this challenge. :) In the body of `f`, the value of `f[0]` is redefined to be the input, which is also returned. That way, whenever `f` is called with `0` after the first time it's called, it will always yield the "remembered" result, which is updated when `f` is called again with a nonzero argument. Thanks to [@attinat](https://codegolf.stackexchange.com/users/81203/attinat) for 2 bytes. [mikado's answer](https://mathematica.stackexchange.com/a/206927/12025) yields a 20 byte solution: ``` FoldList[#2/. 0->#&] ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 21 bytes ``` s/([^0])0/$1$1/&&redo ``` [Try it online!](https://tio.run/##K0gtyjH9/79YXyM6ziBW00BfxVDFUF9NrSg1Jf//fwMDEwMDU4N/@QUlmfl5xf91CwA "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` ηε0†θ ``` [Try it online!](https://tio.run/##yy9OTMpM/W/k9v/c9nNbDR41LDi343@tzn9DE2MDA3NTUwNjLgMDExMTU1MA "05AB1E – Try It Online") For each prefix of the input, filter 0s to the front, then get its last digit. Yes, filter-to-the-front is somehow a single-byte built-in (`†`). I didn't think I'd ever need it, but here we are. [Answer] # Java 10, 65 bytes ``` s->{while(!s.equals(s=s.replaceAll("(.) 0","$1 $1")));return s;}; ``` A Function that repeatedly replaces "N 0" with "N N" until such time as the String stops changing, then returns it. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ȯ@\ ``` [Try it online!](https://tio.run/##y0rNyan8///EeoeY////G@goGOoomOgoGOsoGICRuY6CKRgB2cYA "Jelly – Try It Online") -2 bytes thanks to FryAmTheEggMan (it's close to being an entirely new solution because 5 -> 3 bytes is a 40% deduction and that's like half the code lol) # Explanation ``` ȯ@\ Main Program \ Cumulative Reduce ȯ@ Logical OR (inverted; basically "right OR left") ``` [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 11 bytes ``` {$[y;y;x]}\ ``` [Try it online!](https://tio.run/##NY3LCsIwFET3/YpZuNCFkJi0luZTaqBuIlKpULpIkfrr8T4ss8mcOeGO5@kxlZK6z6Ffwxpy3G5lkfadu4QchvcYjkO6P18hkzCf4lYtvYWHg6FcUVMMXAUo5Sit4SLJrHmRSSRNO4eUXdgHI4CLLla45eJxoRO86Utgq7/QEG7/aWL5AQ "K (ngn/k) – Try It Online") `{` `}\` scan - starting with the first element, apply the function in `{` `}` between the current result and the next element. collect intermediate results in a list. `$[y;y;x]` cond - if the right argument `y` is truthy (not 0), return it, otherwise return the left argument `x` ]
[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/193093/edit). Closed 4 years ago. [Improve this question](/posts/193093/edit) ## INTRODUCTION I like Karma Fields : he's a music producer that creates original music tracks. His artwork also matches up really well his style. He has a logo witch I find really interessing : [![enter image description here](https://i.stack.imgur.com/FrVpC.png)](https://i.stack.imgur.com/FrVpC.png) ## GOAL Your goal will be to reproduce that logo, graphically or in ASCII. **Edit** @NahuelFouilleul managed to provide a readable ascii version of this : ``` / \ /| |\ / | | |\ |\ /|\ / \|/| | | \ | | |/ \ / \ | | \ | / | | \|/ \|/ \ / \ | / \|/ ``` ## RULES * The logo can be any size BUT has to be recognisable (each hexagon part has to be visible). * Colors don't matter, only the drawing counts. * Each line can be the same thickness, and you can forget about the 2 dots. * This is a codegold challenge, so the least amount of bytes wins. * The usual loopholes are forbidden. [Answer] ## Logo, ~~170~~ ~~168~~ 160 bytes ``` make"l[4 5 2 3 1 3 1 1 3 1 5 5 1 3 1 1 2 5 2 5 5 3 5 5 3 0 5 4 5 3 5 5 3 5 5 4 0 0 5 0 0 5 0 0 5 0 0 5 0 0 5 0 0 5 4]repeat 55[rt 60*head:l fw 20 make"l tail:l] ``` [Try it online!](http://logo.twentygototen.org/k9uE9DsN) Edit: Saved ~~2~~ 9 bytes thanks to @Night2. [Answer] JavaScript, 420 407 bytes ``` document.write('<svg id="pic" height="255" width="255"></svg>') v="0011120322210011343546413441045156516421646728696a52586758075b5104074848090a520a4248423a030a".split``.map((x,i)=>(i%2?[43,88,175,220,100,72,58,131,144,162,190,117]:[129,206,52,179,154,103,77])[+('0x'+x)]) for(i=1;i<46;i++) pic.innerHTML+=`<line x1=${v[2*i-2]} y1=${v[2*i-1]} x2=${v[2*i]} y2=${v[2*i+1]} style="stroke:red;stroke-width:2" />` ``` Point coordinates coding ``` let c=[129, 43, 206, 88, 206, 175, 129, 220, 52, 175, 52, 88,129, 43, 206, 88, 179, 100, 179, 72, 154, 58, 154, 88, 179, 100, 154, 88,129, 100, 103, 88, 103, 58,103, 88,77, 100, 52, 88,77, 100, 77, 131, 52, 144, 77, 162, 77, 190, 103, 175, 103, 144, 77, 131, 103, 144,129, 131, 103, 117, 103, 88,129, 100, 129, 131,154, 144, 154, 144,129, 162, 129, 190, 103, 175,129, 190,154, 175,154, 144,154, 175, 179, 190,129, 220,129, 190 ] a=[... new Set(c.filter((x,i)=> i%2))] // remove duplicates for X b=[... new Set(c.filter((x,i)=> i%2-1))] // remove duplicates for Y d=c.map((x,i)=> (i%2?a:b).indexOf(x).toString(16)).join`` console.log({a,b,d}); ``` [Answer] # Raw bitmap (29x35), 202 bytes Hand drawn a small monochrome bitmap file which looks like the logo. I'm not sure if raw bitmap is accepted here, but if it is not, a HTML version is below the post too. ![logo](https://i.stack.imgur.com/PieC4.png) Please note that the image above is converted to PNG during upload, to see the original image save the hex dump as a binary file or use the HTML version. ``` 000000 42 4d ca 00 00 00 00 00 00 00 3e 00 00 00 28 00 BM........>...(. 000010 00 00 1d 00 00 00 23 00 00 00 01 00 01 00 00 00 ......#......... 000020 00 00 8c 00 00 00 c3 0e 00 00 c3 0e 00 00 00 00 ................ 000030 00 00 00 00 00 00 00 00 00 00 ff ff ff 00 ff fd ................ 000040 ff f8 ff f0 7f f8 ff ed bf f8 ff 9d cf f8 fe 7d ...............} 000050 f3 f8 fd fd fd f8 f1 f8 fc 78 e6 e5 33 b8 97 5d .........x..3..] 000060 cf c8 77 bd df f0 77 bd df f0 77 bd df f0 6f bc ..w...w...w...o. 000070 df f0 5f bf 1f f0 3f 9f df f0 4e 67 3f f0 75 fa .._...?...Ng?.u. 000080 ff f0 7b fd ff f0 7b f9 ff f0 7b e5 ff f0 7b dd ..{...{...{...{. 000090 ff f0 7b dd ff f0 7b dd ff f0 64 dd fe 70 5f 52 ..{...{...d..p_R 0000a0 78 90 3f 8f a6 e8 bf df de d8 cf df de b8 f3 df x.?............. 0000b0 de 78 fd df d9 f8 fe 5f d7 f8 ff 9f cf f8 ff cf .x....._........ 0000c0 bf f8 ff f2 7f f8 ff fd ff f8 .......... ``` # HTML, 292 bytes ``` <img src=data:;base64,Qk3KAAAAAAAAAD4AAAAoAAAAHQAAACMAAAABAAEAAAAAAIwAAADDDgAAww4AAAAAAAAAAAAAAAAAAP///wD//f/4//B/+P/tv/j/nc/4/n3z+P39/fjx+Px45uUzuJddz8h3vd/wd73f8He93/BvvN/wX78f8D+f3/BOZz/wdfr/8Hv9//B7+f/we+X/8Hvd//B73f/we93/8GTd/nBfUniQP4+m6L/f3tjP396489/eeP3f2fj+X9f4/5/P+P/Pv/j/8n/4//3/+A ``` [Answer] # [PHP](https://php.net/), 71 bytes I have used a compressed version of the string created by [Nahuel Fouilleul](https://codegolf.stackexchange.com/users/70745/nahuel-fouilleul) in the OP comments. Uses raw output of [gzdeflate](https://www.php.net/manual/en/function.gzdeflate.php) and contains unprintable binary data, so the code itself and direct TIO link cannot be posted here, but here is a hex dump of it: ``` 000000 3c 3f 3d 67 7a 69 6e 66 6c 61 74 65 28 22 15 c7 <?=gzinflate(".. 000010 47 01 43 01 14 02 b0 73 97 87 38 c0 10 52 10 df G.C....s..8..R.. 000020 ff 36 01 d1 df 1b 19 76 39 0c 73 5a e5 56 97 3d .6.....v9.sZ.V.= 000030 34 35 70 8c ba c5 51 4d 8c a3 2e b7 2a 8f 28 73 45p...QM....*.(s 000040 19 74 f9 03 22 29 3b .t.."); ``` Save it as a binary file then execute it like this: `php hex.php` TIO which uses bash to create and run this file: [Try it online!](https://tio.run/##HY9LbsMwDET3PcW7QANJlETrOPpYSDat0aZAFr27I5ogBiDAN0O2@ns/z9dr8PnD7fF1/D1vz8c3/xz34zzdVSAdmcggK1rJhbyTM7mTPRrJibARAj7R9cMov7ioOE8UUx9xgeZQoSibIhvdsfZSMB3z4sLi5grLBo3VE9/wBc1IwXUzSJU9kbI5ybg4sTsjklDH1mmVvlZW/LCxCmGnKaGyTbtW5eLi4sw9Mpe72BOhIO0N "Bash – Try It Online") Base64 of deflated string for anyone who might need it: ``` FcdHAUMBFAKwc5eHOMAQUhDf/zYB0d8bGXY5DHNa5VaXPTQ1cIy6xVFNjKMutyqPKHMZdPkD ``` ]
[Question] [ The ChatRoom is [here](https://chat.stackexchange.com/rooms/83075/reaper-russian-bs) I love playing the card game BS, but sometimes, it just doesn't have enough **oomph** for my short attention span. Instead, let's play some Russian BS. # Rules [Here](https://www.instructables.com/id/How-to-play-bluff/) is a quick guide to the rules. * The game begins with a random player declaring the card type of the round (out of 14 options: `A,2,3...10,J,Q,K,j` where the `j` stands for joker) * The same player starts the round, placing down as many cards as he or she wants, which all have to be of the declared card type. * Any player can call BS on the play. If multiple players call BS, the player closest to the player who put down the cards to the right will be the one to call BS * If BS is called on the play, then the cards played there are checked by the moderator. If the cards were indeed valid (i.e., all of the declared type or jokers), the player who called BS will take all of the cards played in the round. Otherwise, the player who played the invalid cards will take all of them. * If no BS is called, the next player is up to play, and must also play the declared card type. * We also allow players to pass their turn if they don't wish to play. However, if they pass, they are not allowed to play for the rest of the round (although they can call BS) * If every player passes, then the round ends, and the player who played the last cards will start the next round by declaring the card type. * If BS is called, the player who played the cards will start the next round and declare if he played valid cards, else the player who called BS will start. * The player who has no cards at the end of the game wins. I like these rules because they don't force you to lie, but usually, players tend to lie more than in the original version of BS # Challenge This challenge will be a [king-of-the-hill](/questions/tagged/king-of-the-hill "show questions tagged 'king-of-the-hill'") challenge, with submissions providing bots to play the game. The bots will be written in **Python 3**, although I'll try my best to accommodate all submissions. The submissions should consist of the following three functions: ``` CallBS - determines whether you seek to call BS or not on a play PlayCards - determines what cards you want to play StartRound - determines what the declared type of the round is, if you are chosen to pick it. ``` The submitted functions should be named such that their names are `***_CallBS`, `***_PlayCards`, and `***_StartRound`, where `***` is the name of your bot. Below are example functions that describe the inputs and outputs: ``` def example_CallBS(self,pos,player,handSize,currCard,numCards,numPile): '''This function will output True if the bot seeks to call BS on the current move, or False if not. The parameters are - self: class variable - pos: int - how many positions away you are to the right of the player (Note: if your function got called, that means everyone to your left before the player decided not to call BS) - player: str - holds the name of the bot who just played cards - handSize: int - how many cards playing bot holds - currCard: str - current card in play (One of A,2,3,4,5,6,7,8,9,10,J,Q,K,j) - numCards: int - number of cards just played by player - numPile: int - number of cards in the pile (not including played cards this turn) ''' return True def example_PlayCards(self,currCard,numPile,stillPlaying): '''This function will output a sublist of the hand of the bot to play this turn, or None to pass. The parameters are - self: class variable - currCard: str - current card in play (One of A,2,3,4,5,6,7,8,9,10,J,Q,K,j) - numPile: int - number of cards in the pile - stillPlaying: list of str - players who haven't passed this round ''' return self.hand[:] def example_StartRound(self): '''This function will output a string representing the card that will be played for the coming round (One of A,2,3,4,5,6,7,8,9,10,J,Q,K,j) The parameters are - self: class variable ''' return 'A' ``` In addition, you will be provided with the following utilities ``` self.obj - A blank object for your usage to store knowledge between calls self.hand: list of card objects - Your current hand in card objects (calling card.val gives you the str value of the card) self.numBots: int - number of competitors you have self.getRandom(): function - outputs a random number from 0 to 1. ``` If you want to use any sort of randomness, you **must** use the `self.getRandom()` function provided. You may not edit any of these objects except for `self.obj` # Parameters and more Rules * The cards in this game (you'll see the class that the cards belong to in the controller below) don't have a suit since suits don't matter to this game. * The number of cards in the game will be `14*number of bots` (numBots of each type of card) * In the output of PlayCards, you **must** output cards that are in your hand. The program will not like you otherwise. You also must output card objects, not strings. * You may take at most 10 ms on average over 5 turns for `StartRound`, 50 ms averaged over 5 turns for `PlayCards`, and 20 ms averaged over 5 turns for `CallBS`. # Controller In this Controller, you add your functions to the top of the program, then add a tuple of all three functions, in the order of `(CallBS, PlayCards, StartRound)` to the list `BotParams`. The Controller should take it from there. Below is the controller with the example bot from earlier. This bot will **not** be participating, nor will any bots that obviously aren't aiming the win the competition. ``` import random as rn rn.seed(12321)#Subject to change def example_CallBS(self,pos,player,handSize,currCard,numCards,numPile): return True def example_PlayCards(self,currCard,numPile,stillPlaying): return self.hand[:] def example_StartRound(self): return 'A' #This is how you add your bot to the competition. Add the tuple of all three of your functions to BotParams BotParams = [(example_CallBS,example_PlayCards,example_StartRound)] #This is the controller class Obj: pass class card: def __init__(self, val): self.val=val def __eq__(self,other): return (self.val==other or self.val=='j') def __str__(self): return self.val class BSgame: def __init__(self,BotParams): self.numBots = len(BotParams) self.AllCards = ['A','J','Q','K','j']+[str(i) for i in range(2,11)] x=[card(j) for j in self.AllCards*self.numBots] rn.shuffle(x) self.hands = [x[14*i:14*i+14] for i in range(self.numBots)] rn.shuffle(BotParams) self.BotList = [BSBot(self.hands[i],len(BotParams),*BotParams[i]) for i in range(self.numBots)] self.play = [] self.pile = [] self.isRound = False self.isTurn = 0 self.currCard = None self.winner=None self.GameSummary = [str(i) for i in self.BotList] def results(self): print("The winner is "+self.winner) print("Final Standings:") for i in self.BotList: print(i) def checkBS(self, caller): if min([i==self.currCard for i in self.play]): self.BotList[caller].hand.extend(self.pile) self.BotList[caller].hand.extend(self.play) self.GameSummary.append(self.BotList[caller].name+" called BS but was wrong!") if self.BotList[self.isTurn].hand==[]: self.winner=self.BotList[self.isTurn].name self.GameSummary.append(self.BotList[self.isTurn].name+" has won the game!") else: self.BotList[self.isTurn].hand.extend(self.pile) self.BotList[self.isTurn].hand.extend(self.play) self.GameSummary.append(self.BotList[caller].name+" called BS and was right!") self.isTurn=caller self.isRound=False self.pile=[] def isBS(self): for i in range(1,self.numBots): if self.BotList[(i+self.isTurn)%self.numBots].callBS(i,self.BotList[self.isTurn].name,len(self.BotList[self.isTurn].hand),self.currCard,len(self.play),len(self.pile)): self.checkBS(i) break if self.isRound: if self.BotList[self.isTurn].hand==[]: self.winner=self.BotList[self.isTurn].name self.GameSummary.append(self.BotList[self.isTurn].name+" has won the game!") self.pile.extend(self.play) def startRound(self): self.currCard = self.BotList[self.isTurn].startRound() for i in self.BotList: i.inRound = True self.isRound=True self.GameSummary.append(self.BotList[self.isTurn].name+" started the round by picking "+self.currCard+" for the round.") def __iter__(self): return self def __next__(self): if not self.isRound: self.startRound() passList = [i.name for i in self.BotList if i.inRound] self.play =self.BotList[self.isTurn].playCards(self.currCard,len(self.pile),passList) if self.play == None: self.BotList[self.isTurn].inRound=False self.GameSummary.append(self.BotList[self.isTurn].name+" passed its turn.") else: try: for i in self.play: self.BotList[self.isTurn].hand.remove(i) except: raise Exception("You can't play a card you don't have, you dimwit") self.GameSummary.append(self.BotList[self.isTurn].name+" played "+",".join(i.val for i in self.play)+".") self.isBS() if self.winner!=None: raise StopIteration if set(passList)!={False}: while True: self.isTurn=(self.isTurn+1)%self.numBots if self.BotList[self.isTurn].inRound: break else: self.GameSummary.append("Everyone passed. "+self.BotList[self.isTurn].name+" starts the next round.") self.isRound=False return(None) class BSBot: def __init__(self,myHand,numBots,CallBS,PlayCards,StartRound): self.obj=Obj() self.hand = myHand self.numBots = numBots self.name = CallBS.__name__.split('_')[0] self.callBS = lambda pos, player, handSize, currCard, numCards, numPile: CallBS(self,pos,player, handSize, currCard, numCards, numPile) self.playCards = lambda currCard, numPile, stillPlaying: PlayCards(self,currCard, numPile, stillPlaying) self.startRound= lambda:StartRound(self) def __str__(self): if self.hand==[]: return(self.name+': WINNER!') return(self.name+": "+", ".join(str(i) for i in self.hand)) def getRandom(self): return rn.random() Mod = BSgame(BotParams) for i in Mod: pass Mod.results() ``` Additionally, if you want to see a summary of the game, type in the following command at the end of the program: ``` print("\n".join(Mod.GameSummary)) ``` [Answer] # Naive Bot ``` def naive_CallBS(self,pos,player,handSize,currCard,numCards,numPile): return False def naive_PlayCards(self,currCard,numPile,stillPlaying): return [card(currCard)] * self.hand.count(currCard) def naive_StartRound(self): return self.hand[0].val ``` Never calls BS, never lies, and lets the game play out, while trying its best to win. Will always play all of the current card, and will start the round with the first card in its hand. [Answer] # Asshole ``` def asshole_CallBS(self,pos,player,handSize,currCard,numCards,numPile): if not hasattr(self.obj, "flag"): self.obj.flag2 = False self.obj.flag = False if len(self.hand) < self.numBots * 14 * 1.5 / 4 and self.obj.flag: self.obj.flag = False if len(set(self.hand)) * self.numBots * 3.0 / 4 < len(self.hand): self.obj.flag2 = True if len(self.hand) < self.numBots * 14 * 3.0 / 4: if not self.obj.flag: self.obj.flag = True return False else: return self.hand.count(currCard) * 1.0 / self.numBots > 0.75 def asshole_PlayCards(self,currCard,numPile,stillPlaying): if not hasattr(self.obj, "flag"): self.obj.flag2 = False self.obj.flag = False if not self.obj.flag: return [card(currCard)] * self.hand.count(currCard) if len(self.hand) > self.numBots * 14 * 3.0 / 4 else self.hand else: if self.obj.flag2 and len(self.hand) < 3: return self.hand return [card(currCard)] * self.hand.count(currCard) def asshole_StartRound(self): if not hasattr(self.obj, "flag"): self.obj.flag2 = False self.obj.flag = False card = "" max_cards = 0 for i in "A,2,3,4,5,6,7,8,9,10,J,Q,K,j".split(","): if self.hand.count(i) > max_cards: max_cards = self.hand.count(i) card = i return card ``` Have you ever been that one player in BS who tries to get all the cards? No? Just me? Well, let me tell you it's just as fun. Trust me, this is a legitimate winning strategy. [Answer] # Moniathan ``` def moniathan_CallBS(self, pos, player, handSize, currCard, numCards, numPile): if numCards > self.numBots * 0.5: return True if self.hand.count(currCard) == self.numBots: return True if self.hand.count(currCard) + numCards > self.numBots * 0.5: return True if numPile > self.numBots * 2: return True return False def moniathan_PlayCards(self, currCard, numPile, stillPlaying): cards = [c.val for c in self.hand] if cards.count(currCard) > 1: return cards.count(currCard) * [card(currCard)] if cards.count(currCard) == 1: if len(self.hand) > 1: add_more = self.getRandom() > 0.75 if add_more: return [card(currCard), [c for c in self.hand if c.val != currCard][0]] else: return [card(currCard)] else: return [card(currCard)] else: if self.getRandom() > 0.5: if self.getRandom() > 0.5 and len(self.hand) > 1: return [self.hand[0], self.hand[1]] else: return [self.hand[0]] else: return [] def moniathan_StartRound(self): return max(self.hand, key=lambda x: self.hand.count(x.val)).val ``` It mostly tries to play safe but sometimes it will take small risks to get ahead. [Answer] # Halfwit ``` def halfwit_CallBS(self,pos,player,handSize,currCard,numCards,numPile): # Call if I know he's lying if numCards + self.hand.count(currCard) > self.numBots: return True # Call if he'd win otherwise if handSize == 0: return True # Call if that would be more than half of the remaining cards, more than 3, and he's got lots of cards if handSize > 14 and numCards > 3 and numCards + self.hand.count(currCard) > (self.numBots - numPile) / 2: return True return False def halfwit_PlayCards(self,currCard,numPile,stillPlaying): # If I have this card, play all that I've got. if self.hand.count(currCard) > 0: return [card(currCard)] * self.hand.count(currCard) # If more than half of the cards of this value are allegedly already out, play nothing if numPile * 2 >= self.numBots: return # Play the smallest stack I've got. counts = [self.hand.count(i) for i in "A,2,3,4,5,6,7,8,9,10,J,Q,K,j".split(",")] choice = "A,2,3,4,5,6,7,8,9,10,J,Q,K,j".split(",")[counts.index(min([x if x != 0 else 100 for x in counts]))] return [card(choice)] * min([x for x in counts if x != 0]) def halfwit_StartRound(self): # Play the card I have the most of return max(self.hand, key=lambda x: self.hand.count(x.val)).val ``` Halfwit always plays something - and he cheats if he doesn't have any of the right cards to play. Right now there's a few issues with the controller and with the bot and I'm not sure which is which, so I'll have to come back and fix some bugs later. ]
[Question] [ A few days ago, I came up with a fun card game to play with my friends. We were having fun playing it, when I thought, "Why not make this a KoTH?" So, here it is! ## Overview In this game, the objective is to get the most points. Your bot starts with 0 points and 20 energy. Every turn (500 in a game), both bots play one card. Some earn you points, some take the opponent's points. ## Cards ``` A=Add 5 points to your score [Costs 0.1 energy] R=Remove 5 points from opponent [Costs 0.1 energy] H=Half your next score [Costs 1 energy] Y=Half opponent's next score [Costs 1 energy] D=Double your next score [Costs 2 energy] T=Double opponent's next score [Costs 2 energy] N=Negate your next score [Costs 3 energy] O=Negate opponent's next score [Costs 3 energy] S=Shield for 5 turns [Costs 15 energy] X=Take five energy from opponent [Gives opponent 10 points] E=Refill five energy [Costs 10 points] ``` ## How it works First how would halving your next score or doubling your opponent's next score come in handy? Well, imagine you get 5 points taken away on your next turn. Instead, 2.5 points get taken away. Cool, right? Or, negating your next score would give you 5. If you think your opponent will give themself points, negate their next move! The order of operations for modifying point values is: 1. Add all positive or negative point changes 2. Half if necessary 3. Double if necessary 4. Negate if necessary 5. If shielding and result is negative, change to 0 Attempting to lower the opponent's **energy** past 0 does not work. There is no upper limit to energy, or lower limit to points. Energy reducing cards are played before other cards, so if Bot A with 17 energy runs shield and Bot B runs take 5 energy, Bot A cannot shield. ## Creating a bot In **Javascript**, create a new function with whatever name you wish. This function should take 3 parameters: ``` Array of Numbers (Your coins, Opponent's coins) Array of Numbers (Your energy, Opponent's energy) Object (Use for storage between rounds) ``` Note that there is no way of knowing what cards have been played. You must teach the bot to figure it out by itself! The way you select a card is by `return`ing a string, containing the letter of the card in uppercase or lowercase. Note that [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) (obviously) aren't allowed. If any other value is returned, your bot just does nothing. ## Scoring Every bot will be run against each other bot once. The loser will get 0 points, anbd the winner will get the difference in points added to its total score (Between all rounds). The top 8 will compete in a tournament. In other words, they will each fight one other bot, the four winners will fight another bot, and the two remaining bots will fight for first. ## Controller ``` var botDataList = [ { name: "", desc: "", run: function(){ } }, { name: "", desc: "", run: function(){ } } ]; function playGame() { botSetup(); for (var i = 0; i < 500; i++) { runBots(); } var botA = botDataList[0]; var botB = botDataList[1]; console.log("Bot " + botA.name + ": " + botA.points); console.log("Bot " + botB.name + ": " + botB.points); } function botSetup() { for (var b, i = 0; i < 2; i++) { b = botDataList[i]; b.points = 0; b.energy = 20; b.storage = {}; b.affectAdd = []; b.affectAct = []; b.shield = 0; } } function runBots() { var botA = botDataList[0]; var botB = botDataList[1]; var resA = botA.run([botDataList[0].points, botDataList[1].points], [botDataList[0].energy, botDataList[1].energy], botDataList[0].storage).toLowerCase(); var resB = botB.run([botDataList[1].points, botDataList[0].points], [botDataList[1].energy, botDataList[0].energy], botDataList[1].storage).toLowerCase(); var modA = 0; var modB = 0; if (resA == 'a' && botA.energy >= 0.1) { botA.energy -= 0.1; modA += 5; } else if (resA == 'r' && botA.energy >= 0.1) { botA.energy -= 0.1; modB -= 5; } else if (resA == 'h' && botA.energy >= 1) { botA.energy -= 1; botA.affectAdd.push('h'); } else if (resA == 'y' && botA.energy >= 1) { botA.energy -= 1; botB.affectAdd.push('h'); } else if (resA == 'd' && botA.energy >= 2) { botA.energy -= 2; botA.affectAdd.push('d'); } else if (resA == 't' && botA.energy >= 2) { botA.energy -= 2; botB.affectAdd.push('d'); } else if (resA == 'n' && botA.energy >= 3) { botA.energy -= 3; botA.affectAdd.push('n'); } else if (resA == 'o' && botA.energy >= 3) { botA.energy -= 3; botB.affectAdd.push('n'); } else if (resA == 's' && botA.energy >= 15) { botA.energy -= 15; botA.shield += 5; } else if (resA == 'x') { modB += 10; botB.energy = (botB.energy >= 5) ? botB.energy - 5 : 0; } else if (resA == 'e' && botA.points >= 10) { modA -= 10; botA.energy += 5; } if (resB == 'a' && botB.energy >= 0.1) { botB.energy -= 0.1; modB += 5; } else if (resB == 'r' && botB.energy >= 0.1) { botB.energy -= 0.1; modA -= 5; } else if (resB == 'h' && botB.energy >= 1) { botB.energy -= 1; botB.affectAdd.push('h'); } else if (resB == 'y' && botB.energy >= 1) { botB.energy -= 1; botA.affectAdd.push('h'); } else if (resB == 'd' && botB.energy >= 2) { botB.energy -= 2; botB.affectAdd.push('d'); } else if (resB == 't' && botB.energy >= 2) { botB.energy -= 2; botA.affectAdd.push('d'); } else if (resB == 'n' && botB.energy >= 3) { botB.energy -= 3; botB.affectAdd.push('n'); } else if (resB == 'o' && botB.energy >= 3) { botB.energy -= 3; botA.affectAdd.push('n'); } else if (resB == 's' && botB.energy >= 15) { botB.energy -= 15; botB.shield += 5; } else if (resB == 'x') { modA += 10; botA.energy = (botA.energy >= 5) ? botA.energy - 5 : 0; } else if (resB == 'e' && botB.points >= 10) { modB -= 10; botB.energy += 5; } if (botA.affectAct.includes('h')) { modA *= 0.5; } if (botA.affectAct.includes('d')) { modA *= 2; } if (botA.affectAct.includes('n')) { modA *= -1; } if (botA.shield > 0) { modA = (modA < 0) ? 0 : modA; botA.shield--; } botA.points += modA; botA.affectAct = botA.affectAdd; botA.affectAdd = []; if (botB.affectAct.includes('h')) { modB *= 0.5; } if (botB.affectAct.includes('d')) { modB *= 2; } if (botB.affectAct.includes('n')) { modB *= -1; } if (botB.shield > 0) { modB = (modB < 0) ? 0 : modB; botB.shield--; } botB.points += modB; botB.affectAct = botB.affectAdd; botB.affectAdd = []; } /* A=Add 5 points to your score [Costs 0.1 energy] R=Remove 5 points from opponent [Costs 0.1 energy] H=Half your next score [Costs 1 energy] Y=Half opponent's next score [Costs 1 energy] D=Double your next score [Costs 2 energy] T=Double opponent's next score [Costs 2 energy] N=Negate your next score [Costs 3 energy] O=Negate opponent's next score [Costs 3 energy] S=Shield for 5 turns [Costs 15 energy] X=Take five energy from opponent [Gives opponent 10 points] E=Refill five energy [Takes 10 points] */ ``` [Answer] # Doom: OX (Negate opponent - Take energy) Combo ``` function(coins, energy, obj) { let mycoin = coins[0] let yourcoin = coins[1] let myenergy = energy[0] let yourenergy = energy[1] if (obj.last === 'O') obj.last = 'X' else if (myenergy >= 3 && (yourcoin > 0 || yourenergy > 0)) obj.last = 'O' else if (mycoin >= 10 && myenergy < 3) obj.last = 'E' else obj.last = 'A' return obj.last } ``` If a player has zero points AND zero energy, it can do absolutely nothing. This bot, named "Doom", aims to put the opponent in this doomed state, and then happily accumulates its own score. [Here is a run against The Classic.](https://tio.run/##pVhdb5tIFH3PrxhZqxpqTMEWWtWJU3HbqvvQ3UrbfdiVZakYcOzKBgtwWyvht2fvwAAzMJ74wxI2uXfuOfdj5mDnu/fDS/1kvcuGURyEz88/vIQs4uyDl3mf12lGpmR2Q/D1WLzTV@RtwwnpuT2jNgVh6rdMyT6akOU@8rN1HGl@vI5Sg4RRmDwcDBIvvusMcb0kWmmeWfM7WydJmO2TiMz6bt/o/43Xv/35TPvTy1Zm4kVBvNX012P9yZrfFvHhJg1bICMJyB94/ScHc5RgYwXYB7z@kYP@rgS1rZNQjf5feH3por9VoztnoRv9j10GzFCkOBPQ6H@VgNolaF7A5kZ3U0F3U8EFm2oTZmR7oH7cv8Uy7EvtOcT7RPDZcy6qhENf3VAhsO1msXQCmIC58eiZmU4J9kEnjYVgf8R51Uz3UzImr14Rrc7rnljk6YmnQ4suwn3pwJWhU2JbFK2GvyNjMfIjF8nb3dLOBl15qmHd4NxuqtaT3cY7fMKRaVXHUTK@YuBO08s9s4wTolEtWSO0dYsfd8Sx6M1goHNzx4lCnKVVGH29eePHURpvQnMTP2icFplbb6dpjzusM0sNNvY0ixPvIcz16f230jP5jS3J2Ro0lDd5tRot7K6oMf@m66xK@s4k0MXMOfZZdRyYG1pum7n55HtYG@mRQQFn0j2O971JYyoT1dWR0I2EJjLnxtJMgbW4HsPC4Ccx6sxh0apmPW8GsmBkRTxnrY/CSDCzzqL9Meft3nIZ@pkbBPSZMpd4/KzjSVfrcBM0xLlQbr15WCHXDY66kzBl0a6J6NpMxGGNMFrxzDw3SHt9pU2t9aV5brTSrFqnm1n8Of4ZJu@9NKyOBkuPZQ/d9Gx5etax9Gx5etaR9OyX09vGgdvMilmgsVCdKjuMcuP1qUwVnW6E0DJtYVdy3mHhbTZHQTaYEoftjEYKa4rkegqgRgXFSkahIuDgC099KszdPl1pCKgfZztcxwbnsQUytpGCbfRCbYGKLbuODc5ji2RsYwXb@IXaIhVbfB0bnMeWSneJo9omTqs6prvq4/Wrz0MWh2VAv360cq8fExr/J6aEGb0TlgyJQya11EsYw6Yy9kgqvu@00nCLkqxbabVcSbwmgahJoBQMUArGsaaBqEkKCgqjlL2hkmIlo1DVcKFKgKhJl7G557EFMraRgu1ClQBRky5jc89ji2RsYwXbhSoBoiZdxuaex5ZKd4mj2iZOq7oXNAnkmuRKNMkVNcmVaJJ7giaBqEmg0iSQaBKoNIlvsZ@Z68jf7PEXcXE8OiW@piJxOkQghxidDBDJAYa2FIENjv6GbQfhAIrPO@p7hz97J4Vd@jQaDnl0/iGA/WuixKSrL/P1Zu0uEn6QsKThxNbD8dbDia2HY62HE1sPR1sPx1sPrPXQaj1ID12n9SC2Hm5v2iJUtR4krYdO6/Pn5j8Kz/8D "JavaScript (Node.js) – Try It Online") Doom wins against Classic with around 1600 - 1800 score, while Classic is always stuck at 0 score and 0 energy. Doom is arguably the strongest among the four bots posted so far (Classic, Greedy, Greedier and Doom), but my guess is it's still susceptible to some kind of anti-Doom. [Answer] # Doom-RX ``` function(coins, energy, obj) { let mycoin = coins[0] let yourcoin = coins[1] let myenergy = energy[0] let yourenergy = energy[1] if(!obj.last) obj.last = ' RXRX'; if(obj.last.length > 1) obj.last = obj.last.substring(1, 5) else if (obj.last === 'O') obj.last = 'X' else if (myenergy >= 3 && (yourcoin > 0 || yourenergy > 0)) obj.last = 'O' else if (mycoin >= 10 && myenergy < 3) obj.last = 'E' else obj.last = 'A' return obj.last.substring(0,1) } ``` Almost entirely derivative of [Bubbler's answer](https://codegolf.stackexchange.com/a/171832), but with a hardcoded opening sequence that counters that specific entry. [Here](https://tio.run/##3Vhbj6JIFH73V9SazQgrEtD4om1POLubfZlkktmXTjomg1AqExoMhbNrevjtPVVQQBWU1V6edn1Q@ty@c6sP6G/@d58EWXTIJ0ka4re3736GNmn@h5/7nyKSoxV6HiD6eS2/2SfxX/ACDb2h1YhCTIKOKDsmC7Q9JkEepYkRpFFCLIQTnO1OFko330weMcY5ejkxPYUqzZ6ddaM5pcdM0rlrwasKR3XVRdexq@a@0db4hSZgxz7JTVRfUbMR@vL05Wm0rK1qlR3jZJfv0SNyJftGT44bkmdRsjNcC83N0h/HBNMgyGgdVhTi80iGfBrJ1k1Rjys0Qx8@IKNpwSNy0I8fYmVUYsrhPvfCVa4r5DosWhP@Ac1kzz8FT1HuVfIM58csUZXsWK45KEqjwuqvCfTXBP4ja/I/nV09rMF6ORjUrUeH2D/9RUdm1B2nJPA3dTwYZnUgtmmGDMYOEQ3tLOnPA5o77GI8NoW504lCmpPajX2CNCFpjO043RkCt9gv/sEwXg@0ypxYfOgkTzN/hwtz9fi10ix@5SYFt6GC6qKoramEX5UVFl9Nk9fIvjmleTRvAZ2uwVJUQ0ftcrWY/JBWhoZoXIaz2YbT6@GiFVWJmnpP6HtC61kIQ2lnwBvcDGFjiXOY9qaw6VQTrdtxbDhY6S9Im4MwlcS8s1T@Wohyf7vFQe6FIbtHrBWaIO9pyD7CcdgCF1K5zerwQu4bHFNnmHBvz6bRjWc5Dm@E1fHn4rWFuvY1M3XsK/Ha6qRZt8608/RT@g/OfvcJrg8GT49nD/30XHV6zrn0XHV6zpn03PfTe0lDr50Vl0ArYSxVdZiSjT9iJFV2uqVBx3alrRS0k1LbLkcJNl6hOd@MlggbiOx@CGBCDcReBaEDEMKXmuZU2Icj2Rs0oHke7XQfGlyHFqrQphq06Tu1hTq0/D40uA4tUaHNNGizd2pLdGjpfWhwHRpRbslctybzTnWcd/XH69@RGLI8LGP28NHJvblNGOKfNCWa0UfJZILmaNFQvQIRt5XxW1L5tNNJwytLcpbKaoWSRE4CmZNASxigJYxzTQOZkzQQLIyW9iZaiL0KQlfDjSwBMifdhuZdhxaq0KYatBtZAmROug3Nuw4tUaHNNGg3sgTInHQbmncdGlFuyVy3JvNOde9wEqg5yVNwkidzkqfgJO8CTgKZk0DHSaDgJNBxktjiILejJIiP9H24PB69En9jJHF5iFAdYnpxgEQdYOIqI/DBsTfYrhMdQPn7wHQf6UvvopQr70aTiRhdvAnQ/rVectL1w3yzrH0j6YWEJw0Xth7Otx4ubD2caz1c2Ho423o433rgrYdO60F56HqtB7n1sBx0SahuPShaD73WF2/t/xPefgI)'s this run against Doom. Essentially, using R has less energy cost than O, so when both play OX against each other after the 4th turn Doom is stuck at 0/0, while Doom-RX survives at -30/1.8 and is able to recover. RXRX isn't the only sequence that works against Doom, but it does look to be among the most robust 4-letter sequences and I liked it best aesthetically. I'm sure there's a more effective approach to this than hard coding, though. Overall OX seems overbearingly powerful; I'd be surprised if an entry that didn't use it could beat this kind of strategy. [Answer] # Greedy ``` function(coins, energy, obj) { if (energy[0] < 0.2) return 'E'; else return 'A'; } ``` I'm probably misunderstanding the game, but I don't see any reason not to just increase your own points every round. [Answer] # Greedier: NE (Negate self - Refill energy) Combo ``` function(coins, energy, obj) { let mycoin = coins[0] let myenergy = energy[0] if (mycoin >= 10 && (obj.last === 'N' || myenergy <= 3.1)) obj.last = 'E' else if (mycoin >= 20 && myenergy >= 8) obj.last = 'N' else obj.last = 'A' return obj.last } ``` ### How it (may) work ``` N : Energy -= 3 E : Energy += 5; Points += -(-10) --------------------------------- Energy += 2; Points += 10 ``` So we don't even need to worry about being out of energy. [Here is the result against Greedy.](https://tio.run/##pVhNb5tAEL37V4ysqoYaE@zUUmXHqZi26iXKpcfIUjGsEyoHLMBpo4Tfnu4uCyyw3vjDBwfP7MybeTM87PzxnrzUT8JtNorigLy9PXkJrOLsu5d5N2GawQLuekBfL/ydvSLvkcyg7/atyhSQ1G@Zkl00g/Uu8rMwjgw/DqPUAhKR5P7Zgnj1xxQZwzUYhfnOWcIVOPbEhIRkuySCwY/BnB8im5RURpcac27OrW5Z2C0LTyhrQzJ4fGZ@ygA/RsuTPEUI9VW1V92IsOsFjB34@BEMmtbeeIzLxQIGtwN4fa0zXC3g0h6bJtSnWN91282UE56yiqaWL83QWylUtruFXZBYekoie8t5r1fSAtuN9/yT0mmUbNCF@EUDt4ZZzGMdJ2CwTQlpamdO/1zB1GEXw6EpzYSyjXGWlmHsdXHhx1Eab4i9ie8NadPsR29rGC9b2miWWmIkaRYn3j3JzcX178Iz@yCO5OIMNRQXeXmaWsQV7zH/bZqiS/YuFtyllUvodIBz2Y0t91i45eL7tDfow5Cns9n@0ev@rDYVhZr6SOxGYh2ZS2OppyAorsawsuRJTDpzWLW6CZf1QFYCjMdL1mrDJw2zYJbaX3LZ7q3XxM/cIGCKsVR4/KzjSR9Csglq4LzRbrU8opHzBsfcCUlFtGvT7MZdM48gwmrFC/PSgvb5Ujda5wvz0mqVWVJn2ll8E/8lyTcvJeWtIcoT1WO3vLG6PGdfeWN1ec6e8sbvl/cYB249K2HB2sKEqmCYyo03YDrFma6lyqFCJ2@l5B1xb70cHGy4gKnYjFoLK4jkfAhkRg3EgwpCByCl557qrrC3u/TBoAnN/WjP56HhcWiBCm2iQZu801ugQ8vOQ8Pj0CIV2qUG7fKd3iIdWnweGh6Hliq3ZKpbk2mrO6G7@tvr30BOyW@WIftK06q9ekwY8sdr@GzC18aJEUxhVim9ApDUjYknEv8K1arC5R05c2WzUkeyJGFTklCrF6jVi32coSRJqIVgabSqN9JCPKi60PVwokhgU5JOQ3OPQwtUaBMN2okigU1JOg3NPQ4tUqFdatBOFAlsStJpaO5xaKlyS6a6NZm2untHklAtSa5CktymJLldSXIPkCRsShLqJAkVkoQ6SZIZ9jM7jPzNjv5W5XdHp8NPTCMOTxGoU0wOThCpE4zGygxibtfQ1WnKP/97xXxfwaFUs8/KZ9FoJGeXnwGUvzqqWXT5Vb7a1e6hxs8RUTQeSD3upx4PpB73UY8HUo97qcf91KOgHlvUo/Ke61CPTepx3mtrUEk9KqjHDvX5W/3/hLf/ "JavaScript (Node.js) – Try It Online") Greedy gets only 2410 since it has to refill its energy from time to time. On the other hand, Greedier achieves full 2500 score if the opponent doesn't interfere. The code above includes a bit of anti-failure measures: * If it's getting out of energy somehow, force refill energy (E). * If it's out of points, try getting some basic points (A). * Use negate (N) only if it has enough energy to run it even if the opponent plays drain energy (X) i.e. `3 + 5 = 8`, AND it has enough coins to run E next turn even if the opponent plays double opponent (T) + reduce opponent 5 (R) i.e. `10 + 5 * 2 = 20`. [Answer] # Doom EX (Rock, paper, scissors!) ``` function(coins, energy, obj) { let mycoin = coins[0] let yourcoin = coins[1] let myenergy = energy[0] let yourenergy = energy[1] if(!obj.last) obj.last = ' EXEX'; if(obj.last.length > 1) obj.last = obj.last.substring(1, 5) else if (obj.last === 'O') obj.last = 'X' else if (myenergy >= 3 && (yourcoin > 0 || yourenergy > 0)) obj.last = 'O' else if (mycoin >= 10 && myenergy < 3) obj.last = 'E' else obj.last = 'A' return obj.last.substring(0,1) } ``` All credit goes to @Bubbler and @ripkoops, I just wanted to point this out. This version manages to beat Doom RX, but loses to Doom OX. Looks like this KOTH is rock paper scissors in disguise... [RX vs EX](https://tio.run/##7Vjfj5s4EH7PX@FGVQMXQiFRXpLNVkxvdS@VKvVeVlpFKglOQsVChJ1eoy1/@54BAzY43vx4OunykLAznvlmPo8/YH/4P32yTsM9HcVJgF9ff/opWiX0T5/6X0JC0QI99RD7vBTf@Sf2n/EM9b2@VZsCTNYtU3qIZ2hziNc0TGJjnYQxsRCOcbo9WihZ/TB5xghT9HzM/QyqWPbkLGvPMTmkks9dClFlOuYrL9qBbTePDTfGO1aAHfmEmqi6YssG6Nvjt8fBvFpVuewIx1u6Q/fIldbXfnJYEZqG8dZwLTQ1i3gcEcySIKMJWDCIrwMZ8nEgr66bul@gCfrwARk1BffIQb9/i50xiymn@9pJV4YukOvk2er0d2giRz4IkaLdK@0ppoc0VrXsWK7Zy4pFmdUdE@iOCfzXx@Th8eH/MblhTHrLea9XbTraR/7xLzYsRrXXTH7@Znn2hllyvElSZOS6FDIkZ85@7tDUyS@GQ1OYODZLkFBShbHPx49sHmKSRNiOkq0h6Jr97O8N42XP2qbE4gNHaJL6W5yZi/vvpWf2ni/J@BpmKC@yajWz8Kui5ey7afIu828upx6rXEBnIzgX3dByu9wtFt9nvaE@Ghbp7Px0sev@rDGVhZr6SOhGQhOZCdvS7AKnuN6GlSXuxLizD6tWN@Fy3vg4WBEvWOtDOJbMnFlmf8lEu7/Z4DX1giC/Py0VnjXteMguxFHQAGdSu/Xw8EZu27jcnWLCoz2bZTee5DycCKsVz81LC7XXV6rYWl@al1arzIo606bJl@QfnH72Ca6OBi@PVw/d8lx1ec6p8lx1ec6J8ty3y3tOAq/ZK26BxpLLVskwUx9/kKtWwXSji47tSlMpeEeFtxmOAmy4QFM@GY0y1hDp7RCQGzUQOxWEDkBIX3jqU2HvD2RnsITmabTjbWhwGVqgQhtr0MZv9Bbo0OhtaHAZWqxCm2jQJm/0FuvQktvQ4DI0opySqW5Mpq3uuO7qj9evgZiyOCzD/GmkVXt9mzDEP1lJrKJP0pIRmqJZLfUKRNx0xm9JxeNPqwyvaMmZK7sVWhI1CWRNAq1ggFYwTpEGsiZpIPI0WtkbaSF2KghdD1eqBMiadB2adxlaoEIba9CuVAmQNek6NO8ytFiFNtGgXakSIGvSdWjeZWhEOSVT3ZhMW929oUmg1iRPoUmerEmeQpO8MzQJZE0CnSaBQpNAp0kixWtqh/E6OrB38eJ4dFr8IxeJ81ME6hTjsxPE6gQjV5mBb1z@StsOYhtQ/N7lvk/sLXhW2JV3o9FIzC7eBBh/TZRcdPUwXw9rd5H0QsKLhjOph9PUw5nUwynq4Uzq4ST1cJp64NRDi3pQHroO9SBTD/NeW4Qq6kFBPXSoz16b/yi8/gs) [Answer] # The Classic (aka Random Player) ``` function(coins, energy, obj) { if (energy[0]<1) return ['A','R','X'][(Math.random()*3)|0]; else if (energy[0]<2) return ['A','R','H','Y','X'][(Math.random()*5)|0]; else if (energy[0]<3) return ['A','R','H','Y','D','T','X'][(Math.random()*7)|0]; else if (energy[0]<10) return ['A','R','H','Y','D','T','X','N','O'][(Math.random()*9)|0]; else if (energy[0]<15) return ['A','R','H','Y','D','T','X','N','O','E'][(Math.random()*10)|0]; else return ['A','R','H','Y','D','T','X','N','O','E','S'][(Math.random()*11)|0]; } ``` ]
[Question] [ This is [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'"). This is the **Robbers** thread. For the cops thread, go [here](https://codegolf.stackexchange.com/questions/128065/stealing-sequences-cops). I've noticed a number of OEIS challenges since I joined the site. It seems only fair that we have a cops-and-robbers challenge that determines who is the master of online integer sequences, once and for all. ## Cops Write a program or function that, given no input, deterministically prints any sequence from the [OEIS](https://oeis.org/). By deleting some subset of the characters, your program must be able to print a different OEIS sequence when run in the same language. The new sequence must be entirely new, not just the first by a different name or with a different offset. Neither sequence may be simply a repeated constant value. You must provide the first function, along with the name of the OEIS sequence so correctness can be verified. It's OK if behavior gets questionable around your language's MAX\_INT value or 256, whichever is larger. ## Robbers Delete characters from some Cop's submission such that your new program outputs any other sequence from the OEIS. Provide the new function along with the name of the new OEIS sequence. Your new sequence may not simply be a repeated constant value. It's in your best interest to delete as many characters from the Cop's submission as possible. If another robber (anyone except the Cop who authored the original program) comes along and finds a shorter solution that finds another *different* sequence, that robber steals your point. (Note that simply golfing off characters and printing the same sequence is not sufficient to steal the point.) ## Rules & Scoring If, after one week, nobody has been able to crack your solution, you can mark your solution as safe by providing the second program along with the name of the sequence it generates. You get one point for each safe posting and one point for each submission you crack. Note that another robber can steal your point from the cracked submission at any time by providing a shorter program that yields a different sequence. Cops may only post one challenge per language. The player with the most points at 12:00 UTC on 7 July wins. [Answer] # [C (gcc)](https://gcc.gnu.org/), [Govind Parmar](https://codegolf.stackexchange.com/a/128085/62346) 142 bytes deleted Golfed more thanks to @StephenS. I'm not sure it matters, but just for the spirit of the site! ``` #include<stdio.h> #include<limits.h> main(){int i,n;for(i=0;i<INT_MAX;i++){n=i;printf("%d,",n);}} ``` [Try it online!](https://tio.run/##S9ZNT07@/185My85pzQl1aa4JCUzXy/DjgsukpOZm1lSDBLKTczM09CszswrUcjUybNOyy/SyLQ1sM608fQLifd1jLDO1NbWrM6zzbQuKAIqStNQUk3RUdLJ07Surf3/HwA "C (gcc) – Try It Online") Sequence: [A001477](https://oeis.org/A001477) [Answer] [PHP](https://codegolf.stackexchange.com/a/128070/194), [Jörg Hülsermann](https://codegolf.stackexchange.com/users/59107/j%c3%b6rg-h%c3%bclsermann), 1 byte deleted ``` for(;;)echo+$i,","; ``` Produces [A000004](https://oeis.org/A000004) [Answer] # [MarioLANG](https://esolangs.org/wiki/MarioLANG), [marcosm](https://codegolf.stackexchange.com/a/128086/48934), 13 bytes deleted ``` >+:< ===#= ``` [Try it online!](https://tio.run/##y00syszPScxL///fTtvKhsvW1lbZ9v9/AA "MarioLANG – Try It Online") [A109613](http://oeis.org/A109613). [Answer] # [cQuents](https://github.com/stestoltz/cQuents), [Stephen S](https://codegolf.stackexchange.com/a/128095/48934), 1 byte deleted ``` =0,11:z+y ``` [A022345](https://oeis.org/A022345). [Answer] # Python 2, [juniorRubyist](https://codegolf.stackexchange.com/a/128329/65836), 253 bytes deleted ``` while True:print 6,4 ``` [Try it online!](https://tio.run/##K6gsycjPM9ItqCyo/P@/PCMzJ1UhpKg01aqgKDOvRMFMx@T/fwA "Python 2 (PyPy) – Try It Online") Not sure how valid this is, because of the newlines, but I believe whitespace is irrelevant. TIL that if I could add a comma at the end, it would fix the whitespace. [A226294](http://oeis.org/A226294) [Answer] # [PHP](https://codegolf.stackexchange.com/a/128070/194), [Jörg Hülsermann](https://codegolf.stackexchange.com/users/59107/j%c3%b6rg-h%c3%bclsermann), 5 bytes deleted ``` for(;;)echo+$i; ``` Produces [A000004](https://oeis.org/A000004) [Answer] # Python 2, [juniorRubyist](https://codegolf.stackexchange.com/a/128329/70708), 114 bytes deleted [cracked](https://codegolf.stackexchange.com/a/128331/70708) ``` import zlib, base64;exec(zlib.decompress(base64.b64decode('eJzLtDUAAAHoANc='))) while True:print i,;exec(zlib.decompress(base64.b64decode('eJzL1LY1BAAC1AED'))) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PzO3IL@oRKEqJzNJRyEpsTjVzMQ6tSI1WQMkopeSmpyfW1CUWlysAZHTSzIzAQmmpGqop3pV@ZS4hDo6OnrkO/ol26prampylWdk5qQqhBSVploVFGXmlShk6pBinqFPpKGTo6OzoaOrC8i8//8B "Python 2 – Try It Online") [A001477](http://oeis.org/A001477). ]
[Question] [ Input into your program a black and white image. (png, jpg, etc) Convert the image to a 2D matrix of pixels, where each index is the grayscale value of the image. Take each index of the matrix and average the 8 pixels around it. Then replace that index with the average. For example if you had: ``` 120 80 60 20 10 30 40 100 05 ``` If you were finding the average for 10, the result would be `56.875`, which is `(120,80,60,30,05,100,40,20)/8`. Round to up to the nearest integer (57) and replace the index. The result of this iteration would be ``` 120 80 60 20 57 30 40 100 05 ``` If you are finding the average for a pixel on an edge then only take values that are valid. In the example above if you were finding the average for `20` You would only consider `120, 80, 57, 100, and 40` which is `79.4` rounded to `80`. You may start at any index of the graph but it must be in order. For example you could do ``` [0][0], [0][1], ... [0][n], then [1][0], [1][1],... [1][n] ``` Once the averaging is complete, convert the matrix back into a new image. Display the new image as the output of the program. (Or save it and add it in your solution). The result of your code should be a blurry looking image but much smoother than the original. Example Input [![enter image description here](https://i.stack.imgur.com/y4Zj9.jpg)](https://i.stack.imgur.com/y4Zj9.jpg) Example Output [![enter image description here](https://i.stack.imgur.com/DYAQ0.png)](https://i.stack.imgur.com/DYAQ0.png) Example Input two [![enter image description here](https://i.stack.imgur.com/eR8EE.png)](https://i.stack.imgur.com/eR8EE.png) Example Output two [![enter image description here](https://i.stack.imgur.com/RXHFI.png)](https://i.stack.imgur.com/RXHFI.png) Please provide your code and start and end image results. **Q/A** *1Q. If one of the 8 neighbors has already been changed, should the average be calculated based on this new value, or based on the original values? That is, does the order of calculation affect the end result?* 1A Yes, You should change each index with new values from any potential indices done before. That is why you need to go left-right, top-bottom etc. In order. *2Q. Could you clarify what is meant by "must be in order"? Does this mean that only raster order/reading order is acceptable? Or does it mean that the order must be the same each time the code is run? Would a spiral be valid? Or a shuffled order that is always the same?* 2A. You should go left to right, right to left, top to bottom, or bottom to top. I.E. Do all of the 0th row, do all of the 1st row,... do all of the nth row [Answer] # J, ~~90~~ 82 bytes ``` [:((=i.@$){"0 1],"+3 3((+/>.@%#)@(_-.~(<<<4){,);._3)_,.~_,._,~_,])&.>/(#<@-#\)@,,< ``` This iterates over pixels from left-to-right, then top-to-bottom. You can see the progression of values here. ``` |. ((=i.@$){"0 1],"+3 3((+/>.@%#)@(_-.~(<<<4){,);._3)_,.~_,._,~_,])&.>/\. ((#<@-#\)@,,<) 120 80 60 , 20 10 30 ,: 40 100 5 ┌──────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬─────────┬────────┬────────┐ │120 80 60│37 80 60│37 32 60│37 32 24│37 32 24│37 32 24│37 32 24│37 32 24│37 32 24│37 32 24│ │ 20 10 30│20 10 30│20 10 30│20 10 30│44 10 30│44 39 30│44 39 40│44 39 40│44 39 40│44 39 40│ │ 40 100 5│40 100 5│40 100 5│40 100 5│40 100 5│40 100 5│40 100 5│61 100 5│61 38 5│61 38 39│ └──────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴─────────┴────────┴────────┘ ``` The output for the first sample image is (converting from an array of pixels to a bmp) ![sample](https://i.stack.imgur.com/gKVt8.png) [Answer] # PHP, 321 bytes ``` $i=imagecreatefromjpeg($f="96512.jpg");list($w,$h)=getimagesize($f);for($y=$h;$y--;)for($x=$w;$x--;$s=$n=0){for($a=-2;$a++<1;)for($b=-2;$b++<1;)if(false!==($d=imagecolorat($i,$x+$a,$y+$b))){$n++;$s+=imagecolorsforindex($i,$d)[red];}imagesetpixel($i,$x,$y,imagecolorallocate($i,$r=ceil($s/$n),$r,$r));}imagejpeg($i,"b$f"); ``` does the blurring from bottom to top, from right to left. -2 bytes for a gif or png; could save even more with a shorter file name and -6 if rounding down was allowed. pity that image processing functions have so long names. but I´m fine. pretty byte count. [![blurred example image](https://i.stack.imgur.com/33PxE.jpg)](https://i.stack.imgur.com/33PxE.jpg) [Answer] # PHP, 70 bytes ``` imagefilter($i=imagecreatefromjpeg($f="i.jpg"),10,0);imagejpeg($i,$f); ``` Overwrites the original image file. Run with `-r`. -2 bytes if you use a gif or png. --- I thought PHP might have a built-in for this, and indeed: `10` stands for `IMG_FILTER_SMOOTH`; and `0` is the weight parameter. See [the GD library source code](https://github.com/libgd/libgd/blob/master/src/gd_filter.c): This calls `gdImageSmooth` which calls `gdImageConvolution` with the requested matrix. I am not sure what it does at the edges; but overall it does the smoothing from top to bottom, from left to right. [![enter image description here](https://i.stack.imgur.com/ZPV9k.jpg)](https://i.stack.imgur.com/ZPV9k.jpg) [Answer] ## Ruby 2.3.1, 338 bytes ``` ->w{d,k=16843008,ChunkyPNG::Canvas.from_file(w);(0..k.height-1).each do |y|;(0..k.width-1).each do |x|;t,i,a=0,0,[[x-1,y-1],[x,y-1],[x+1,y-1],[x-1,y],[x+1,y],[x,y+1],[x,y+1],[x+1,y+1]];a.each do |c|; next unless k.include_xy?(c[0],c[1]);t=t+k.[](c[0],c[1]);i=i+1;end;n=t/i;while(n%d)>0 do;n=n+1;end;k.[]=(x,y,n-1);end;end;k.save("w")} ``` * Uses oily\_png/chunky\_png for image handling. * Goes left to right, top to bottom doing the averaging. * Since chunky uses integer color values, I'm doing a really, really slow up rounding method to get averaged color values to an actual grayscale value. Example output(that took a very, very long time): [![enter image description here](https://i.stack.imgur.com/jBwql.png)](https://i.stack.imgur.com/jBwql.png) # Ungolfed, slightly modded, and commented ``` require 'oily_png' l = -> img { time_begin = Time.new d = 16843008 k = ChunkyPNG::Canvas.from_file(img) # go line by line, pixel by pixel (0..k.height-1).each do |y| (0..k.width-1).each do |x| total, i = 0, 0 p "Starting color is #{curr} or #{curr.to_s(16)}" # set the coords around the pixel we want around = [[x-1,y-1], [x, y-1], [x+1, y-1], [x-1,y], [x+1, y], [x,y+1], [x, y+1], [x+1, y+1]] # grab the 8 colors around the current pixel around.each do |coords| # ignore values that are not in bounds next unless k.include_xy?(coords[0], coords[1]) # get a total to average later total = total + k.[](coords[0], coords[1]) # increment i = i+1 end # get the average value for the new color new_color = total/i # since new color will likely not be a grayscale value, # round up to the nearest grayscale value. # This is unfortunately really slow. while (new_color%d) > 0 do new_color = new_color+1 end p "New color is now #{new_color-1} or #{(new_color-1).to_s(16)}" # set the color and # remove one from the color value to get full alpha instead of none. k.[]=(x, y, new_color-1) end end # save the complete image k.save("#{Time.new}.png") } l.($*[0]) ``` Could certainly do things a bit more efficiently, unfortunately I'm not quite how to. There's got to be a more clever way of handling the coordinate management for the 8 surrounding locations. [Answer] ## Racket 346 bytes ``` (let((s1 sub1)(a1 add1)(lr list-ref)(ln length))(define(g r c)(if(or(> r(s1(ln l)))(> c(s1(ln(lr l 0))))(< r 0)(< c 0)) #f(lr(lr l r)c)))(define(ng r c)(define h'(-1 0 1))(define k(filter(λ(x)x)(for*/list((i h)(j h)#:unless(= 0 i j)) (g (+ r i)(+ c j)))))(round(/(apply + k)(ln k))))(for/list((i(ln l)))(for/list((j(length (lr l 0))))(ng i j)))) ``` Ungolfed (comments follow ';'): ``` (define (f l) (define (get r c) ; to get value at a row,col (if (or (> r (sub1 (length l))) (> c (sub1 (length (list-ref l 0)))) (< r 0) (< c 0)) ; if row/col number is invalid #f (list-ref (list-ref l r) c))) ; return false else return value (define (neighbors r c) ; finds average of neighboring values (define h '(-1 0 1)) (define k (filter ; filter out false from list (lambda(x) x) (for*/list ((i h)(j h) #:unless (= 0 i j)) (get (+ r i) (+ c j))))) (round(/(apply + k)(length k)))) ; find average of values (sum/length of list) (for/list ((i (length l))) ; create a list of lists of average values (for/list ((j (length (list-ref l 0)))) (neighbors i j)) )) ``` Testing: ``` (f (list '(120 80 60) '(20 10 30) '(40 100 5))) ``` Output: ``` '((37 48 40) (70 57 51) (43 21 47)) ``` ]
[Question] [ The official release of the Nintendo 64 in North America was on September 29, 1996.[[1]](http://en.wikipedia.org/wiki/Nintendo_64) I figured that this anniversary deserved an ASCII art challenge. There's one small twist though, you have to output a different ASCII art for each of three different inputs. If the input is `1`, output this ASCII art of an N64 Controller: [(source)](http://osrevad.westopia.net/asciicontrollers.php) ``` | | _,.-'-'-.,_ ______| |______ ,-' | NINTENDO | `-. ,' _ `. / _| |_ (^) \ | |_ _| (<) (>) | \ |_| (S) (B) (v) / |`. ___ (A) ,'| | `-.______ ,' _ `. ______,-' | | | `. | (_) | ,' | | | | \`.___,'/ | | | | | | | | | / | | \ | \ / | | \ / `._,' \ / `._,' \ / `._,' ``` If the input is `2`, output this ASCII art of the N64 logo:[(source)](http://www.asciiartfarts.com/20020320.html) ``` .-"-. .-" "-. /"-. .-| / "-.-" | / / | .-"-. / / | .-"-. .-" "-/ / | .-" "-. |-. .-"\ / | /"-. .-| | '-.-" \ / | /' "-.-" | | \ \/ .-"-. /' | | | \ \.-" "-. | | | \ |-. .-"\ | | | \ | "-.-" '\ | | | \ | | '\ | | | |\ \ | | '\ | | | | \ \ | | '\| | | | \ \ | | :\. | | | \ \| | | \. | | | \ | | \. | '-. | .-"\ | | '.\. .-' "-|-" \ | | "-\.-" \ | | \ | | "-. | .-' "-|-" ``` Finally, if the input is `3`, outout this ASCII art of a console and TV: [(source)](http://nintendo64.ascii.uk/) ``` o o / \ / \ / \ / ______________ |.------------.| || || || || || || || || ||____________||_ |OO ....... OO | `-. '------_.-._---' _.' _____|| ||___/_ / _.-|| N ||-._ \ .-._ / -'_.---------._'- \ ,'___i-i___ /_.-'_ NINTENDO _'-._\ ' /_+ o :::\ |`-i /m\/m\|\|/=,/m\i-'| | || \ O / || | |_\_/\_/___\_/'./| | | \/ \ / \/ `-' '-.`-' , V `---' ``` ## Rules: * Input may be either as a number or a string/char. * You may have any amount of leading or trailing spaces and trailing or leading newlines. (Output must be aligned correctly though) * Your submission may be either a full program or a function. * No retrieving the ASCII art from the internet. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so smallest byte count wins. [Answer] # Javascript ES6, 1175 bytes Using a simple [Run Length Encoding](https://en.wikipedia.org/wiki/Run-length_encoding) to encode just the spaces. ``` let F= z=>[(f=d=>d.replace(/\d+/g,e=>' '.repeat(e)))(`17|1| 13_,.-'-'-.,_ 6______|11|______ 3,-'6|2NINTENDO1|6\`-. 1,'3_26\`. /3_|1|_21(^)3\\ |2|_3_|18(<)1(>)1| \\4|_|9(S)5(B)2(v)3/ |\`.14___7(A)4,'| |2\`-.______3,'1_1\`.3______,-'2| |6|4\`.1|1(_)1|1,'4|6| |6|6\\\`.___,'/6|6| |6|6|7|6|6| |6/6|7|6\\6| \\5/7|7|7\\5/ 1\`._,'8\\7/8\`._,' 15\\5/ 16\`._,'`),f(`18.-"-. 15.-"5"-. 14/"-.5.-| 13/4"-.-"2| 12/6/5| 3.-"-.3/6/6|7.-"-. .-"5"-/6/7|4.-"5"-. |-.5.-"\\4/8|3/"-.5.-| |2'-.-"4\\2/9|1/'4"-.-"2| |5\\6\\/3.-"-.2/'8|4| |6\\6\\.-"5"-.9|4| |7\\6|-.5.-"\\8|4| |8\\5|2"-.-"4'\\6|4| |9\\4|4|8'\\4|4| |4|\\4\\3|4|10'\\2|4| |4|1\\4\\2|4|12'\\|4| |4|2\\4\\1|4|4:\\.12| |4|3\\4\\|4|4|2\\.10| |4|4\\9|4|4\\.8| '-.2|2.-"\\8|4|4'.\\.4.-' 3"-|-"4\\7|4|6"-\\.-" 13\\6|4| 14\\5|4| 15"-.2|2.-' 18"-|-"`),f(`14o 5o7/ 6\\5/ 7\\3/ 8\\1/ 3______________ 2|.------------.| 2||12|| 2||12|| 2||12|| 2||12|| 2||____________||_ 2|OO1.......1OO1|1\`-. 2'------_.-._---'1_.'2 3_____||3||___/_ 2/2_.-||1N1||-._2\\6.-._ 1/1-'_.---------._'-1\\4,'___i-i___ /_.-'_2NINTENDO1_'-._\\2'1/_+2o1:::\\ |\`-i1/m\\/m\\|\\|/=,/m\\i-'|1|1||1\\1O1/1|| |2|_\\_/\\_/___\\_/'./|2|1|1\\/2\\1/2\\/ \`-'14'-.\`-'2,6V 20\`---'`)][z-1] G=_=>h.innerHTML = F(a.value) h.innerHTML = F(1) ``` ``` <input id=a onchange="G()" type="number" value="1"></input> <pre id=h> ``` [Answer] ## JavaScript (ES6), ~~907~~ ~~904~~ 903 bytes Implements a compression by successive substitutions of the most frequent sub-strings. This can be compressed significantly more (down to about 850 bytes) by assuming Windows-125x encoding and using replacement characters in the range `0xA0` - `0xFF`. But the result is just ugly. :-) ``` let f = n=>[...Array(78)].map((_,i)=>s=~":<=>ABNOSV\\^_`imov|".indexOf((c=String.fromCharCode(125-i)))?s:s.split(c).join(['\\','NINTENDO',` `][c]||"9|XsD'RE405398T08kU8K0\"-G/'0|W7/;_E/C62G5|557970..-\"6_ /|52F8@04D\"`.-','??7 25\";7|3 3|4 .-662|---. |4|43__4433 ".substr(k+=2,2)),s="c99JE_,zP;,_27fX39fe,PH3197`;2 MG_cwQ2/G_|9_cE(^)G0@F_G_Xw(<) (>)9208_X (S)E(B)3(v)n@Q57ZK(A)4M|@3`;fGM _ QGf,PF@H4Q9 (_)9 M8H@HaQZM/HH@HHbHH@jHbaH20gbbqg2 Q_M50K/5Q_MJqgJ5Q_M~c3DIJKyIJjIED|Jg4I[FJ4/j49eDInjHKDI2yp/jb4yI@;ERT/dnIED|@3';[x3/59Y'4I[F@E0a/GDI3/'dUaayI59UqH;ER0dU5T93I[4lHU5 0885l8rt3uwlFr tF854l|r3tu4:0.5rGt|[[email protected]](/cdn-cgi/l/email-protection)';F3R0d84'.0.4zep|[xb87p0RJE0H8J7TuJKIF3zJwp|[~57o2EoK/2ag2qnJ0YeCCfW.LL?-;k{{{{|CCC||_WOO ]]]. OO9 `;23'L?_.h?P _.'eC_||3}Z/_23/3_D|| N}h307.h2Y P_.LLh'- TMZi-iZ2/_z_31 _'h03'Y_+3o :::0@`-iYm0/m0|0|/=,/m0iP|9} 0 OY}@F_0_/0_/Z0_/'./|F9 0/30Y30/2`P57';`P3,7VJ54`?P",k=-2)&&s.split`~`[n-1] console.log(f(1)); console.log(f(2)); console.log(f(3)); ``` ### Making-Of The above JS was generated with the following PHP script, where `"n64.txt"` is basically the concatenation of the 3 original pictures separated with `~` characters. ``` <?php $str = file_get_contents("n64.txt"); // ignore line-breaks between 2 pictures $str = str_replace("~\n", "~", $str); // replace backslashes with 0's $str = str_replace("\\", "0", $str); // replace 'NINTENDO' with 1's to have more uppercase letters // available as replacement characters $str = str_replace("NINTENDO", "1", $str); // replace line-breaks with 2's $str = str_replace("\n", "2", $str); // $skipped is the list of characters that can't be used as replacement // characters (backslash + anything existing in the original string) $skipped = ''; // $dic is the replacement dictionary $dic = ''; for($i = 0; $i < 75; $i++) { // $r = current replacement character $r = chr(51 + $i); // can we use it? if($r == "\\" || strpos($str, $r) !== false) { $skipped .= $r; continue; } // look for the most frequent 2-character sub-string $count = array(); for($n = 0; $n < strlen($str) - 1; $n++) { $s = substr($str, $n, 2); $count[$s] = isset($count[$s]) ? $count[$s] : 0; $count[$s]++; } asort($count); $keys = array_keys($count); $s = array_pop($keys); // add it to the dictionary $dic = $s.$dic; // replace all occurences with the replacement character $str = str_replace($s, $r, $str); printf("'%s' => '%s' %d\n", $s, $r, strlen($str)); } // generate JS file_put_contents( "n64.js", sprintf( "n=>[...Array(78)].map((_,i)=>". "s=~\"%s\".indexOf((c=String.fromCharCode(125-i)))?s:". "s.split(c).join(['\\\\','NINTENDO',`\n`][c]||\"%s\".substr(k+=2,2)),". "s=\"%s\",k=-2)". "&&s.split`~`[n-1]", str_replace("\\", "\\\\", $skipped), str_replace('"', '\"', $dic), $str ) ); ?> ``` [Answer] # Racket, 1059 bytes ``` (require file/gunzip net/base64)(display((λ(o)(gunzip-through-ports(open-input-bytes(base64-decode(list-ref'(#"H4sICMov7lcCAzEAdZExDsMgDEV3TuENkAhcoKrUqh2ypEM7osIpOvnwtTEkgaaOFIvvZ8efAAyBgKoTkvOTpse7VAupBO6bROK6m3QbBMu8vO7L7QGVzZNX4Lie4G9krwITtMgxZd6W3lEhCNFt0piTBXO25CXKfhtjnlbylbL58CEozL4fQG4afym808hfJAvitUjkozSKVKwXqvpnM5RNokXEd7uJniI3mcc6HTp1pBCOjisVDqnYqLiHRqpiQdHKyWno1K1Lqmq47bX351cy/AXpeU7EYwIAAA=="#"H4sICNkv7lcCAzIAbdIxDgQhCAXQfk5BbKzUfs/CUTj8qiACMo2J/xl/cADi11tp/Xs39/pGY24JIR8NObCO+mjYZUf70pgAuUq3g1fMbEPSSgUt3NIVnhu1yVE0cMpRXX/ugpziuJ3ZaY8jlZpikMtDY+1ECiUtNvtjLpmSnaNYKwkP9ZKtk3BolMt6eeiVP+z2wJVCyZa11kjAMECe75V1DZCyAe6SnW1v9dvvQfruEEdV2no3/z/7OUOSpRE/POm9Tzpr/AEE2h7HhgMAAA=="#"H4sICOIv7lcCAzMApVG7DsIwDNzzFd48UNt7JTYYWNoFMUVy1gyIH/DHc0l4tBIb1yjxXf1MiLZ4pHG8qA1Kecc6/RCwbvsOUEJlA40mxbZY/Clt64E1bV1JBwhmUBGFzKMFV1HHyeTKRJ+me/KezloSg6wCcYGIiPf41MITfgv7dzR1luEwMTJUqW16gwcjcrks1/NyWgle6nBjMj+0C57nOacoUsnuGSty2HGCUYUDnaN+phXVMCz6C89uWEiOndWahi9bfwBslgom2wE1uzYNekv0A6XfyBPSqZrcBwIAAA==")(-(read)1))))o)(get-output-string o))(open-output-string))) ``` Just gzipped data encoded as base64. ## Ungolfed ``` (require file/gunzip net/base64) (display ((λ (o) (gunzip-through-ports (open-input-bytes (base64-decode (list-ref '(#"H4sICMov7lcCAzEAdZExDsMgDEV3TuENkAhcoKrUqh2ypEM7osIpOvnwtTEkgaaOFIvvZ8efAAyBgKoTkvOTpse7VAupBO6bROK6m3QbBMu8vO7L7QGVzZNX4Lie4G9krwITtMgxZd6W3lEhCNFt0piTBXO25CXKfhtjnlbylbL58CEozL4fQG4afym808hfJAvitUjkozSKVKwXqvpnM5RNokXEd7uJniI3mcc6HTp1pBCOjisVDqnYqLiHRqpiQdHKyWno1K1Lqmq47bX351cy/AXpeU7EYwIAAA==" #"H4sICNkv7lcCAzIAbdIxDgQhCAXQfk5BbKzUfs/CUTj8qiACMo2J/xl/cADi11tp/Xs39/pGY24JIR8NObCO+mjYZUf70pgAuUq3g1fMbEPSSgUt3NIVnhu1yVE0cMpRXX/ugpziuJ3ZaY8jlZpikMtDY+1ECiUtNvtjLpmSnaNYKwkP9ZKtk3BolMt6eeiVP+z2wJVCyZa11kjAMECe75V1DZCyAe6SnW1v9dvvQfruEEdV2no3/z/7OUOSpRE/POm9Tzpr/AEE2h7HhgMAAA==" #"H4sICOIv7lcCAzMApVG7DsIwDNzzFd48UNt7JTYYWNoFMUVy1gyIH/DHc0l4tBIb1yjxXf1MiLZ4pHG8qA1Kecc6/RCwbvsOUEJlA40mxbZY/Clt64E1bV1JBwhmUBGFzKMFV1HHyeTKRJ+me/KezloSg6wCcYGIiPf41MITfgv7dzR1luEwMTJUqW16gwcjcrks1/NyWgle6nBjMj+0C57nOacoUsnuGSty2HGCUYUDnaN+phXVMCz6C89uWEiOndWahi9bfwBslgom2wE1uzYNekv0A6XfyBPSqZrcBwIAAA==") (- (read) 1)))) o) (get-output-string o)) (open-output-string))) ``` [Answer] # PHP, ~~2113~~ 2112 bytes If nobody else is going to compete I'll just grab the trophy and leave.. ``` <?php function a($n){if($n<2){?> | | _,.-'-'-.,_ ______| |______ ,-' | NINTENDO | `-. ,' _ `. / _| |_ (^) \ | |_ _| (<) (>) | \ |_| (S) (B) (v) / |`. ___ (A) ,'| | `-.______ ,' _ `. ______,-' | | | `. | (_) | ,' | | | | \`.___,'/ | | | | | | | | | / | | \ | \ / | | \ / `._,' \ / `._,' \ / `._,'<?php }else if($n==2){?> .-"-. .-" "-. /"-. .-| / "-.-" | / / | .-"-. / / | .-"-. .-" "-/ / | .-" "-. |-. .-"\ / | /"-. .-| | '-.-" \ / | /' "-.-" | | \ \/ .-"-. /' | | | \ \.-" "-. | | | \ |-. .-"\ | | | \ | "-.-" '\ | | | \ | | '\ | | | |\ \ | | '\ | | | | \ \ | | '\| | | | \ \ | | :\. | | | \ \| | | \. | | | \ | | \. | '-. | .-"\ | | '.\. .-' "-|-" \ | | "-\.-" \ | | \ | | "-. | .-' "-|-"<?php }else{?> o o / \ / \ / \ / ______________ |.------------.| || || || || || || || || ||____________||_ |OO ....... OO | `-. '------_.-._---' _.' _____|| ||___/_ / _.-|| N ||-._ \ .-._ / -'_.---------._'- \ ,'___i-i___ /_.-'_ NINTENDO _'-._\ ' /_+ o :::\ |`-i /m\/m\|\|/=,/m\i-'| | || \ O / || | |_\_/\_/___\_/'./| | | \/ \ / \/ `-' '-.`-' , V `---' <?php }}?> ``` Thanks to @KevinCruijssen for a byte! [Answer] # PHP, 881 Bytes ``` <?=json_decode(gzinflate(base64_decode("rVY9rxQxDPwr0Ta5E0lWQHcCJBAUNHcFiCoi217xeBIFDea/M3acr80eFXlPG6094x07TnK/l5fLZTH7QYbiz/hjsCUXvMVfcKn5kgzqqdmkEOdtiWiun69fP10/3ozCNx8E5RiSJg11bAKLK6Mg7Bh5+n7GM0aGksmoQVfBvTmb07tzzi/GrLjhTl/Oef6A+fRLYq4ScwtjIORYOO+F4yzpx5FYLoJYkZpws0kKUoBaGE4R8ylBVq5GKdEE5BQ3ju6sFOSf0JIWPQTuYrRvdFB9KdA91lS/LCbEOWtGV0fO/qm39lF2Q0iLW14d9aoJPi7aSrMjRz3041uwK3Lu96yZIRJmApScdC7+rGb213o1ub2+PTrDpwyoCo5LLlkrLR3mBKv1JQ5TGgGMuNo5y6y0LB721NrlpYwqcWinShmEm4eE1mlTXsf4QqBOMxKsYWaCMqg+OsIOTlrROOGVscebRtjjhTHhG6HhL6hWzxvwldDwEiU8wrc912vqCAK3XG46LrdoD8rAka99jXJT10U7Qu5hWfZ5I02LY478j9zaQtSLmRGsDSfE6+mEeK6U54LuzpijY0ds40EEUzWkYWQjBd+NoFnQ0A/0H629Aryp+XYzIQ9z41u2XLA4AGSkgIsJM66kgE3c5yMfkrhx1XC868GA5woPmG0lOY6AgPE2teRDsl5RziLY3d+1RgiL5UvdrwBAEQVYizDpBa/P5XLRG3zzd1if+OzBg/h/fevk5e4t8Q8U2X03lkBlC6ASEQnIg7/LM1p5JflFoyeZrGU+1pi2eWuGAVlic/n123HL8S3PlVz+/AU=")),1)[$argv[1]]; ``` Making of fill the lines with the graphics use the heredoc syntax in PHP ``` $a[1]=<<<A A; $a[2]=<<<B B; $a[3]=<<<C C; echo base64_encode(gzdeflate(json_encode($a))); ``` ]
[Question] [ Aside of nursing my child, [Vitsy](https://github.com/VTCAKAVSMoACE/Vitsy), and dabbling in the art of code golf, I also am an avid dubstep fan, listening to all the new dubstep that [Monstercat](https://www.youtube.com/user/MonstercatMedia) puts out as regularly as I can. I also share a random dubstep of the day, though not regularly, in [the Nineteenth Byte](http://chat.stackexchange.com/rooms/240/the-nineteenth-byte). This last bit is what this challenge relates to; so, without further ado, let me get to what you actually need to think about: # The Challenge You must generate a randomly sorted list of songs from [this playlist](https://www.youtube.com/playlist?list=PLF5C76212C58C464A) in the following format: ``` <Title> - <Artist>: <link to the video> ``` # Rules * The output list must update with the playlist provided, or every byte used counts as 2 (your score would be double your byte count). * The output list must have no repeats. * The output list must be given in the specified format. * The output list must have all of the videos listed in the playlist provided. * You may not use builtins for array shuffling (such as `Collections.shuffle(List<?> x)` from Java) * You may not use the YouTube builtin shuffle mechanism (as this is not random). * There are no limits on runtime. # Example Output ``` Division - Ephixa: https://www.youtube.com/watch?v=M1mPFWhgYUM&list=PLF5C76212C58C464A&index=95 Wanna Know You (ft. Holly Drummond) - Direct: https://www.youtube.com/watch?v=6QWQfzYMJTs&list=PLF5C76212C58C464A&index=24 Edge of the World (feat. Becko) - Razihel & Xilent: https://www.youtube.com/watch?v=P0dQ55ZgNkw&index=4&list=PLF5C76212C58C464A ... until the final video ... Way Too Deep - Grabbitz: https://www.youtube.com/watch?v=4T28WgVqdrA&index=8&list=PLF5C76212C58C464A ``` It may be worth perusing the [YouTube API](https://developers.google.com/youtube/v3/), but parsing the page with the playlist on it might save you some time. [Answer] # JavaScript, 532 536 538 582 bytes Thanks to @ӍѲꝆΛҐӍΛПҒЦꝆ and @Quill for a whole bunch of bytes. I did do a couple of things here which may not be 100% to the spec - If they aren't admissible please tell me and I'll fix them: 1. I shortened the YouTube URL 2. The shuffle is VERY weak, and is not considered in any way close to random. 3. There's a bit of whitespace due to the `join`. I'd like to start by saying, to any JavaScript developers out there: I'm so sorry. New version alternates captures to reduce on regex byte cost and strips some URL length, but sacrifices on alerts. Now instead of 3, you get like 20. Unfortunately the https on the URL's seem to be required or the page won't load, though that may be my setup :/. This could possibly be improved with proper XML parsing and loops instead of weird recursion things with calls to other functions. I had fun taking advantage of the fact that `XMLHttpRequest` causes synchronous execution. ``` d="https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLF5C76212C58C464A&key={REALLY SUPER LONG GOOGLE API KEY HERE}",h=[];o=l=>{x=new XMLHttpRequest,x.open("GET",l,!1),x.send(0),j=x.responseText;y=`nextPageToken": "`;e(j) j.includes(y)&&(q=j.split(y)[1].split('"')[0],o(d+"&pageToken="+q));h.sort(b=>.5-Math.random());alert(h.join ` `)} e=v=>{for(r=/(title": "(.*)\[)|(oId": "(.*)")/g;null!==(m=r.exec(v));)a=m[2]+": https://youtu.be/"+r.exec(v)[4],z="] - ",a.includes(z)&&(a=a.split(z)[1]),h.push(a)} o(d) ``` Replace the {REALLY SUPER LONG GOOGLE API KEY HERE} with your **39 character long** YouTube API key. Ungolfed: ``` //Define base URL, sacrificing speed and pages for bytes d = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLF5C76212C58C464A&key={REALLY SUPER LONG GOOGLE API KEY HERE}"; h = []; o = l => { //Grab API data x = new XMLHttpRequest(); x.open("GET", l, false); x.send(0); j = x.responseText; //Set up a split since we use it twice y = `nextPageToken": "`; //At this point, jump off to the other function to deal with the output e(j); //If there are multiple pages of results, as we only get a couple from each API call to save bytes with URL's if (j.includes(y)) { //Get the ID for the next page q = j.split(y)[1].split("\"")[0]; //Call again with an added parameter o(d + "&pageToken=" + q) } //Taking advantage of XMLHttpRequest forcing this as synchronous, so all the above happens first //Bad shuffle h.sort(b => .5 - Math.random()) alert(h.join ` `); } e = v => { //Regex for titles/ID's - Grabbitz doesn't fit the "[Genre] - Song - Artist" mould so we need a slightly longer regex r = /(title": "(.*)\[)|(oId": "(.*)")/g; //Since we know there's one title to one video, we can run them both at the same time while ((m = r.exec(v)) !== null) { //Build the string a = m[2] + ": https://youtu.be/" + r.exec(v)[4]; z = "] - "; //That Grabbitz edge case ruining my day again, I'm glad it's a good track... if (a.includes(z)) { a = a.split(z)[1]; } h.push(a); } } o(d) ``` [Answer] # Julia, 590 bytes ``` using Requests L="PLF5C76212C58C464A" u="https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=$L&key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" R(x)=JSON.parse(readall(x)) F(x)=(s=x["snippet"];(s["title"],s["resourceId"]["videoId"],s["position"])) g=get(u) v=[F(i)for i=R(g)["items"]] t="nextPageToken" while haskey(R(g),t) g=get("$u&pageToken="*R(g)[t]) v=[v;[F(i)for i=R(g)["items"]]] end for j=randperm(109) t,d,i=v[j] t=replace(t[13:end],r"\[Mo[\w ]+\]$","") println(join(reverse(split(t," - ")),"- "),": https://www.youtube.com/watch?v=$d&list=$L&index=$(i+1)")end ``` This is a full program that uses Julia's `Requests` module to connect to the YouTube API, get the results, and print them to STDOUT. It will not likely win unless no one else participates. The X'd out portion is my Google Developer API key, which unfortunately is 39 characters. Ungolfed: ``` using Requests # Store the playlist ID L = "PLF5C76212C58C464A" # Store the initial API URL u = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=$L&key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" # Create a function for parsing JSON responses R(x) = JSON.parse(readall(x)) # Create a function for constructing a tuple containing video information F(x) = (s = x["snippet"]; (s["title"], s["resourceId"]["videoId"], s["position"])) # Perform the initial API request g = get(u) # Collect all relevant returned information in an array v = [F(i) for i = R(g)["items"]] # Perform pagination to get all 109 items t = "nextPageToken" while haskey(R(g), t) g = get("$u&pageToken=" * R(g)[t]) v = [v; [F(i) for i = R(g)["items"]]] end # Select the elements at random indices for j = randperm(109) # Get the title, ID, and playlist index t, d, i = v[j] # Parse out the actual title t = replace(t[13:end], r"\[Mo[\w ]+\]$", "") # Print the current item println(join(reverse(split(t, " - ")), "- "), ": https://www.youtube.com/watch?v=$d&list=$L&index=$(i+1)") end ``` [Answer] # PHP, 594 bytes Here's my submission using PHP. ``` <?php $t=[];$n='';while(1){$l='https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLF5C76212C58C464A&pageToken='.$n.'&key={InsertKeyToContinueOnYourAdventure!!!}';$c=json_decode(file_get_contents($l),true);$t=array_merge($c['items'],$t);if(empty($c['nextPageToken']))break;else $n=$c['nextPageToken'];}$o=[];while(count($t)){$k=rand(0,count($t)-1);$s=$t[$k]['snippet'];echo preg_replace('/(?:\[.+\] - )?(.+) - (.+)/','${2} - ${1}',$s['title']).': https://www.youtube.com/watch?v='.$s['resourceId']['videoId'].'&list='.$s['playlistId'].'<br/>';array_splice($t,$k,1);}?> ``` It's probably not the best - or shortest - solution out there but it does the job. Before I go on, though, here's the ungolfed version: ``` <?php $t = []; $n = ''; while (1) { $l = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLF5C76212C58C464A&pageToken=' . $n .'&key={InsertKeyToContinueOnYourAdventure!!!}'; $c = json_decode(file_get_contents($l), true); $t = array_merge($c['items'], $t); if (empty($c['nextPageToken'])) break; else $n = $c['nextPageToken']; } $o = []; while (count($t)) { $k = rand(0, count($t) - 1); $s = $t[$k]['snippet']; echo preg_replace('/(?:\[.+\] - )?(.+) - (.+)/', '${2} - ${1}', $s['title']) . ': https://www.youtube.com/watch?v=' . $s['resourceId']['videoId'] . '&list=' . $s['playlistId'] . '<br/>'; array_splice($t, $k, 1); } ?> ``` I really feel like the regular expression can be improved - both in size and quality. Also, I couldn't think of a better way to break the first while other than that ugly if-else statement. Maybe the while statement could be handled better. I don't know. It's 1:15 am here and I'm half asleep. Looking at the other answers, it seems that PHP probably isn't ideal for this due to its long function names. Still, file\_get\_contents() was pretty helpful and cut down a lot of request handling. I opted to use that instead of file() since it made decoding the request easier. I also did find a way to reduce some code around around that if-else statement, but the result would throw one notice when there was no 'nextPageToken' given on the last HTTP request. I suppose if you wanted to turn error reporting off then it could be possible, but I felt like that would be cheating. For those who are curious, the ungolfed if-else would look like this: ``` if ($d = $c['nextPageToken'])) break; else $n = $d; ``` Edit: I just realised that if this were to be run from a console I could reduce the size by 11 bytes (removing php tags + replacing br/ tag with \n). Oh well, at least's more readable on a browser IMHO. I'll just leave it for now. > > First code golf! Woooo! Now I must sleep. Good night, y'all! > > > ]
[Question] [ **This question already has answers here**: [Can you Meta Quine?](/questions/5510/can-you-meta-quine) (6 answers) Closed 7 years ago. Write a program or function which, when run, outputs another program or function which is valid in the same language as the original program, and which itself will output another program or function that has the same properties. You must at one point end up back to your initial program or function. ## Example Suppose you write program `A`. When run, it outputs program `B`. When you run `B`, it outputs program `C`. When you run `C`, it outputs program `A`, thus completing the circle. `A`, `B` and `C` are all valid in the same language and are all different by at least one character. ## Scoring Your score is calculated as `<Number of bytes of the initial program>/<number of iterations to get back to the initial program>` For instance, with the programs `A`, `B` and `C` in the previous example, the number of iterations is `3` (you have to run 3 times to get back to `A`) and the number of bytes is the number of bytes of `A`. This incentivize both golfing your initial code, and having an initial program that leads to a longer chain. **The smallest score wins** [Answer] # CJam, score → 0 ``` {)1e9%"X$~"}0X$~ ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%7B)1e9%25%22X%24~%22%7D0X%24~). The actual score of this program is obviously positive, but `1e9` can be replaced with `1e99`, `1e999`, `1e9999`, `1e99999`, etc. The numerator of the score grows *much* slower than the denominator. ### How it works ``` { } e# Define a block: ) e# Increment the integer on the stack. 1e9% e# Take the incremented integer modulo 1,000,000,000. "X$~" e# Push that string. 0 e# Push 0. X$~ e# Copy the block and execute the copy. e# The stack now holds the block, the modified integer and e# the string "X$~", all of which CJam prints before exiting. ``` Executing the code prints `{)1e9%"X$~"}1X$~` which, when executed, prints `{)1e9%"X$~"}2X$~`, etc. After reaching `{)1e9%"X$~"}999999999X$~`, one more execution yields the original code. [Answer] # Javascript ES6, `68/1.8e16` (basically 0) ``` $=_=>`$=${$};$(0)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(0) ``` Based on my Bling Quine framework: ``` $=_=>`$=${$};$()` ``` Here's the output sequence starting from `$(0)`: ``` $=_=>`$=${$};$(1)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(0) $=_=>`$=${$};$(1)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(1) $=_=>`$=${$};$(2)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(1) $=_=>`$=${$};$(2)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(2) $=_=>`$=${$};$(3)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(2) $=_=>`$=${$};$(3)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(3) $=_=>`$=${$};$(4)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(3) ... $=_=>`$=${$};$(8999999999999999)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(8999999999999999) $=_=>`$=${$};$(0)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(8999999999999999) $=_=>`$=${$};$(0)`.replace(eval(`/(${_})\\)/`),x=>++_%9e15+`)`);$(0) ``` [Answer] # [Underload](https://esolangs.org/wiki/Underload), score of 0 in the limit ``` (a(:^)*(a(S)*):*:*:*:*^S):^ ``` Adding another `:*` to the sequence of `:*` will add two bytes to the program, and double the period of the quine. Thus, the score can be made arbitrarily small by adding more copies. [Try it online!](https://tio.run/nexus/underload#@6@RqGEVp6kFpII1tTSttCAwLljTKu7/fwA "Underload – TIO Nexus") This basically uses the Underload universal quine constructor `(a(:^)**f*S):^`, which is capable of producing a program whose output is any function *f* of the original source code. In this case, the function in question produces a string that outputs its argument in the most naive way (by escaping it and adding a print statement; escape is `a`, add a print statement is `(S)*`); and we run the function in a loop (via `^`) a power of 2 times. (2 to the power of *n* can be written in Underload by using *n* repeats of `:*`.) The result is output like ``` (((((((((((((((((a(:^)*(a(S)*):*:*:*:*^S):^)S)S)S)S)S)S)S)S)S)S)S)S)S)S)S)S ``` which produces, when run, ``` ((((((((((((((((a(:^)*(a(S)*):*:*:*:*^S):^)S)S)S)S)S)S)S)S)S)S)S)S)S)S)S ``` and so on until the original program is reached. ]
[Question] [ ## NOTE: This question was migrated from <https://stackoverflow.com/q/27134588/1442685> PHP QUESTION Almost purely out of curiousity, how can I take an array like this: ``` array( 'fruit' => 'banana', 'drink' => 'milk') ``` And convert it to an array like this: ``` array( 'fruit=banana', 'drink=milk') ``` **Requirements** * Cannot use anonymous functions * If needed, can only use `array_*` functions that accept callable if that callable is native to PHP * Must be a one-liner solution --- This is not for a class. I'm curious to see how clever one can be with array functions. Given the requirements, is it possible? [Answer] ``` explode('&',http_build_query($a)) ``` 33 bytes [Answer] # PHP (33 bytes) I am not 100% sure if this is valid. I used 0 (**zero**) functions. This solution is 1 byte shorter than @Devon's solution. The code: ``` foreach($a as$k=>$v)$z[]="$k=$v"; ``` The var `$a` is the array, the var `$z` will have the new array. There are no restrictions to the vars or how it should be implemented. [Answer] # 32 bytes ``` foreach($a as$k=>&$v)$v="$k=$v"; ``` Update by reference, shaves off 1 byte. Not sure how important removing the original key is, sort of a grey area. This is what I mean: ``` [ ['fruit'] => 'fruit=banana', ['drink'] => 'drink=milk' ] ``` But it saves on variables, as your not creating a new array ]
[Question] [ **Forward:** Depending on what language you use and what user you are logged in as this challenge could be dangerous so proceed with Caution! You could delete something, fork bomb yourself, or worse... **Challange:** Write a program of n bytes which creates n copies of itself on disk, modifies the first byte of the first copy to an 8-bit value of your choosing, modifies the second byte of the second copy to an a bit-value of your choosing, ... , modifies the nth byte of the nth copy of the program to an 8-bit value of your choosing, and then executes all n of the modified copies synchronously starting with the first and ending with the last, the program should print "alive", then program should then exit. **Scoring: Lowest Score Wins** Score = (-1 \* (Number of times "alive" is printed)) + number of bytes in your program **RULES** 1. Infinite loops in the program or one of its creations will disqualify an answer. 2. Number of times alive is printed has to be less than 1024. **Why this interests me:** I think a lot about the relationships between biology and analogies between living things and computer programs. One of the qualities of living things is that they know how to reproduce. One of the factors of replication that make evolution possible is that the replication is not perfect. If one were to design artificial life it should have a very compact method of reproducing itself. This is why I am turning to the code golf community to see what sort of strange ideas are out there. Sorry for all the edits to this question. [Answer] ## Perl, 167 - 973 = -806 ~~142 - 55 = 87~~ Here's an entry in the proper spirit of this code challenge: ``` if($ARGV[0]=~s/r/X/){open F,$0;for(@x=split//,join"",<F>){ $c=$_++;open F,">$0~".++$x;print F@x;$_=$c}sleep 1; fork||exit exec"perl $0~$_ @ARGV"for 1..@x}print"alive\n" ``` I forkbombed myself a few times in the process of writing this script. As a result, this version comes with a couple of safety features. First off is the `sleep 1` just before the spawning loop. That leaves enough idle processing time to allow one to type `killall perl`, if and when such measures become necessary. The second safety feature is that the spawn loop is disabled by default. To run in full power, you need to supply the word `reproduce` as an argument on the command line. (Seriously, it's embarrassing to acknowledge the number of times I've had to do a hard reboot today because of some bug in my script, before I finally got the balance right.) The program ends up producing several thousand imperfect copies of itself, from which about one in eight succeeds in printing `alive`. Most of the copies have syntax errors and so don't get run. A handful of scripts run but produce invalid output. Here's a sample test run. (Note that, due to the `sleep`, it takes several seconds before the spawning finally grinds to a halt and all the scripts stop running.) ``` $ mkdir run $ cp changer run/ $ cd run $ ls -l total 4 -rw-r--r-- 1 breadbox breadbox 167 2013-07-19 21:35 changer $ perl changer alive $ perl changer reproduce 2> /dev/null >> out $ ls -l out -rw-r--r-- 1 breadbox breadbox 2608 2013-07-19 21:35 out $ ls -l out -rw-r--r-- 1 breadbox breadbox 6404 2013-07-19 21:35 out $ ls -l out -rw-r--r-- 1 breadbox breadbox 9370 2013-07-19 21:35 out $ ls -l out -rw-r--r-- 1 breadbox breadbox 9370 2013-07-19 21:35 out $ ls -l | wc -l 7691 $ grep -c alive out 973 $ cd .. $ rm -r run/ $ ``` Finally, I should note that the script has a bit of nondeterminism -- a common enough circumstance when starting up lots of child processes. As a result, the number of `alive`s that get output varies a bit with each run. The highest count I've seen so far is 984, so I believe that it's not in any danger of exceeding the 1024 limit. [Answer] Here is my submission: It's a program of o Bytes. It created 0 copies of itself and modified all 0 bytes. It prints out Alive 0 times for a total socre of -1\*0+0=0 Feel free to smack me for this submission :) ]
[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/25/edit) Let's suppose there is a finite unknown number `n` (`n` can be very large, does not necessarily fit 64-bits; think of `BigInteger` in Java or `long` in Python) and a function `cmp(x)` that returns `true` if `x <= n`. Write a program to determine `n` in minimum number of calls to `cmp`. [Answer] Double our guess until we exceed `n`, then do binary search. This is a reasonable approach until `n` could be very large, at which point you probably want to do more than doubling at each step. ``` b=1; while (cmp(b)) b *= 2; a = b/2; while (a < b-1) { // invariant: a <= n < b m = (a+b)/2; if (cmp(m)) { a = m; } else { b = m; } } return a; ``` [Answer] # Clojure - 161 chars Solution using BigInteger arithmetic and successive squaring / square roots to home in on answer. I believe this usually results in less comparisons than binary search for large values of n - typically close to the number of bits in the binary representation of the answer, which is the theoretical optimum if you only have a binary comparison available. ``` (use'clojure.contrib.math)(defn find[](loop[l 0 h nil](let[t(+(if h((exact-integer-sqrt(* l h))0)(* l l))1)](if(= l h)l(if(cmp t)(recur t h)(recur l(dec t))))))) ``` Expanded for readability: ``` (use 'clojure.contrib.math) (defn find[] (loop [l 0 h nil] (let [t (+ (if h ((exact-integer-sqrt(* l h)) 0) (* l l)) 1)] (if (= l h) l (if (cmp t) (recur t h) (recur l (dec t))))))) ``` Note that the conciseness of the solution is considerably helped by the fact that Clojure automatically uses BigIntegers once values go outside the 64-bit long range. In action: ``` ; counter for compares (def counter (atom 0)) ; value to find (def n 100000000000000000000000000000000000000000000000000000000) ; compare function (defn cmp [x] (do (swap! counter inc) (<= x n))) ;let's find it! (find) => 100000000000000000000000000000000000000000000000000000000 ; how many calls to cmp? @counter => 203 ; how close to theoretical optimum? (.bitLength 100000000000000000000000000000000000000000000000000000000) => 187 ``` [Answer] Here's my solution in C, based on “binary search”: ``` #include <stdio.h> int cmp(long x) { return (x <= 727695360); } int main(void) { char *p = (char*)cmp; for (;;) { long x = *(long*)p++; if (cmp(x) && !cmp(x+1)) { printf("%ld\n", x); break; } } return 0; } ``` Granted, there are a number of things that could go wrong, including: * `cmp` might compute its secret indirectly rather than using it as a literal. * The compiler might tweak the literal to generate faster or smaller code. For example, `x <= 727695360` could become `x < 727695361`. * The literal may be broken in half due to the target having a fixed-width instruction set. I do not expect this code to work on PowerPC. * The target CPU might not like those unaligned `long` reads. This code will cause an address error on a 68000 CPU. [Answer] Assuming a uniform probability distribution: 1. Assign x to the maximum value n could be, y to the minimum value 2. Guess n=ceiling((x+y)/2) 3. If cmp returns true, y = the guess; else x = the guess - 1 4. If x=y, done (n=x=y); else goto (2) [Answer] Simple non-golf binary search: ``` num = 110134848298567717 # sample number guess = 1 inc = 1 halved = 0 calls_to_cmp = 0 def my_cmp(x, n): global calls_to_cmp calls_to_cmp += 1 return x <= n while True: small = my_cmp(guess, num) if small: # add to guess, increase search field inc *= 2 guess += inc else: # subtract from guess, decrease search field inc /= 2 guess -= inc print "Guess: ", guess, ", inc: ", inc, " calls so far: ", calls_to_cmp if inc == 0: break print "Done." ``` One thing to consider is to initially try tripling or quadrupling for the first few loops: this will determine if the number is "small" (say under 1 million) or "large" and may speed the search up. [Answer] Just to be a cheeky bugger: # JavaScript, 34 chars calls to `cmp`, *technically* 0 ``` c=cmp i=0 while(c(++i)); alert(i-1) ``` **NOTE**: JavaScript isn't a reasonable language to perform this in as it is restricted to 64-bit numeric values, so a string library would be necessary for managing larger numbers. [Answer] A solution in pseudocode (assuming x is nowhere near 0): ``` x=0 #Step 1: get upper and lower bounds on the number of digits #double the number of digits until we go past the number while cmp(2**(2**x)): x++ mindgt=2**(x-1) maxdgt=2**x #Step 2: find bounds on log(number) while(maxdgt-mindgt!=1): n=(mindgt+maxdgt)/2 if cmp(2**n): mindgt=n else: maxdgt=n min=2**mindgt max=2**maxdgt #Step 3: straightforward binary search while(max!=min): n=(max+min)/2 if(cmp(n)): mindgt=n else: maxdgt=n-1 print max ``` For a value on the order of 1e40, this method takes 9 calls on step #1, 7 calls on step #2 and about 133 calls in step #3 for a total of 149. ]
[Question] [ Your task is to solve a new puzzle called Cubax. This toy is actually a Chinese puzzle whose expected “final” state is a simple cube. During the festivities, Cubax unfolded, because it cannot move when folded. Cubax is composed of `N³` smaller cubes (elements) linked together in a kind of doubly linked chain. The chain has two ends, it doesn't loop. 3 successive elements of Cubax are either: * always aligned * always at a right angle (90°) Thus a simple way of defining Cubax's structure is to provide the successive number of aligned blocks, starting from the first element. For example, representing `S` as the starting elements, `E` as the ending element and `X` as other elements, the structure defined as `332` could take any of the following 2D shapes: ``` XE EX X X SXX SXX SXX SXX X X EX XE ``` Another example: `434` could be represented as: ``` S E X X X X XXX ``` Note: Counting the successive the number of aligned elements implies that elements in an angle are counted twice. In the last example `434`, there are actually only `4+3-1+4-1=9` elements. To provide the output solution, use the following rules. For each series of aligned blocks, one character representing the direction where it has to point to is written: * `U` Direction Up (increasing y) * `D` Direction Down (decreasing y) * `R` Direction Right (increasing x) * `L` Direction Left (decreasing x) * `F` Direction Front (increasing z) * `B` Direction Back (decreasing z) Considering a 3D representation (x,y,z), we will only be interested in the solutions where the first element is located at `(1,1,1)` and where the last element is located at `(N,N,N)` Note: As a consequence, there will be no valid solution starting by `D`, `L` or `B`. ## Example For the input `3332`, the output `RDRD` corresponds to the following planar shape: ``` SXX X XXX E ``` For the same input `3332`, the output `RDLU` corresponds to: ``` SXX E X XXX ``` ## Input & Output Your program has to read the initial shape of Cubax and provide the moves to apply so as to pack it back to a full cube of side length `N`. You are given an integer `N`, the side length of the cube, and a string that contains a string of Blocks -> each character providing the successive number of aligned blocks You are to output the alphabetically-sorted list of all solutions, one solution per line # Test cases: ``` # 2*2*2 cube 2 2222222 -> FRBULFR FUBRDFU RFLUBRF RULFDRU UFDRBUF URDFLUR # 3*3*3 cube 3 232333232223222233 -> FRFLUBRFDRBLBRDRUF FUFDRBUFLUBDBULURF RFRBULFRDFLBLFDFUR RURDFLURBULDLUBUFR UFUBRDFULFDBDFLFRU URULFDRUBRDLDRBRFU # 4*4*4 cube 4 3232242323232222222233222223422242322222222242 -> FRBULFDRBUBDBRFUFDFULBUBRDRULDFURDFLULDBLFUBRF FUBRDFLUBRBLBUFRFLFRDBRBULURDLFRULFDRDLBDFRBUF RFLUBRDFLULDLFRURDRUBLULFDFUBDRUFDRBUBDLBRULFR RULFDRBULFLBLURFRBRFDLFLUBUFDBRFUBRDFDBLDRFLUR UFDRBULFDRDLDFURULURBDRDFLFRBLURFLUBRBLDBURDFU URDFLUBRDFDBDRUFUBUFLDFDRBRFLBUFRBULFLBDLUFDRU ``` ## Others: * You are allowed to output the moves in a string or list/array * You are allowed to input the aligned blocks numbers via list/array as well * You may assume there will always be at least 1 solution to the puzzle * You are allowed to take in the input as 2 lines or on the same line as a list/array/string representation Credits to the codingame community for the [puzzle](https://www.codingame.com/ide/puzzle/cubax-folding)! ## Scoring This is code-golf, so shortest code wins! [Answer] # [Python](https://www.python.org), ~~269~~ ~~240~~ 232 bytes ``` from itertools import* P=product def f(n,q): for w in P(*['BDFLRU']*len(q)):x=y=z=0;{*P(*[range(n)]*3)}-{(x:=x-E%9*E%4+1,y:=y-E*~E%7%4+1,z:=z+E%-83%E%4-1)for d,p in zip(w,q)for E in[ord(d)%13]*~-p}=={(0,)*3}!=n-1==x==y==z!=print(w) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVA7TgMxFOz3FE5hxXZsKcsiERa9BmEqigiJarUFYtdgKbEd42h_2lyEJg1cgpNwA46Bl0-D9F7xZkaamffy5rrwZM3x-LoPSqw-PpW3W6RD7YO1m2ekt876wJI1OG-r_UNIqlohRQzf0TxBynrUIG3QmrBifnl1fXN7Ny_ZpjZkR2neQgc9LC8GNvH-3jzWxNCSZXQUA2lzaIXE50zi00XKuxw6IdlB4rPvu8-hX0gsVhmOApHSyazibrLrtSNNjDBBMgKF9RWpKE6zkh2EGwEGsuSUZeMMjEgBWohRoJ_FGtoE0tCfvu-KnHBUxP0_5a_i7zNf) This is too slow for the side length 3 cube. --- # [Python](https://www.python.org), 382 bytes Slighly optimized for speed, but still too slow to run the last case in a minute. ``` D=dict(zip('BDFLRU',zip((0,0,0,-1,1,0),(0,-1,0,0,0,1),(-1,0,1,0,0,0)))) def f(n,q): S=[('',a:=(0,)*3,{a})] for i in q: N=[] for p,w,c in S: for d,(X,Y,Z) in D.items(): nc=c|c;x,y,z=w for _ in' '*~-i: x+=X;y+=Y;z+=Z;nc|={a:=(x,y,z)} if n<=max(a)or x|y|z<0 or a in c:break else:N+=(p+d,(x,y,z),nc), S=N return[p for p,(x,y,z),_ in S if x==y==z==n-1] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=ZVLLboJAFE23fMXsmJFLA7JpwLtpTFeNi5omKjGGIqST1hERIyD6Dd1346b9p_ZrOjNo08c8knvPPec-MvP6nlXF41Icj2-bIrWvPi8OfZzzuKA1z6h53b-5vbs3QTnUAbVtF1xwGFBttpgrXe2cACaXMU9SklIBK-YbZIghNU2IfJQ61vFgF-3Z1CDpMieccEFWkkQGGEpMgxlsIVaBoQpoaA50BGOYMAX3L3mRLNaU6TARMcZNHJRQQY1bDSnJTFJNYnYONm95pLRwFFQWjoPawkkg4gZ3qiutZPuWxFMieriIShoxmaVsqqbuOUSakaod-w95Ej1pbvK8TvyBhTSzZH9tFhAxAxUd4sAgeVJschFmp7HOnJkeTpUqESvEGlHY7rR9ho8XRS4VJaVdIKG8f89Uj57lXBS0ZEZrmLbZ6TrM-CH3WrmnVd75fCPdf_aJ9jt_29f5m3wB) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 75 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` "BDFLRU"¹gãʒ3Å0Uݨ3ãsÇ13%¹<øε`иε9%y*yy±*7%y83(%y%)4%<`()Xs-DU}}€`KJJ_X>²ªË* ``` Port of [*@ovs*' (first) Python answer](https://codegolf.stackexchange.com/a/242601/52210), so make sure to upvote him as well! No TIO, since it even times out for the 2x2x2 test case. To verify it works as intended, here two separated TIOs, so both parts of the program can be verified independently: * `"BDFLRU"¹gã`: Generate all possible move-sets that we're going to filter - [try it online](https://tio.run/##yy9OTMpM/f9fycnFzScoVOnQzvTDi///jzbWMdIBYSMdEygLIYIMjVHEjMGqkXWhQ6B4LJcJAA). * `3Å0U²Ý¨3ã³Ç13%¹<øε`иε9%y*yy±*7%y83(%y%)4%<`()Xs-DU}}€`KJJ_X>²ªË*`: Verify a move-set (which we take as additional third input here) - [try it online](https://tio.run/##yy9OTMpM/f/f@HCrQeihTYfnHlphfHjxoc2H2w2NVQ/ttDm849zWhAtAwlK1Uquy8tBGLXPVSgtjDdVKVU0TVZsEDc2IYl2X0NraR01rEry9vOIj7A5tOrTqcLfW///RxjpGOiBspGMCZSFEkKExipgxWDWyLnQIFI/lMuEKCvVxcwlyApI@Tj6hQW5BTkFuLkBOqFOomwuQHeoU5AJk@LgEAcWC/uvq5uXr5iRWVQIA). **Explanation:** ``` "BDFLRU" # Push string "BDFLRU" ¹g # Push the length of the first input-list ã # Cartesian product to create all possible move-sets ʒ # Filter this list of strings by: 3Å0 # Push [0,0,0] U # Pop and store it in variable `X` ²Ý¨ # Push a list in the range [0, second input-integer) 3ã # Create all possible triplets of this ranged list s # Swap so the string is at the top again Ç # Convert it to a list of codepoint-integers 13% # Modulo-13 each ¹ # Push the first input-list again < # Decrease each of its values by 1 ø # Create pairs at the same positions of these two lists ε # Map over each pair [y,z]: `и # Pop the pair, and create a list of `z` amount of `y`s ε # Map over each integer `a` in this list: 9%y* # Push y%9*y yy±*7% # Push y*~y%7 (where `~` is the bitwise-NOT) y83(%y% # Push y%-83%y ) # Wrap all three into a list 4%< # Modulo-4 and then decrement each `() # Negate the last item of the triplet: Xs- # Subtract them from triplet `X` at the same positions # [a,b,c] → [a-(y%9*y%4-1),b-(y*~y%7%4-1),c+(y%-83%y%4-1)] DU # Store it as new triplet `X` (without popping) } # Close the inner map } # Close the outer map €` # Flatten it one level down to a list of triplets K # Remove all those from the earlier list of triplets JJ_ # Check if only [0,0,0] is left as item X # Push the final triplet `X` > # Increase each of its values by 1 ²ª # Append the second input-integer Ë # Check if all four values are the same * # Check if both checks are truthy # (after which the filtered list of strings is output implicitly) ``` [Answer] # Python3, ~~2040~~ 1759 bytes ``` B=input();R=range;X=str.maketrans;j=None;e=sum(int(i)-1for i in B)+1;s=round(e**(1/3));l=(s**3)-1 def q(x,y,z):return x+y*s+z*s*s class P: def __init__(s,x=0,y=0,z=0):s.x,s.y,s.z=x,y,z def q(s):return q(s.x,s.y,s.z) def u(s,v):return P(s.x+v.x,s.y+v.y,s.z+v.z) def v(f):return f.x>-1+f.y>-1+f.z>-1+f.x<s+f.y<s+f.z<s def I(s): r=[] for d in P(z=1),P(z=-1),P(y=1),P(y=-1),P(x=1),P(x=-1): n=s.u(d) if n.v():r+=n, return r n=[0]*e;K=[{}for _ in R(e)] def I(t):return s>t>-1 for x in R(s): for y in R(s): for z in R(s): p=P(x,y,z);k=p.q();n[k]=len(p.I()) if I(x-1):K[P(x-1,y,z).q()]["R"]=k if I(x+1):K[P(x+1,y,z).q()]["L"]=k if I(y-1):K[P(x,y-1,z).q()]["U"]=k if I(y+1):K[P(x,y+1,z).q()]["D"]=k if I(z-1):K[P(x,y,z-1).q()]["F"]=k if I(z+1):K[P(x,y,z+1).q()]["B"]=k class A: def __init__(s,f=j): if f:s.E=f.E[:];s.b=f.b;s.N=f.N[:];s.y=f.y;s.g=f.g;s.f=f.f;s.G=f.G else:s.E=[0]*e;s.b=e;s.N=n[:];s.G=j;s.y=0;s.e();s.g=0;s.f="" def w(s):return A(f=s) def t(s,h): for c in h: s.f+=c;a=[int(c)-1for c in B][s.g];s.g+=1 for _ in R(a): try:s.y=K[s.y][c];s.e() except:return return 1 def l(s):return s.b<1 def e(s): k=s.y if s.E[k]:g s.E[k]=1 if s.G==k:s.G=j elif s.G!=j:g s.N[k]=0;s.b-=1;h=K[k] for d in h: k=h[d] if not s.E[k]: n=s.N[k] if k!=l+n<3: if s.G!=j:g s.G=k;s.N[k]=n-1 if s.b>=1and s.E[l]:g def p(_,z,N): N+=1 for C in{"L":"BDFU","R":"BDFU","U":"BFLR","D":"BFLR","F":"DLRU","B":"DLRU"}[_]: c=z.w() if c.t(C): if c.l():m.append(c.f) else:p(C,c,N) *m,N=0,;S=A() S.t("FU") p("U",S,N);T="FBLRUD" for s in m[:]:m+=s.translate(X(T,"FBDURL")), for s in m[:]:m+=s.translate(X(T,"UDLRFB")),;m+=s.translate(X(T,"RLBFUD")), print("\n".join(sorted(m))) ``` [Try it online!](https://tio.run/##jZVdb@I6EIbv8yuyuXJIyIFyRzqVmrKgqhVCdJFWyokQDQ4fAZPGoZtktb@9Z8YOXzrn4lyEGduPx6/HY5NVxfogel9fAWxEdiyY7U8hX4gV93@CLHJvv0h5gR3S38L4ILjPQR73bCMKtrHb3eSQmxtzI8zAdrq@hPxwFEvGWy3W/atn2/4OmGy1ekgaS56YH6x0K7e2@zkvjrkwS6dqSaduyZY04t1CSnPSN0wi5/ON2BTzOZNuCR23wq@Gjt2XXulKr8KvBhVL4x9MnoOif4FsPX7EOJ9nYkKE86kptIpEe6I/WXJmE698aHedxKu0qbUp7yX1qd/6Xup5z6TCMM0cwggNJWdJyZmwGrq2S6atbAWN0c0SGoNNmm8KkN6RLW3yN4kpvE@GghwQLkXXwnJDQNiJWtx/gfD3H1psTotNGbcjQ8spztuQDwUKN4gqNaWkUru6aquO@rrDzGDSnJqfQuZ9YImIMI1gxwXLvGdmn1Q@s5L0v4QTctQMoqPQmloRpBfKOVHODfV6Q1XnWC66F2p2SzkXyrmiBjdUfRXLpUZDDW8p55pyzlSgKF2ej/8uzwS2KlEYI8Hy/A6J9z3sR7703tF9RztGO9ZdFboV2hXaFdoEbYJ2hHaEQfhOchVEnyzF4CqC0PNHsFVROvjL8SQoUkfFsSyt7NfVTXhkCcimpguUuj4fcUxHvFbni5MdiP0FhHSp4@ZSKyCIQlyA1l050CX4qsoWujzMIq/6JOkF2SoK40hLU2O8jHlWNHKopxHW1Zp2V1pxq/dNN29KL8VbUOnMYkqw5vorw2xcJUcNjADSvsqMyp/u@wbbBh4TTCl6b0PXX6PM9OZu6iSksA6X0em6HYrTgmoXdBvHepoaT7/BzhH3PT1q3q6oMjqC1G@WFu2ucYLeH6C7EEsVfEe7od1mbO7W7ph2PFZZJmlPKO033oi@FQyGM8vFK3R2Z@QOX6foDi7uEN3B65SA4OT@CedqCzHU3i91JCgj9gr2pM9OtXb4tOy9RZZxfLljL1Enp@owY09ujMqM1t4d4wPsv8EjRnnDABYqsY2MoRj3DRH/B1jDANccWOqNkZTaPdZsf@9g9tQ/yG5RcPaT/UCtwWA2fbVs2/0f8Ay3MgwI9v9rePoaDHFVipXlVMHW38LytoeNYPKQF3zJ9rZtf33d9e56Pfzu7tSHjX8A) -18 thx to @Unrelatedstring -65 thx to @TheFifthMarshal -1 thx to @AidenChow ]
[Question] [ This challenge is one of the two challenges which were planned for [Advent of Code Golf 2021](https://codegolf.meta.stackexchange.com/q/24068/78410), but didn't fit into the 25-day schedule. Related to [AoC2020 Day 22](https://adventofcode.com/2020/day/22), Part 2. --- Combat is a simple two-player card game played with a deck of cards. A unique positive integer is written on each card. The game proceeds as follows: * Shuffle and split the cards so that each player has their own deck. * For each round... + Both players draw their top card. The one with the higher-numbered card wins the round. The winner places both cards at the bottom of their own deck, so that the winner's card is above the other card. * If a player owns all cards, the player wins. **Recursive Combat** is a variant of Combat. The only difference is how to decide the winner of each round. * Before either player deals a card, if there was a previous round in this game that had exactly the same cards in the same order in the same players' decks, the game instantly ends in a win for player 1. Previous rounds from other games are not considered. (This prevents infinite games of Recursive Combat.) * Otherwise, this round's cards must be in a new configuration; the players begin the round by each drawing the top card of their deck as normal. If both players have at least as many cards remaining in their deck as the value of the card they just drew, the winner of the round is determined by playing a **new game of Recursive Combat**, where each player takes that many cards from the top of their own deck (excluding the cards drawn) to the "sub-game". When the sub-game ends, the cards are returned to the decks as they were before the sub-game, and the parent game proceeds like Combat: the winner of the sub-game (= the winner of the round) puts the two cards drawn at the bottom of their own deck, so that the winner's card is above the other card. * Otherwise, at least one player must not have enough cards left in their deck to recurse; the winner of the round is the player with the higher-value card. Note that the winner's card might have lower value than the other card in this version. Let's call the two players Player 1 and Player 2. Given both player's decks at start, determine whether Player 1 will win the game of Recursive Combat or not. Both decks are given as list of values written on each card. You can choose which side will be the top of the deck. It is guaranteed that both decks are non-empty and all numbers are unique positive integers. For output, you can choose to * output truthy/falsy using your language's convention (swapping is allowed), or * use two distinct, fixed values to represent true (affirmative) or false (negative) respectively. Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. The shortest code in bytes wins. ## Test cases **P1 wins** ``` P1's deck, P2's deck (first number at the top) [43, 19], [2, 29, 14] (by infinite loop prevention) [10, 8, 2] [4, 3, 5, 6, 9, 1, 7] [2, 1, 10, 8] [7, 6, 5, 3, 9, 4] [2, 1, 7, 8, 9, 4, 5, 6] [10, 3] ``` **P2 wins** ``` P1's deck, P2's deck (first number at the top) [9, 2, 6, 3, 1], [5, 8, 4, 7, 10] [6, 2, 1, 8, 9, 4], [7, 3, 10, 5] [4, 6, 2, 1, 3], [8, 10, 7, 9, 5] [7, 4, 9, 2, 6, 1, 3], [10, 8, 5] ``` [Answer] # JavaScript, ~~146~~ ~~145~~ 134 bytes ``` c=d=>(d[[[A,B]=d,B]]^=Y=B[0])?(X=A[0])?d[w=A[X]+B[Y]?c(d.map(a=>a.slice(1,a[0]+1))):Y>X|0].push(d[w].shift(),d[w^1].shift())&&c(d):1:0 ``` [Try it online!](https://tio.run/##TdHdboIwFAfwe5@iV6aNHaF8iJJUo0@haWrSFJxsKMSymSV7d3Z6qmQ3hNPzO/8W@mG@jbP3ph/eXN9U9f3a3T7rn3G0spIbWimldnyvZQUPfZJHuVexZlt6kDt8qdQD3g56sVdHvbW0iq6mp0ZuTOTaxtZUcANwIRhj5XFz@I111H@5CyQ/dOQuzXmgjENxElPJ5nMIYqUo43Go3WCNqx2RRM2UylJOxFpzohJOkjUUmdYcGiLmZAVLvpVxAiznZMmJJ5wUASVYIPWuQJGjBpf9RwXG@dWQ5L0fTAOCRoLT/jy@l6PPcFDEAS0RiSnpuWcajpAHlGFMcKkXq9AucOaJCoyeNn3R50cD0jPb3VzX1lHbvdPpr71uw9LXfcA9sPEP "JavaScript (SpiderMonkey) – Try It Online") Takes the decks as an array of arrays of integers, top first; this array will be modified. Returns 0 for player 1 winning, 1 for player 2 winning. -12 from the original by removing `h` and instead reusing `d`, as well as a modification of an idea from tsh. ## Explanation ``` (d[[[A,B]=d,B]]^=Y=B[0])?…:0 ``` * `A` and `B` are set to the decks of player 1 and 2, respectively. * The default `toString` of arrays joins with commas, which is injective for arrays of integers, but not for arrays of arrays of integers – for example, it does not distinguish `[[1,2],[3]]` and `[[1],[2,3]]`. For that reason, `toString` is instead (implicitly) called on a new array, which lists the elements of A once and the elements of B twice. This distinguishes all possibilities because the numbers that appear twice must be from B while the numbers that appear once must be from A. * Additional properties of `d` are used to keep track of which configurations of cards have been seen before. + Indexing with a new string finds `undefined`, which gets converted to 0 before the XOR makes it equal `B[0]`. + Indexing with a previously-seen string finds the previous value of `B[0]`, which is necessarily equal to the current value, thus the XOR changes it to 0. (Player 1 wins immediately.) + If `B` is empty, `B[0]` is `undefined`, which also gets converted to 0. The string has to be new, making the result 0. (Player 1 wins immediately.) * Also, `Y` is set to Player 2's top card. ``` (X=A[0])?…:1 ``` * `X` is set to Player 1's top card; Player 2 wins immediately if Player 1's deck is empty. ``` d[w=A[X]+B[Y]?c(d.map(a=>a.slice(1,a[0]+1))):Y>X|0]… ``` * `A[X]` and `B[Y]` check whether the players have enough cards for a recursive sub-game, yielding the value of the last card to be used if there are enough, or `undefined` if there are not enough. The sum is a positive integer (truthy) if both are positive integers, or `NaN` (falsy) if at least one is `undefined`. * If there are enough cards, `c` is called to determine the winner of the recursive sub-game, using `slice` to extract the appropriate cards. * Otherwise, `Y>X` determines the winner, and `|0` converts it to an integer, 0 or 1. * `w` is set to the (0-indexed) winner. ``` d[w=…].push(d[w].shift(),d[w^1].shift())&&c(d) ``` * The two `shift`s take out the top cards of the winner and non-winner in that order, and `push` puts them on the bottom of the winner's deck. * Finally, `c(d)` calls the function again to repeat the analysis. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 114 bytes ``` ⊞υ⟦⟧≔⟦✂θ⟧ηWυ«≔№§υ±¹θε⊞§υ±¹✂θ¿›⬤θ∧κ›Lκ§κ⁰ε«⊞υ⟦⟧⊞η✂θUMθ✂κ¹⊕§κ⁰»«¿›⬤θκε≔‹§θ⁰§θ¹ε«≔∧⊟υ¬§θ⁰ε≔⊟ηθ»F²⊞§θε§§θ⁺λε⁰UMθΦκν»»ε ``` [Try it online!](https://tio.run/##dZJJa8MwEIXP9q@Y4whUSNKdnkygJZAWQ4/GB@NMIhNFjre2UPLb3ZFqJXGXgw6a5b2nz85VVudlpvs@7hqFnYQkFQ9h1DTFxmDyqoucsBKpBMXld1VoAuwEfIbBMDMvO9Ni1C7Mij6swAttspZwKoSEig/xYuDU/xnyJnauWAM@1cS9GiOtsZIQmRVuJfjqksymVbjlRa/H3YkQwnm5aMHoMcNVjZ2C52w/L3e7jOUr32KlqYSFyWvakWlphT89ePMApBtyPn/E3Q4xBjxLapqjSGVFTrn5OhWeUHAU9WTtw@Nyz7iZV9mOVU57ftyOKsfcVg981mUNOBMwgl/ZvVOGs3Ksuwa1S@8cfkN6LLR9KbMw3yTCQxjXBX9/jtL3SZLcSJg5hncS7iVc8Y@T3Eq45NpEwnWapv3Fm/4C "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a pair of lists and outputs `-` if player 2 wins, nothing if player 1 wins. Explanation: Charcoal doesn't really do recursion, so here's an iterative approach. ``` ⊞υ⟦⟧ ``` Start tracking previously seen positions for the top-level game. ``` ≔⟦✂θ⟧η ``` Create a dummy "calling game state" for the top-level game. ``` Wυ« ``` Repeat until all games have been resolved. ``` ≔№§υ±¹θε ``` See whether this position has been seen in this game or not. ``` ⊞§υ±¹✂θ ``` Save a (shallow) copy of this position to this game. ``` ¿›⬤θ∧κ›Lκ§κ⁰ε« ``` If a recursive game is possible, then: ``` ⊞υ⟦⟧ ``` Start tracking previously seen positions for the sub-game. ``` ⊞η✂θ ``` Save the calling game state for the sub-game. ``` UMθ✂κ¹⊕§κ⁰ ``` Create the state for the sub-game. ``` »«¿›⬤θκε ``` Otherwise, if this is a new position and both players still have cards, then... ``` ≔‹§θ⁰§θ¹ε ``` ... see who wins this position. ``` «≔∧⊟υ¬§θ⁰ε≔⊟ηθ» ``` Otherwise, remove the previously seen positions for this game, see whether Player 1 lost by running out of cards, and restore the calling game state. ``` F²⊞§θε§§θ⁺λε⁰ ``` Append the top card of both the winner and loser to the winner's hand. ``` UMθΦκν ``` And remove them from the top of both players' hands. ``` »»ε ``` Output whether Player 2 won. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 127 bytes ``` f=##!={}&&Check[#&@@@#,#&@@#=={}]/.{c__}:>MapAt[#~Join~{c}[[{n,-n}]]&,Rest/@#,n=If[f@@Check[{##2}[[;;#]]&@@@#',0<c],2,1]]~f~##& ``` [Try it online!](https://tio.run/##ldBNS8NAEAbge3/FysB6mdom2TStNWXFk4LgxzEsJSwJDdIoGk/L5q/H2dlavHoKO/PMO0OO9XBojvXQ2Xqa2hLgonReyrtDY98qkFprwPCBkupmceXsfu@vd4/1x@1Qwfjw3vWjs76qXI/z3hsj8aX5GhY01pf3bdVqHbMcQEpsuwUyIfYSlzfWYIqJMWM7Asjp@btrBv302fWUPd@1GowcX21NK2bOqQxFsvEoXIoi3dBDeY/USJYo1lQKLYWCWI5ihSIQFEVEKT@YBlewyFmTU39RwXGhGpOCD4NZQKSok/J4OCg0cx5QPJksY9SKUXKOOi3N4g15RIpjosuCWMd2wTP/QQXvP1/2S0@/htDMTz8 "Wolfram Language (Mathematica) – Try It Online") Input a list containing the decks in order, i.e. as `[{P1, P2}]`. Returns `False` if P1 wins, and `True` if P2 wins. ``` ##&!={}&& check for a loop Check[#&@@@#, attempt to take one card from each deck #&@@#=={}] if not possible, check which deck is empty /.{c__}:> the current round's cards are c: MapAt[#~Join~{c}[[{n,-n}]]&, append both cards in the correct order Rest/@#, to the winner's deck, n=If[ deciding the winner by: f@@Check[{##2}[[;;#]]&@@@#', attempt to play a subgame 0<c], if not possible, the higher card 2,1] bool -> player number ]~f~## recurse ``` [Answer] # Python3, 264 bytes: ``` k=lambda x,y,a,b,h,r:([a,[y,x]+a][r],[[x,y]+b,b][r],h+[[a+[x],b+[y]]]) def f(a,b,h=[]): if[a,b]in h:return 1 if not all([a,b]):return len(a)>0 x,y=a.pop(),b.pop() if x<=len(a)and y<=len(b):return f(*k(x,y,a,b,h,f(a[-x:],b[-y:]))) return f(*k(x,y,a,b,h,x>y)) ``` [Try it online!](https://tio.run/##bZBLjoMwEET3nKJ3Y4dmxDck1pCLWF7YSghRGAchRoLTM3aTH1JWll2vqqvdTUNzs9mu6@f5WrX61xw1jDihRoMN9oJJjXLCUYVayV6hlE5VoUFD1yaUUodyVGhCOSmleHA81VAz8ldScQEQwKV2MUZdLDSiPw1/vYXEv4K9DaDblpHMH1p7skzzQxz4KpX@7m4d42iWk3zjT7VA2h5hWi7m6a/Z5speW7g2MhqF6yijSSjOXcZncjxMnM9@g7PfgIs3UEshosSH0MmDrr/YgZ2ZzDOEZK8QZIqQ7t0ld0NeehIj7JziiRzB0QXCFsGTCOWKTemNHB4vCSzI5PD8A1tSuBeXXG/z/uzFfkVfmzx@czo6pWTf3BsKCskpLYlXU7bEJs8p91rZ0rJYsTmFLnjmwd1ClWRdsyXNezZ5OO6fRez8Dw) [Answer] # Scala, 150 bytes ``` (a,b,s)=>if(a.isEmpty)2 else if(b.isEmpty|s(a->b))1 else if(a(0)>b(0))f(a.tail:+a(0):+b(0),b.tail,s+(a->b)) else f(a.tail,b.tail:+b(0):+a(0),s+(a->b)) ``` [Try it on Scastie](https://scastie.scala-lang.org/kjetillll/grqQobjJSc2njPmAWZm0KA/4) [Answer] # Python 3, 262 bytes ``` def r(a,b,h=[]): while 1: if h.count((a,b))or not b:return 1 if not a:return 2 h.append((a.copy(),b.copy()));c,d=a.pop(0),b.pop(0) if len(a)>=c and len(b)>=d:q=r(a[:c],b[:d]);a+=([],[c,d])[q];b+=([d,c],[])[q] else:a+=([c,d],[])[d>c];b+=([d,c],[])[c>d] ``` Takes the top of the deck as element 0 in the lists, and returns 1 for Player 1 winning, 0 for player 2 winning. [Try it online!](https://tio.run/##XZNNjqMwEIX3nKKGFVaXovCTJiEi0mzmAtM7yxoZ7DRItKEN0UyfPlPGdELilf3e51e2KYavqelNer0qfQYbSaywKblgRQA0/jZtpyH2CzfaMzSbur@YKXIsY70F009QFVZPF2sgXqPOkd/O9uY0GzkM2iiKoKzhK2JYLRPGjjWqUm6Gfoi2TveTdWqnTSTZqaxBGjWvKlqp4rOk8/OiFljxQgl2lC9lxAVyShSMf4pj5QSFRPBZuKXqbtTFjDt2dtWpft5Qn5S4Tnqc/tRy1COUwOcEzrMU4wNBCSYHjDOBscDFire4x4S8DFPc4SsSgPmaSEhwFDE5@TviDpg9EznFkOwiCCQ@XRMHTGhr6hS@IzIjPt4K3N6IV3Qpex9NhVJXc7cmMvQMBfO9c3OCH4iccn0lT813m4lABMEgx7E17/Qsb/aigzO1RgutASvNu47cd7q/HVsazOrx0k20xa5M3gpOReFRiYXvgsG21H3hG5ngTAjhBcbJRi2jSbhEFjfZr2cPQf8bdD1pdbcfiySC@SpL936fr4Rn7v5P3O/9S1IfBbR1kYr1gX923RwCvnkcotWPkAVz863J3/2HXqNnSX@h2tAI2fU/ "Python 3 – Try It Online") ]
[Question] [ When I was posting answers for the [Husk Language of The Month thread](https://codegolf.meta.stackexchange.com/a/19387/80214), I realized it took more time to enter them in the thread than it took to actually write the answers. So, why not automate it? Write a program/function which inputs a language name, and displays all answers in that language during the current month so far) [Sandbox](https://codegolf.meta.stackexchange.com/a/20474/80214) # Introduction You are to find all answers in Code Golf Stack Exchange in the current month so far, whose first non-empty line matches the following: ``` #<whitespace>[<language name>(case insensitive match)]<anything else> ``` For example, the current month's answers should have been posted within the time frame of Nov 1 till the current date(Nov 6, as of this question's sandbox post). for each answer, you must find the following: * Question name * Answer URL * Answer Poster's Name * Answer Poster's Profile URL And format them in the following manner for Markdown: ``` - [<Question Name>](Answer URL) by [<Answer Poster's Name>] ``` Once you are done listing the answers, to keep the post short, you must key in the usernames to their respective profile URLs as follows: ``` - [<Answer Poster's Name>]:<Answer Poster's Profile URL> ``` This must be added at the end of the output. # Output The final result should look like the following: ``` - [Size up a number](http://example1.com) by [Razetime] - [My smartphone's Phonebook](http://example2.com) by [Bubbler] - [1,2,Fizz,4,Buzz](http://example3.com) by [Lyxal] - [Upgoat or Downgoat?](http://example3.com) by [LegionMammal978] - ..... [Razetime]:http://exampleA.com [Bubbler]:http://exampleB.com [Lyxal]:http://exampleC.com [LegionMammal978]:http://exampleD.com ... ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in each language wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~283~~ 282 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žgŽ7?-©ƵÇ+400÷®<т÷(®69-4÷®70-365*•ΘÏF•ºS₂+žf<£`žgт‰0Kθ4ÖOŽª+·*’¸¸.‚‹º.ŒŒ/–«?€¼=ƒËŠˆ&€š‚‚=ÿ’žYì.w„†ä_¡¦ε',¡нþ}Ùε’ƒËŠˆ.‚‹º.ŒŒ/’žYì©’ÿ…é/ÿ’.w……<h1¡¦ε„><S¡3èy’="/a/’¡1è'"¡н®"ÿa/ÿ"y'†§™’ÜÇ.µÔ/ÿ’¡1è…><"S¡64Sè`®¨ì)}ćнδª}€`ʒнlIlQ}ʒ1è'/¡4èXså]DεƵ=Sè`“- [ÿ](ÿ)€‹ [ÿ]“}»sε32Sè`"[ÿ]:ÿ"}Ù»¶2×ý ``` Ugh.. No TIO of the full program, because `.w` is disabled. **Explanation:** Step 1: Get the current year and month, and convert it to a Unix timestamp (using [this formula](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_16)): ``` žg # Push the current year Ž7?- # Subtract 1900 © # Store it in variable `®` (without popping) ƵÇ+ # Add 299 400÷ # Integer-divide by 400 ® # Push year-1900 again from variable `®` < # Subtract 1 т÷ # Integer-divide by 100 ( # Negate it ® # Push year-1900 again 69- # Subtract 69 D # Duplicate it 4÷ # Integer-divide the copy by 4 s # Swap so year-1969 is at the top again < # Subtract 1 to make it year-1970 365* # Multiply by 365 •ΘÏF• # Push compressed integer 5254545 º # Mirror it to 52545455454525 S # Convert it to a list of digits ₂+ # Add 26 to each: [31,28,31,30,31,30,31,31,30,31,30,31,28,31] žf # Push the current month < # Subtract it by 1 £ # Leave that many trailing items in the list ` # Pop and push them all separated to the stack žg # Push the current year again т‰ # Divmod by 100: [year//100,year%100] 0K # Remove 0s from this pair θ # Leave the last item 4Ö # Check if it's divisible by 4 # (this results in 1 for leap years; 0 for non-leap years) O # Sum all values on the stack Žª+ # Push compressed integer 43200 · # Double it to 86400 * # Multiply the sum by this 86400 ``` [Try just this first step online.](https://tio.run/##yy9OTMpM/f//6L70o3vN7XUPrTy29XC7tomBweHth9bZXGw6vF3j0DozS10TEN/cQNfYzFTrUcOiczMO97sB6UO7gh81NWkf3Zdmc2hxAtCUi02PGjYYeJ/bYXJ4mv/RvYdWaR/arvX/PwA) Step 2: Use this timestamp to create the stackexchange-API URL, and get the content of this url (which contains the JSON of all answers created this month): ``` ’¸¸.‚‹º.ŒŒ/–«?€¼=ƒËŠˆ&€š‚‚=ÿ’ # Push dictionary string "api.stackexchange.com/answers?site=codegolf&fromdate=ÿ", # where the `ÿ` is automatically replaced with the timestamp žYì # Prepend constant "https://" .w # Browse to this URL, and read its contents as string ``` [Try the first two steps online (without `.w`).](https://tio.run/##yy9OTMpM/f//6L70o3vN7XUPrTy29XC7tomBweHth9bZXGw6vF3j0DozS10TEN/cQNfYzFTrUcOiczMO97sB6UO7gh81NWkf3Zdmc2hxAtCUi02PGjYYeJ/bYXJ4mv/RvYdWaR/aDtQw89COQzv0DgMlZz1q2Hlol97RSUcn6T9qmHxotf2jpjWH9tgem3S4@@iC021qQO7RhWB1s2wP7wdqPbov8vCa//8B) Step 3: Extract all unique answer-id and question-ids from this JSON: ``` D # Duplicate the JSON „†ä_¡ # Split it on dictionary string "question_" s # Swap so the JSON is at the top again „Ž»_¡ # Split it on dictionary string "answer_" ‚ # Pair those two lists together ε # Map over the pairs: ¦ # Remove the first item ε # Map over each inner string: ',¡ '# Split it on "," н # Pop and leave just the first item þ # Pop and leave just the digits in this string }Ù # After the inner map: uniquify the resulting ids } # Close the outer map ``` [Try just this third step with the JSON as input.](https://tio.run/##7ZrbbtvIGYBfxeBFemOZcz4YCArFieNgk8BOgt0kRSGMyKFEhyIVkvIpCJDXaC@KXWDRN9irYnuRoLeLPkNeJJ0huakskrJMM72pDRuQ9Wt@zvDTf2aSqXGov3y5//nD3z5/@PHTz6OPP2Xm9b9@/fgP8/Lzh7/@9svHv//2yx@2P/70718//fP9p7@8//LFcZx3TpjrWebs/umdk5zGOnV23zmpni9ylYdJ7OxiJLnYdhaZTkeh7@wyAhGs/s/P59rZNR@fhFmuU@072848TYIw0qNwpiZWOM3zebbruqenpzuTVJ2oXKU7XjJzy5cuQZRBJEUw9nxAfeEpphVDeqwUAcz3/5jdhUjc8e@Gvo7z0EviO@ndw4d3grvQXM0Ps3mkzkexmtmLJSeZeTMK4zdLV/YSX0@SKNjJcuW90WfeVMUTXezBniJziyO5du37bSfMRsrz9Dw3p9kNVJTpbSfzktSoB0a1ynIjz8OTMD8f@So3b0OzfyEApaiSaz/MG2Reqot7elmEiNx2VJydVvcXQfMm23beLnRWfPrrm9SoSOLc3IVRFHo6zuyJ9/a27r0aPB9ukR1gtt8CUTAB5BJEihAEayCWd2CUFhuVrJ1qWN7UnXA2WZRYn@jg@eHO8XxSgZs0cfpOn4Tx1l66CI@zTMcdmBUncN9YPQPvq571/OBafkSAVn6FrIEf5@YXr/LjtIEfY7g7P87gEj0IALaX6M0GGZQSc0oB9pAPAq09OQbcpxqLMeUBv5YN3lcn5mMdkJbHcv1y/XqUaA1KziFuQ1nJmkwRU0BIDaUkdZSGeneUEi4bIqPS2vW1Sdbtbu/0bf7yKrt7kIbe1v3FLIzDqIujtLt1tVEy8CslN8DEjGW1YSplTZg44ZDUPWbfmBATYNlhUmy19cBpSNP986s4zdVxYtB0cIt2n261fD0bvI4N5Ri3sSllTWwYkUjU2eCe2VDGl9BICS39HtDER2hxehWa@yoOuyQZxTaNc7Orb2A0hBHWBqaUNYGBkNp4v@LbOOsZDKQM0yU0xNiq6DFOmeQQA02CMfM9qscyCChQATSmyjVDQLfEqTrEPJt2QFgcx7Vr1wMkawECTFoBFrImgFRShuqWBXoHSARZAmjSU9jFtqIp2ZkkySTSdmm1m@JODh6@uBiMZKZf@sIdfv159N/Xbx@4FxLvATw48Z5k7nya5ElplBeWbh3mM3Wh83DWJeUozuemvytYj5Wuwwokh21YS1kDViYIFfX00WYEK1g5k@AGWAngBC2HM0FtOrpZ/i/odZzoQRjsH1zlRIdprBaR3yXA2Z27qlrfPcIxZuraFmCVrNGREo5Y3ZGKnu3wtujeyJkyilhbmlLJmiAiAGmt6OYC9e1M4UrRVthwbwwDxgBVZpOI@AJDiE2xRnCgAkA8MpbgWgz12TzVWXacQYS7lW7mcO4lLd17KcycpS3DLEWrcRCuogOM2TqrKzom2XIaQxEC/UbB6eAhPwolVjppjoL3PffAP5ul6dGBIkcbRMHnx4lO/UMdx2E86WKQxSndrFAz/11Nd4hUckJbbLOSNSc6mNJ6FS5XANuvO7tJniP5cnnHpKB92ubYN85UBL5xsGPM1djjGiksfYQFMrXq9RoqdlcIII5kFzdrT@YuqegeMqnZe5u3rWRNOY4EsKH2AKJforcdzqvxQSZbjK4UrRpd31kNQnwZkSlpOOylcM/fvnm2vzOPryzcdbR1sNOleLdbLYp3HQ2mN2gzm3wftvUmK1kTIAIEafCKvA4I2frttvz7BuXfWqxQwrZqopI1TQ8gKbq/K1hRPZuRAN2g/JMMXAp2CMuNiz9O12FmbZifjx8//06pF8P4tBnz/tDVk6NH8@OHBGViA8yPddIl/NmzupFZ273nZowPkla7hA0zA9YzQAjQcikhOZOwX7NU@vwALvbTJ2kLr@HQHT55vVh48Q/34PEB9EZD8MOeH76@mCee/zTkg8PpJmnq0GY8pIsLtod2Vbm8e1pKAMSsDWYhWoVZa8aYfIbe@tj/uY/FErbOJCpZk49lBDR0bOhqsQ8BLsa2t1i/AVa8FitgqBVrIWvCSjHj9aqCiJ6N1WCly1ghZwBtGjuty792Z45i4Y2lr4mERJkvqg@xryjwuEcAU9frzD3Vnca8xSHdWF853l3L1eCALZP2UrTqaPseE0JGl9MeScDatKdDloNydhZFh2h@b9hskacTdxofTV9P9o6Rv0l4fKCyc5Udhl0CpD2fqwsF87CNnPn8bBFbVvae@Zd62ybA0o0yIgwpbLXZUtbYPC8vsNp3XU13CSlm712xEztyWeLOTQYOeikzH7/@/tXRVWXmvcV4HJldXR9gsVF3XK2/QaAEFLXNoipZAx0KjVet5bIMN3TFKb9JoEQYoUtmKfqcbFACRUA5V@NAcY8i6fsm/nOECUNjQsDGI@KnSeJHWnYyRAHduFrevezAAAjSirGQNRmZSWJtubk6oWqaFN/kiTRECLr0FEbxwE5vGAGTlEs@ZoBhSHAQcKkDTZUUihPM4MYYVaTnUxWZvy4kzaHcJQ3dyw4khWx5oKkSrUbDvu3uFtg1gVHQCqwQrQKrdW0gEzeJYxJAcqlbChHrJYy9evRy/@zKx5wS@3yft3Wi4q0HHTvYxZZdv9Q0MJoGeoMeNltLBdouf6NPrGSNxLCk9RpQkN4HvstpB@WU9ptuRt@zQfTs/MXhWUu6ee/IvXiciRf85UDnrzZIN/d1FGaHU5XNulhbcUQ3sDrmpY7uSQsqOy3NZEtZI1kiecMoX9YfoKGY39aB36gOXA@26D43witFq46071Tl/9WRrqXCKWw1t1LWYm4U1c2tNssFoiwCryD2523H@I3RrNhuni601ZPkajRTZ84uLh9vtP@neqZC@0SCuaAg7x3H@Q8) Step 4: Convert each question-id to an URL, and get its contents (which is the entire HTML page of a question): ``` ` # Pop and push both lists separated to the stack U # Pop the list of answer-ids and store it in variable `X` ε # Map over the question-ids: ’ƒËŠˆ.‚‹º.ŒŒ/’ # Push dictionary string "codegolf.stackexchange.com/" žYì # Prepend constant "https://" © # Store this string in variable `®` (without popping) ’ÿ…é/ÿ’ # Push dictionary string "ÿ/questions/ÿ", # where the first `ÿ` is automatically replaced with "https://codegolf.stackexchange.com/" # and the second `ÿ` is automatically replaced with the current question-id .w # Browse to this URL, and read its contents as string ``` [Try steps 3 and 4 with JSON input (without `.w`)](https://tio.run/##7ZpNb9vIGYD/isFDerHE@R6OgaCQnTgONgnsON2NUxTqiBxKdChSISl/BQGMHnrpLbf0UOwCxQIL9JpDW@wWsJFeCgT9Df4j6fBjU1kkZZlmeqkNG6b1cl7O8PH7ORPGcuCpT5/uXZz@6eL02/M/98@@i/X1hx/P/q4vL07/@PH92fcf3/9i9ey7f/94/tOb83dvfvurj@8vTt/98@35Hz58@6/fd89/p2@7OP3r2d@6H95@eGtq2Yef9s7/cvaDvjr/x8Xp9@c/mOnvd58@GYbx2vASNY6NtV@/NsLDQEXG2msjUpNpIhMvDIw1jAS3Vo1prKK@5xhrjEAEi7@T44ky1vTtQy9OVKQcY9WYRKHr@arvjeUwFY6SZBKvmebh4WF3GMkDmcioa4djM780CaIMImG5A9sB1LFsyZRkSA2kJIA5zi/juxBZd5y7nqOCxLPD4E50d/vBHfcu1E9zvHjiy@N@IMfpw8KDWH/oe8HLmSfboaOGoe9240TaL9WRPZLBUGVzSFcRm9mSzHTsm1XDi/vSttUk0atZc6Ufq1UjtsNIqwdatYwTLU@8Ay857jsy0R9DPX/LApSiQq4cL6mQ2ZHK3ullESJi1ZBBfFi8XwT1h2zVeDVVcXb35w@pVhEGiX4Lfd@zVRCnK97YWFnf6@z2VkgX6OnXQLSYBcQMRIoQBAsg5m@gH2UTFayeqpe/1K43Hk5zrI@Vu7vd3Z8MC3DDKk5fqQMvWNmIpt5@HKugAbNsBebLVE/H/qxnMT@4kB@xQC2/TFbBj3P9jef5cVrBjzHcnB9ncIYeBACnj2jNBhkUAnNKAbaRA1ylbDEA3KEKWwPKXX4tG7wnD/RtDZDmyzKdfPxilGgBSs4hrkNZyKpMEVNASAmlIGWUmnpzlALOGiKjIrXra5Ms293G4avk@VV2dz/y7JV707EXeH4TR5nO1lRaSccplNwAE9OWVYcpl1Vh4oRDUvaYbWNCzAKzDpPiVFsLnHo02jy@itNE7ocaTQO3mM7TLIYvZoMXsaEc4zo2uayKDSMCWWU2uGU2lPEZNELAlH4LaIIdND28Cs09GXhNkoxsmtq5paNvYDSEEVYHJpdVgYGQpvF@zrdx1jIYSBmmM2iItlWrxTilk0MMFHEHzLGpGgjXpUC6UJsqVwwBVROnyhCTeNQAYbYcMx27GCBZCBBgUgswk1UBpIIyVLYs0DpAYpEZgDo9hU1syx@R7jAMh75Khxazyd5k58Gzk05fxOq5Y5m9z18P/3v96r55IvAGwJ0D@3FsTkZhEuZGeZLSLcN8Kk9U4o2bpBzZ@szoZwWLsdJFWIHgsA5rLqvAyixCrXL6mGYEc1g5E@AGWAngBM2GM4um6ehy@b9Fr@NEtzx3c@sqJ9qLAjn1nSYBLp25KYvxzSMcY7qurQFWyCodKeGIlR2p1bId3hbdSzlTRhGrS1MKWRVEBCAtFd3cQm07UzhXtGU23BpDlzFApZ4kIo6FIcS6WCPYlS4gNhkIcC2G6mgSqTjejyHCzUo3vTjzkpbmvRSm11KXYeai@TgI59EBxtI6qyk6JthsGkMRAu1GwVHnAd/xBJYqrI6C92xzyzkaR9HOliQ7S0TB3f1QRc62CgIvGDYxyGyVZpypmfyspjlEKjihNbZZyKoTHUxpuQoXc4DTf3d2kzxH8NnyjgmLtmmbA0c7U8t1tIMdYC4HNldIYuEgbCFdq16voZLOCgHEkWjiZtOVmTMqmodMqude520LWVWOIwCsqD2A1S7R2w7n1fggEzVGl4vmja7trAYhPotIlzQctlK4J69ePt3sToIrC3flr2x1mxTv6VSz4l35ndEN2sw634d1vclCVgWIAItUeEVeBoTS@u22/PsC5d9CrFDAumqikFXtHkCSdX/nsKJyNiMAukH5Jxi4FOwQFksXf5wuwszqMO8OHu1@JeWzXnBYjXmzZ6rhzsPJ/gOCYmsJzI9U2CT8pWs1fT22ec9NGx8ktXYJK/YMWMsAIUCzpYTgTMB2zVKq4y043YweRzW8ej2z9/jFdGoH36zD/S1o93vgmw3He3EyCW3nicc726Nl0tRemvGQJi44XbQp8@HN01ICIGZ1MDPRPMxSM0bnM/TWx/7PfSwWsHZPopBV@VhGQEXHhs4X@xDgbNv2FusXwIoXYgUM1WLNZFVYKWa8XFUQq2Vj1VjpLFbIGUDLxs7U5V@7M0exZQ@Eo4iAROp/VAdiR1Jgc5sAJq/XmXuiGm3zZos0A3Xl9u5CrhoHrNlpz0XzjrbtbULI6GzaIwhYmPY0yHJQwo58fxtN1nvVFnk4NEfBzujFcGMfOcuEx/syPpbxttckQKbrM1WmYOLVkdP3j6dByip9Z86l3rYOsHSpjAhDCmttNpdVNs/zB8z3XefTXUKyvfem2Em65TLDnesMHLRSZj568fXezlVl5vp0MPD1rK4PMJuoOSjG3yBQAorq9qIKWQUdCrVXLeWyDFd0xSm/SaBEGKFLZmm1ubNBCbRcyrkcuJLbFAnH0fGfI0wYGhAClt4ifhKGjq9EI0O0oBkUw5uXHRgAi9RizGRVRqaT2LTcnN@hqtopvsmJNEQIunQKIzuw0xpGwATlgg8YYBgS7LpcKFdRKSzJCWZwaYzSV5OR9PVPE5J6UeaMhuZlBxKWqDnQVIjmo2HbdncL7JrAKKgFlonmgZW6NpBZN4ljAkByqVsKEWsljO09fL55dOUxpzA932evHMhg5X7DDnY2ZdPJNXW0po5aoofNFlKBaZe/0icWskpiWNByDWiR1jd8Z9MOyiltN930v2Yd/@nxs@2jmnRzfcc8eRRbz/jzjkr2lkg3N5XvxdsjGY@bWFu2RNNNdUxyHc2TFpR3WqrJ5rJKskTwiq18UT5AQzG/rQO/UB24GGzWfa6El4vmHWnbqcr/qyNdSIVTWGtuuazG3Cgqm1tpLxdYeRF4BbHfrBrab/TH2XSTaKpSPWEi@2N5ZKzh/Hhj@nekxtJLTyToB1rkjWEY/wE). Step 5: For each HTML-content of a question, get a list of its `[language_name, answer_url, user_name, user_url, question_name]` (this may contain some garbage in the result - i.e. the trailing item, or if an answer contains multiple `<h1>`-refs, but we'll filter those out later): ``` …<h1¡ # Split the HTML-content on "<h1" ¦ # Remove the first item ε # Map over each string: „><S¡ # Split it on both ">" and "<" 3è # Get the fourth item (which is the question name in the first iteration, # and language name in every other iteration) y # Push the string again ’="/a/’¡ "# Split it on "="/a/" 1è # Get the second item (which is the trailing answer-id URL portion) '"¡ '# Split that on '"' н # Pop and leave the first item ® # Push "https://codegolf.stackexchange.com/" from variable `®` "ÿa/ÿ" # Push dictionary string "ÿa/ÿ", # where the `ÿ` are filled again to create the answer-URL y # Push the string again '†§ '# Push dictionary string "person" ™ # Titlecase it to "Person" ’ÜÇ.µÔ/ÿ’ # Push dictionary string "schema.org/ÿ", # where the `ÿ` is replaced with "Person" ¡ # Split the string on that 1è # Get the second item …><"S¡ "# Split that on ">", "<", and '"' 64Sè # Get the seventh and fifth items # (which are the user name and trailing user URL portion) ` # Push those separated to the stack ® # Push "https://codegolf.stackexchange.com/" again ¨ # Remove the trailing "/" ì # Prepend it in front to create the user-URL ) # Wrap all four values into a list }ć # After the map: extract the first quadruple н # Pop and push its first item (the question name) δ # Map over each remaining quadruples ª # And append the question name as trailing item to each ``` [Try just this fifth step with the HTML as input.](https://pastebin.com/AKC8p6Fc) Step 6: Filter this list, so it only contains answers from the earlier list, and only the language that's equal to the input: ``` ʒ # Filter this list of quintuples by: н # Pop and leave its first item (the language name) l # Convert it to lowercase Il # Get the input in lowercase as well Q # And check that both are equal }ʒ # After the filter: filter once again: 1è # Get the second item (the answer URL) '/¡ '# Split it on "/" 4è # Leave its fifth item (the answer-id) X # Push the list of answer-ids from variable `X` så # And check if the current answer-id is in it ] # Close both the filter and outer map ``` [Try just the sixth step with the list of quintuples of the previous step as input.](https://tio.run/##rZZPTtwwFMb3nMLKpiAx4/xPXAEVUKRCJdSCKlUaZmESMzGTsaPYiWDRS3CDLipxiW7KjlVvNPXAxM4qHUvMYvRkv@/zL/Hzc7jA15Qsvy2fH/7@Lk/Lrz@eH7ynx3fwz8/w6fG7ePo1XS4nTuCjJHV2geN7aerG6yiJdIRCPWuioJtNYj3mdmNupGc75yT1dZ6nnZFW6DxkoqSLfKMwVHqNqHNOQqPVfGmnjQOdl2hSpMeQXiMNdaT5kFakqTPdmkycT42Yr8YKKSvxHsKM52TGy5uxkDibk7uswGxGxhlfQAxfbWHk@96L0Ue@oIxmoMUMnAhB2IZOjSC1gCjy/Bjmrx4j5TEincepAFQCrIwXFa0JYM3imtQfnOkumDhndryu4T3jDBdWjF4UxgjedrpBri/3suAM@HZ4vsHjrbCCi0PP9@BaNYh2xTaGOjjDLb7MalpJsH1yGe/sAhSA63tJxB4svIMrtlcdHArRLIgAssBS/RFAWdVIUGABVCmQlrD1@oDfgJzOqBRjcEFkUzOVAY44L4lKbHHZkPEerJTryldhZyUWYn9FC6vNmKu3fPrXw2625LBmuClzq22J0igOIDbK4Wruve5zZT2@FTs2uKpfGVwp7Mo7DBMvhWvVIOZxgeuM49LqTaLAoJ0TWtodvSR2fcjWskE4Nzo88k7s0Hqb/Jm0lIHjuqG31k3sxQTOVw6jrO8wvOmkLO/t@kRseO/ojFO7VpuiKIJa9/ZtLOnhfcSM2jUyhDw3hHmnGy5EsD3Lsh27ze7fWbilObGrRNcNInVTaeUg4IXd6e0dkQqri2ZuV35RkPjQCP/TB0HvtzFmrycDqb7FWE7u9jdTgxxLPJK4nhG5P8g33Vp9ifwD) Step 7: Convert it to the output in the specified format: ``` €` # After the map over the questions, flatten it one level down D # Duplicate this list ε # Map over the quintuplets: Ƶ= # Push compressed integer 214 Sè # Leave just the third, second, and fifth items ` # Pop and push them separated to the stack “- [ÿ](ÿ)€‹ [ÿ]“ # Push dictionary string "- [ÿ](ÿ) by [ÿ]", # where the `ÿ` are filled again }» # After the map: join the strings by newlines sε # Swap, and map over the quintuplets again: 32Sè # Leave just the fourth and third items ` # Pop and push them separated to the stack "[ÿ]:ÿ" # Push string "[ÿ]:ÿ", # where the `ÿ` are filled again }» # After the map: join the strings by newlines as well ¶2×ý # Then join these two strings with "\n\n" as delimiter # (after which the result is output implicitly) ``` [Try just the sixth and seventh steps with the list of quintuplets of step five as input.](https://tio.run/##rZZNa9swGMfv/RTClzXQRH5/KU1H32DtoGwtg0EamGqrsVpHNpYc2kOh7CP0Mga77DDoYdcORimFGHbooewz9ItkThvLPnkRNIegPHr@f/1iPXrkmKFDgicfJveXf2@j7ej9@f2lll@9guPvZn71keU/@psP13@uu/v51afHi29t0Mvv@ov5Xevx88/Hi99PP4v4@fiGPVwb@jRNmcaW8zvlPP86vhn/0vMv@e1k0lMM3XNcZQkouua6qj0bOZYYeaaYrUZGOevYIqaWMdUSs6Wz4@oiTxPOnlCIPK8aOeVIrxQVlVjDKp0ds9IKPrfU2obIcwSpJ2KeWMM1xUjweULhukp/oddT3mTsZBoLOU/YMoR@HOBBHB11GEf@CT71Q0QHuOPHQ4jgsy20dF17MtqMh4QSH4wQBVuMYTqnU8ZwyqBnaboNg2ePduHRxqXHNgOEA1QYDxOSYkCz4SFOXyv9JdBTduR41Yp3J6YolGLULNP24HGpa@R6d8bDmAJdDk@v8OIRk4KzTU3X4EzViHZA54Za3UEjtO@nJOFgcWvfbi0BzwCHZxyzFRhqqwd0JVldYywbYgZ4iHjxhQGhScZBiBgoSgGPMJ2tD@IjEJAB4awD9jDPUlpkgPU4jnCROEJRhjsrMClcp74Fth8hxrpTWpjMx5y85L9/PuzVlqylFGVRILUtlmvZBkSVsrmaa497t7DuHLOWDG7RrypczuTK2zQdzYUzVSPmRohSP0aR1JP0jAptF5NI7ug5tqpDOpM1wqnW2rq2JYdW2@S3eEQo2EgzcizdxJ5M4MnUoe3XHZo3HUfRmVyfsCveUzKIiVyrdT3LgkL38m3MqeFtIkrkGpnnaaoJg1LXXIhgceD7LbnNrt9ZaEQCLFeJqmpYxU0llI2Ae3Knt3ZEElRcNCdy5WcZjg4r4X/6IKh95sas9WTAizc6GuDT7nxqECCO2hylA8y7jXz9hembyD8) [See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand how the dictionary strings and compressed integers work. [Answer] # Python 3.6 and later + BeautifulSoup + requests, 681 bytes ``` from bs4 import* from requests import* from datetime import datetime as d import json def l(b): c='https://';s='.stackexchange.com';z="";y="";a=json.loads(get(c+'api'+s+'/answers?site=codegolf&fromdate='+d(d.now().year,d.now().month,1).strftime('%s')).text) for x in a['items']: k=BeautifulSoup(get(f"{c}codegolf{s}/questions/{x['question_id']}#{x['answer_id']}").text);t=k.select(f"#answer-{x['answer_id']}>div>div.answercell.post-layout--right>div.s-prose.js-post-body>h1");q=k.select('.question-hyperlink')[0];n=x['owner']['display_name'] if t and b in t[0].text:z+=f"- [{q.text}]({c+'codegolf'+s+q['href']}) by [{n}]\n";y+=f"[{n}]:{x['owner']['link']}\n" print(z+"\n"+y) ``` Relevant function is `l`, where you pass the name of language `b` Explanation coming soon ]
[Question] [ Consider \$3\$ binary strings of length \$n\$ chosen independently and uniformly at random. We are interested in computing the exact expected minimum [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between any pair. The Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. # Task Given an input n between 2 and 10, inclusive, consider \$3\$ binary strings of length \$n\$ chosen independently and uniformly at random. Output the exact expected minimum Hamming distance between any pair. Output should be given as a fraction. Your code should run in [TIO](https://tio.run/#) without timing out. [Answer] # [Pari/GP](http://pari.math.u-bordeaux.fr/), ~~92~~ 90 bytes 2 bytes saved thanks to @Nicolas! ``` n->sum(a=0,n,sum(b=0,n-a,sum(c=0,n-a-b,n!/a!/b!/c!/(n-a-b-c)!*min(a+b,min(a+c,b+c)))))/4^n ``` [Try it online!](https://tio.run/##JcpBCsMwDATAr8Q9KY2EEmiPzlMKksDBh6jGbd/vxokOu8OiIjXTVlqKzWn9/HaQOKNjl3aRnLbLpOiBJbAGtsBwTmRjuO/ZQSbFqw11srEfP17e0ruCxwWfM5aa/Qs@3AZaj0jgx1P7Aw "Pari/GP – Try It Online") $$ f(n) = \frac{1}{4^n} \sum\_{\substack{a+b+c+d=n\\a,b,c,d\geq 0}} \binom{n}{a,b,c,d}\min(a+b,a+c,b+c)$$ A more direct brute force approach may be shorter in some languages, but I'm not sure if that's true for Pari. Anyway, it's a shame that Pari's `min` only accepts two arguments. I can avoid the `min` and be about 6 times faster, but the compensating additional code makes it longer. Maybe in another language this is the shorter way. And maybe it is possible to simplify further and get rid of the innermost sum. ``` n->sum(a=0,n,sum(b=a,n-a,sum(c=b,n-a-b,n!/a!/b!/c!/(n-a-b-c)!*(a+b)*6/(1+(a==b)+(b==c))!)))/4^n ``` [Try it online!](https://tio.run/##HYxBCsMwDAS/EvUkxRZKoO1NeUpBNrjkUNW47ftdJ5dhWHa3Wtv5WXvR7rx9fi80XaLHw5JadLbTs6bDeRDEQBJIBsEz4kwwo4VE811wDeNCE4Wx10wERCTXh/fybui6xtsSa9v9iz5dJt4GCvoo9T8 "Pari/GP – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 31 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ḷṗ4S⁼¥Ƈɓ!×Ṗṁ4SƝṂƲ}:!P$}ð€S,4*$} ``` A monadic Link accepting an integer which yields a pair of integers, `[numerator, denominator]` (not reduced to simplest form). **[Try it online!](https://tio.run/##AUAAv/9qZWxsef//4bi24bmXNFPigbzCpcaHyZMhw5fhuZbhuYE0U8ad4bmCxrJ9OiFQJH3DsOKCrFMsNCokff///zEw "Jelly – Try It Online")** Or see [all of n=2 to 10](https://tio.run/##AV8AoP9qZWxsef//4bi24bmXNFPigbzCpcaHyZMhw5fhuZbhuYE0U8ad4bmCxrJ9OiFQJH3DsOKCrFMsNCokff8ycjEwwrUs4oCcIC0@IOKAnSzDhzpnLyTFkuG5mMaKKVn//w "Jelly – Try It Online") reduced to simplest form. ### How? Uses the same approach as [Christian Sievers' Pari/GP answer](https://codegolf.stackexchange.com/a/198730/53748) ``` Ḷṗ4S⁼¥Ƈɓ!×Ṗṁ4SƝṂƲ}:!P$}ð€S,4*$} - Link: integer, n Ḷ - lowered range -> [0..n-1] ṗ4 - Cartesian power 4 (all length 4 tuples using alphabet [0..n-1] Ƈ - filter keep those for which: ¥ - last two links as a dyad: S - sum ⁼ - equals n? ɓ ð€ - for each tuple do f(n, tuple): ! - factorial = n*(n-1)*...*1 } - use right argument: Ʋ - last four links as a monad: Ṗ - pop i.e. (a,b,c,d)->(a,b,c) ṁ4 - mould like 4 -> (a,b,c,a) Ɲ - for neighbours: S - sum -> (a+b,b+c,c+a) Ṃ - minimum × - multiply } - use right argument: $ - last two links as a monad: ! - factorial -> (a!,b!,c!,d!) P - product -> a!×b!×c!×d! : - integer division S - sum } - use right argument: $ - last two links as a monad: 4 - four * - exponentiate -> 4^n , - pair ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 26 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Ý4ãʒOQ}ε¨Ćü+ßI!*y!P÷}O4Im‚ ``` Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/198772/52210), which uses the same formula as [@ChristianSievers's Pari/GP answer](https://codegolf.stackexchange.com/a/198730/52210). Just like his answer, the output is not reduced to its simplest form. [Try it online](https://tio.run/##ATEAzv9vc2FiaWX//8OdNMOjypJPUX3OtcKoxIbDvCvDn0khKnkhUMO3fU80SW3igJr//zEw) or [verify all test cases](https://tio.run/##AUYAuf9vc2FiaWX/MlTFuHZ5PyIg4oaSICI/ecKp/8OdNMOjypJPwq5Rfc61wqjEhsO8K8Ofwq4hKnkhUMO3fU80wq5t4oCa/yz/). **Explanation:** ``` Ý # Push a list in the range [0, (implicit) input-integer] # (NOTE: Jonathan's Jelly answer uses the range [0,input) instead of # [0,input], but that doesn't pose an issue, since the mapped value will # result in 0, not affecting the total sum) 4ã # Create all possible quartets by using the cartesian product with 4 ʒ # Filter these quartets by: O # Take the sum Q # And check if it's equal to the (implicit) input-integer }ε # After the filter: map each remaining quartet [a,b,c,d] to: ¨ # Remove the last item d: [a,b,c] Ć # Enclose the list, appending its own head: [a,b,c,a] ü+ # Sum each consecutive pair: [a+b,b+c,c+a] ß # Pop and push the minimum of this I! # Push the input, and take its factorial * # Multiply both by each other y! # Take the factorial of each value in the quartet: [a!,b!,c!,d!] P # Take the product of this: a!*b!*c!*d! ÷ # Integer-divide the two: (min(a+b,b+c,c+a)*n!) // (a!*b!*c!*d!) }O # After the map: take the sum of all values in the list I # Push the input-integer again 4 m # And take 4 to the power this ‚ # And finally pair both together # (after which this pair is output implicitly as result) ``` ]
[Question] [ Do you know the book *Murderous Maths*, in the *Horrible Science* series? In the book, the Laplace Princess' "ridiculous" cipher might be interesting enough and simple enough to be a code-golf challenge. # Task The original cipher looks like this: > > Please read primes elephant help you me like cold > > > The nth word is only meaningful if it is a prime. So, the cipher becomes: > > read primes help me > > > Your task is to write a program that inputs the cipher and outputs the plaintext. # Rules * You can take the input in any acceptable forms, e. g. an list of words. * The input will only consist of printable-ASCII characters. * You can use 0-based index or 1-based index. * A "Word" includes any punctuation. For example: ``` This is, "a" great test! I think. ``` should output ``` is, "a" test! think. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-f`](https://codegolf.meta.stackexchange.com/a/14339/), ~~6~~ 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) I/O as arrays of words with 0-based indexing ``` Vj ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWY&code=Vmo&input=WyJQbGVhc2UiLCJyZWFkIiwicHJpbWVzIiwiZWxlcGhhbnQiLCJoZWxwIiwieW91IiwibWUiLCJsaWtlIiwiY29sZC4uLiJdCi1T) ``` Vj :Implicit filter of input array V :0-based index of current word j :Is prime? ``` --- ## Japt `-S`, 4 bytes I/O as space-delimited strings, with 0-based indexing ``` ¸fÏj ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=uGbPag&input=IlBsZWFzZSByZWFkIHByaW1lcyBlbGVwaGFudCBoZWxwIHlvdSBtZSBsaWtlIGNvbGQuLi4i) ``` ¸fÏj :Implicit input of string ¸ :Split on spaces f :Filter by Ï : 0-based index j : Is prime? :Implicit output, joined by spaces ``` --- ## Japt `-S`, 6 bytes I/O as space-delimited strings, with 1-based indexing ``` ¸fÏÄ j ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=uGbPxCBq&input=IlBsZWFzZSByZWFkIHByaW1lcyBlbGVwaGFudCBoZWxwIHlvdSBtZSBsaWtlIGNvbGQuLi4i) Same as above using `Ä` to add `1` to the index. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` #āpÏðý ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f@UhjweH@wxsO7/3/PyAnNbE4VaEoNTFFoaAoMze1WCE1J7UgIzGvRCEjNadAoTK/VCE3VSEnMztVITk/J0VPTw8A "05AB1E – Try It Online") ``` # # split the input on spaces ā # push [1..length of the list of words] p # is prime? Ï # keep only words where the above check is true ðý # join with spaces ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 22 bytes ``` *[grep &is-prime,2..*] ``` [Try it online!](https://tio.run/##HcoxCgIxEAXQ3lN8tthi0YAWNuId7MUimL9ucGKGGUVy@izsq5/S5NxLwzjj2qf7y6gYsx/UcuH@FML06Jedx4YZwzHgJoxOGGPCdhwU6hI/XywURas/FELym3hWSUP4V0veVw "Perl 6 – Try It Online") Takes input as a list of words and outputs the zero indexed list. [Answer] # [Kotlin](https://kotlinlang.org), 201 bytes Input is zero indexed. ``` fun p(s:Int):MutableList<Int>{val l=MutableList(0){0} o@ for(v in 2..s){for(e in l)if(v%e<1)continue@o l.add(v)} return l} fun main(){var w=readLine()!!.split(" ") for(i in p(w.size))print("${w[i]} ")} ``` [Try it online!](https://tio.run/##hVVhayM3EP3uXzExPboGZx1fP7Q1SZvj2l4DCRzJQSlHKfLu2CuslbaSNo7P@LenM6OV4xSOfjFr6WnmzZs30sZFo@3zbAY3tuvjAkKnKoSAnfIqYg1b5@sAzoICAmI5IuinBod15RG@oHegbY1PWJcj3n/vUc6unIfY6ACVqxHWzqygapQxaNe4YGATYxcWsxnv83YZoqo2@EQogpSVa2f/zOY/fjf/4XuGfzSoAsI9qho@et1iAMn3i4Od62Fj3ZbyISyd28Bd72ti1ge4U7EJU6LIWN7/3XmvlwbhodJopVyvMfxMGhzPTzP4VnWGJaGEBA3hWxh7XeuqNxR7DJXuGvQMbvW6ibBEShTRY4jargGt69cNKFtD0G1nkJHDYnSMVqLO@Wt1ko6fVNiMsuDO67W2ygwZwRDJQD3ZoGi8GJ0o5FmhLimEBjuSM0KDphOdWiEhJytn6mMGGxtpK2huuNkRUFkqYtUb0CvQkTYYq1LoEh7cVCQaGC2RGoYDk1MKkpmy8vqfridTUGGchRTYeh1RQrq1Vy3FU5SHvRhyB4bwrKHrI@/IMrWFlX6KSaz73mDIKaBS1Eol2mAKR78UYgeqqrCLaplaQRZtyRtUzLqkbVIlRHCrZO/yKE2KsNXGJGUqZ8OApBqthDtn8LuH9zc33EevKnLBECIz6qk3F@dLalGdJoa6CvPThYR/B@M/iMCY1irT1yQhM@96W8VeRe1sCb85MR0@KXbVIhElSTVVM1ZjWPMMQiQbnsENO8RuSmBUaFxvspK8kE8kbEbyzq9PHYnOg8yZKS0pQB6hLrdoo7SvUoYmgaY9N2toOWni5MoI1B46PqwXQX/BBc1ZnCxoQkW3W8Jc0spPsB@NACjOXW6cdAPbLu6kYIhbB72NmrqwSlDbt0vyRu7YlEYZB7Me51ElaDItfT/SEEnkq1MKxcUE9nABB0KQOOiv6YNvsILwPVsA3pYl858kohKUWSl2xeq0eiJhIThYKT/NSCLF1q9670k8GILSfD4iOSqjav2oAynNrGC5kyMSdEr3J3kv40hdzmfJ/ilUKTvClyae@8OMucyJ7AATSKW8yYBLmOdNYEvTjdXjtRR/LPAm0U501xh5mj2xYYH7wPpm5HAtcN2qrhlAJPlsMgGj5Is2Ew/OfYA0hEPn7zH23r5UHficT4t8eHQ4djK8tmhLl8FXfFrKi5EN@mrCYeVdK8s0mp4eP6P52masS2@BvIcU4gPGwc/D0HOfOU16VphxiphewpAMi6pqcv9qTeHVLvNgdBoNpv53wa5ib@Y4V3KF3tKbW0zOzkqhVoxhPMm2TBeIPo5WurLEoKmrcjMV42/2svNZ8H8dOIKoKGnTqzHcvfJMc@yTd4i2317MyYp0PTzLIBdhIfP73/Hdy1xdvR6p/cVh5K5HFLR4zCM02fNfmSgz0avi8Q1ezicv/huZ5JHJYZRbfzgKVUz2otHV19Th2FpkKbaDGi9CfNYiwOH5eXgpa/e/j@XLS/kv "Kotlin – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` LÆRị ``` A monadic Link accepting a list of words which yields a list of words. **[Try it online!](https://tio.run/##y0rNyan8/9/ncFvQw93d/w@3a@s/alpzdNLDnTP@/49WD8nILFbXUVDPLNYBUUqJSiAqvSg1sQTEKEktLlEEMTzBvIzMvGz1WAA "Jelly – Try It Online")** (the footer calls the Link then formats, since a full-program implicitly smashes output) ### How? ``` LÆRị - Link: list, W L - length (W) ÆR - inclusive prime range = [2,3,5,7,...,Prime <= length(W)] ị - index into (W) ``` --- Also 4: ``` JẒƇị ``` [Answer] # [PHP](https://php.net/), 167 bytes ``` <?php $i=explode(' ',$argv[1]);$l=count($i);unset($i[0]);for($x=1;$x<$l;$x++){$y=$x+1;$z=2;while($z<$y){$t=$y/$z;if($t==(int)$t)unset($i[$x]);$z++;}}echo join(' ',$i); ``` [Try it online!](https://tio.run/##PY7BCsIwEER/ZQ8LJlTQek2Dv@C9eCjtaqJrEtpU20q/PUYEL8NjBmYmmJBSdQwmAFpNU2DfkdjAZotNf33W5VkqZN360UWBVqrRDfSlep@Ti@8FTrpUOFXIWYtCvnHWGbK36IN6GcskcKlwzknUOO9wUfYiMmthXZQY5b8Tp@/cUhRqXak1Hm7eut@bPJ1SOjE1A0FPTQehtw8agJiCaVwEQxxg9iM8CNjeCVrP3Qc "PHP – Try It Online") ### Ungolfed: ``` <?php $input = explode(' ', $argv[1]); $length = count($input); unset($input[0]); for($x = 1; $x < $length; $x++) { $y = $x + 1; $z = 2; while($z < $y) { $test = $y / $z; if($test == (int) $test) { unset($input[$x]); } $z++; } } echo join(' ', $input); ?> ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~125~~ 107 bytes 107 bytes thanks to Black Owl Kai ``` i=input().split();j=k=1 for c in i: if j>1: while k>2: k-=1 if j%k<1:k=0 if k:print(c) j+=1;k=j ``` [Try it online!](https://tio.run/##HYpBDoIwEEX3nOJvTCBGY3UHljN4BQJDOp3SNlBiOH0trt5/eT8eyQT/ypk1@7inurlv0XFhZ7VoVc1hxQj24LYCz7C9KgNfw44g/fMUyK08C89@kbdqRT@qv0obV/apHpsK9qpVJ9rm/HE0bISVhgmlL7SBHEUz@ARDLuIIOxaCYyGMwU0/ "Python 3 – Try It Online") 120 bytes if it strictly follows rules. -25 bytes thanks to Black Owl Kai # [Python 3](https://docs.python.org/3/), ~~145~~ 120 bytes ``` i=input().split();j=k=1;l=[] for c in i: if j>1: while k>2: k-=1 if j%k<1:k=0 if k:l+=[c] j+=1;k=j print(*l) ``` [Try it online!](https://tio.run/##HYxBDoIwFET3PcVsTECisboDyxncExYEPuHTT2mgxHD6Cq7evJlk/B6G2b1iZMPObyFJ76sXPliMxhpdiKlq1c8LWrAD5wrcYyz1EfAdWAi2fJ4CezP65Llf7Fvn1jzUX20umanaWmHMjktrRuUXdiG5ShrjR6hZCQs1HY56ohUk5IfGBQwkHvu8YSIIW0I7S/cD "Python 3 – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 90 bytes ``` print(*[w for n,w in enumerate(input().split()[1:])if all((n+2)%i for i in range(2,n+2))]) ``` [Try it online!](https://tio.run/##Tc1NasMwEAXgvU/xMASkNpSMnH/oHbpPs1DrcSwqj4UsE3J6V3Y2Wc1jmPdNeKS2l2pqPr3tfmp7/p5CdJLU2@WOpo@Q9R1OwDJ2HG1i5SSMSemPIXiX54XOV@0aWO@VknejV27pubkVrdxYmfW811c9NUoXT76MbGvk3PGAln1Ax6UuXg4MKuxwABGoAuVwKvX05dkOjNc2ew6tlfRkHv2YKXj3x/jtfV0QZmmbrX3WjjiBNgtqFncL2oH2y4Nj/gGz@Qc "Python 3 – Try It Online") [Answer] # Rust, 339 bytes First ever submission to Code Golf, but it works! ``` use std::io;use std::io::BufRead;fn main(){println!("{}",io::BufReader::new(io::stdin().lock()).lines().flat_map(|s|s.unwrap().split_whitespace().map(|s|s.to_owned()).collect::<Vec<String>>()).enumerate().filter(|(x,_)|{if *x<2{return false}for i in 2..*x{if x%i==0{return false}};true}).map(|(_,y)|y).collect::<Vec<String>>().join(" "));} ``` This code is compressed down from this: ``` use std::io; use std::io::BufRead; use std::io::BufReader; fn main() { let s = BufReader::new(io::stdin().lock()) .lines() .flat_map(|s| { s.unwrap() .split_whitespace() .map(|s| s.to_owned()) .collect::<Vec<String>>() }) .enumerate() .filter(|(x,_)| { if *x<2 { return false } for i in 2..*x { if x % i == 0 { return false } }; true }) .map(|(_,y)| y) .collect::<Vec<String>>() .join(" "); println!("{}", &s); } ``` [Answer] # [Ruby](https://www.ruby-lang.org/) `-p -rprime`, 36 bytes Replaces every word (and the space after it, if present) with the empty string if it is a non-prime word. ``` i=0 gsub(/\S+ ?/){$&if(i+=1).prime?} ``` [Try it online!](https://tio.run/##HcyxDoIwFEbhnaf4JcZAUNAHIMxsJjq6FLnSGwptestAjK9uNawn@Y5fujVGrs/JIEuXVY9bgabK3/sDvzIu6kteOs8TNZ8Yr4aUEDypHlsUkCGn1RygyTisdsFEMDwSntb0yV2zgOWIVKUY/jAgkIQdWgTN81h@rQtsZ4kn57flDw "Ruby – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 95 bytes ``` #define f(w,n)for(int i=0,j,p[n]={};++i<n;p[i]||printf("%s ",w[i]))for(j=i*i;j<n;j+=i)p[j]=i>1; ``` [Try it online!](https://tio.run/##bZDBbsMgDIbvPIXFNCk0TGq1I2MvEuVQpaYx6kxEaJmW5tkz2HaZNh8M5v/8C3t4Og/Dtj2c0BEjuCZrVi7EhjgB2b32euq4t8tq2pZe2Ewd9ff7FIvuGvk4g9S5PKmvJm9pR8YXzLeW1NT53tLrwWxiGI9xBznE09z1YGGRHxiD1DIwlpxyvacxYqkE/ArpwjUW1dGtojO9/0VmvCEXEek8pnIy8T9G6Zu5/MAp46VYrkbUqAO/HYkbBYuoi6h/1YdnUFWHiOkaGfZGrNsn "C (gcc) – Try It Online") Sieve of E. [Answer] # [R](https://www.r-project.org/) + gmp, 48 bytes ``` (W=scan(,'',,,,''))[gmp::isprime(1:length(W))>0] ``` [Try it online!](https://tio.run/##HY2xCsIwFEV/5dolCZSia0EHN3ehgzik9pE8NK8leSJ@fWy94zkcbq7VDsfy8GJbY9p1xjh3C2npey5L5kT20L9IgkY7OHfa3@s1cgGXFo1vEDJ5hVLRHS7QyPLscH4rkv@OhA9BiCboDI/XLIEyinqlRKIb3UpEDnEV5v9XDHwmjMQSMM1CXf0B "R – Try It Online") This use `gmp` for the `isprime` builtin. This returns 0, 1 or 2, hence the test for > 0. `scan` takes the input as characters split on whitespace and quotes set to empty string. [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 8 bytes ``` ⌈'&›¥æ;Ṅ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%8C%88%27%26%E2%80%BA%C2%A5%C3%A6%3B%E1%B9%84&inputs=Please%20read%20primes%20elephant%20help%20you%20me%20like%20cold&header=&footer=) ``` ⌈ # Split on spaces ' ; # Filter by &› # Increment register ¥æ # Register prime? Ṅ # Join on spaces ``` ]
[Question] [ This challenge is pretty simple: Your task is to draw a schematic of a (simplified) memory array. You will be given two (positive) integers `n,m` and the task is to draw the `n:2^n` decoder connected to the memory array with `d` data lines. The addressing will be in the order of [gray codes](http://mathworld.wolfram.com/GrayCode.html), to check if the sequence is correct, see [A014550](https://oeis.org/A014550). For simplicity there are no input ports, write ports etc. On the top of the decoder you need to specify its type (e.g. `2:4`) and you will label the data lines with `d:[d-1],...,d:1,d:0`. If the cray code wouldn't fit the decoder width, you'll need to expand the width, see the last two examples. ## Rules * Leading whitespaces are not allowed * Trailing whitespaces are allowed * At the end of the output there may be one or several newlines * You can assume the following constraints on the input `0 < n` and `0 < d <= 1e4` * The output is either printed to the console or you write a function that returns a newline-separated string * For invalid input the behaviour of your program/function is left undefined ## Test cases ``` n = 1, d = 1 .-----. | 1:2 | | | | 0|---+ | | | | | .+. | | | +-+ | | `-' | | 1|---+ | | | | | | | .+. | | | | +-+ | | `-' | `-----' | d:0 ``` --- ``` n = 1, d = 10 .-----. | 1:2 | | | | 0|---+-----+-----+-----+-----+-----+-----+-----+-----+-----+ | | | | | | | | | | | | | | .+. .+. .+. .+. .+. .+. .+. .+. .+. .+. | | | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | `-' | `-' | `-' | `-' | `-' | | 1|---+--(--+--(--+--(--+--(--+--(--+--(--+--(--+--(--+--(--+ | | | | | | | | | | | | | | | | | | | | | | | | | .+. | .+. | .+. | .+. | .+. | .+. | .+. | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | `-' | `-' | `-' | `-' | `-' | `-----' | | | | | | | | | | d:9 d:8 d:7 d:6 d:5 d:4 d:3 d:2 d:1 d:0 ``` --- ``` n = 2, d = 3 .-----. | 2:4 | | | | 00|---+-----+-----+ | | | | | | | .+. .+. .+. | | | +-+ | +-+ | +-+ | | `-' | `-' | `-' | | 01|---+--(--+--(--+ | | | | | | | | | | | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | | `-' | `-' | `-' | | 11|---+--(--+--(--+ | | | | | | | | | | | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | | `-' | `-' | `-' | | 10|---+--(--+--(--+ | | | | | | | | | | | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-----' | | | d:2 d:1 d:0 ``` --- ``` n = 4, d = 5 .------. | 4:16 | | | | 0000|---+-----+-----+-----+-----+ | | | | | | | | | .+. .+. .+. .+. .+. | | | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | | 0001|---+--(--+--(--+--(--+--(--+ | | | | | | | | | | | | | | | .+. | .+. | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | | 0011|---+--(--+--(--+--(--+--(--+ | | | | | | | | | | | | | | | .+. | .+. | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | | 0010|---+--(--+--(--+--(--+--(--+ | | | | | | | | | | | | | | | .+. | .+. | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | | 0110|---+--(--+--(--+--(--+--(--+ | | | | | | | | | | | | | | | .+. | .+. | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | | 0111|---+--(--+--(--+--(--+--(--+ | | | | | | | | | | | | | | | .+. | .+. | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | | 0101|---+--(--+--(--+--(--+--(--+ | | | | | | | | | | | | | | | .+. | .+. | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | | 0100|---+--(--+--(--+--(--+--(--+ | | | | | | | | | | | | | | | .+. | .+. | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | | 1100|---+--(--+--(--+--(--+--(--+ | | | | | | | | | | | | | | | .+. | .+. | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | | 1101|---+--(--+--(--+--(--+--(--+ | | | | | | | | | | | | | | | .+. | .+. | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | | 1111|---+--(--+--(--+--(--+--(--+ | | | | | | | | | | | | | | | .+. | .+. | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | | 1110|---+--(--+--(--+--(--+--(--+ | | | | | | | | | | | | | | | .+. | .+. | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | | 1010|---+--(--+--(--+--(--+--(--+ | | | | | | | | | | | | | | | .+. | .+. | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | | 1011|---+--(--+--(--+--(--+--(--+ | | | | | | | | | | | | | | | .+. | .+. | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | | 1001|---+--(--+--(--+--(--+--(--+ | | | | | | | | | | | | | | | .+. | .+. | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | | 1000|---+--(--+--(--+--(--+--(--+ | | | | | | | | | | | | | | | .+. | .+. | .+. | .+. | .+. | | | | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | `------' | | | | | d:4 d:3 d:2 d:1 d:0 ``` --- ``` n = 1, d = 1024 (output truncated!) .-----. | 1:2 | | | | 1|---+-----+----... | | | | ... | | .+. .+. ... | | | +-+ | +-+ ... | | `-' | `-' | ... | 0|---+--(--+--(-... | | | | | | ... | | .+. | .+. | ... | | | +-+ | +-+ ... | | `-' | `-' | ... `-----' | | ... d:1023d:1022d:1021... ``` --- ``` n = 10, d = 1 (output truncated!) .-----------. | 10:1024 | | | | 0000000000|---+ | | | | | .+. | | | +-+ | | `-' | ... ... ... ``` --- ``` n = 12, d = 5 (output truncated!) .-------------. | 12:4096 | | | | 000000000000|---+-----+-----+-----+-----+ | | | | | | | | | .+. .+. .+. .+. .+. | | | +-+ | +-+ | +-+ | +-+ | +-+ | | `-' | `-' | `-' | `-' | `-' | ... ... ... ... ... ... ... ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 185 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` b :2b^:D⁰∑l2+bIΧCc┌*:A .1ΟO@c*┐1Οd5*2+∙ `a '+++;31žƧ01bH{╬⁰1w⁄»Ƨ01*□+}I{∑4⌡@}¹cb-2+3žKOKOād0C{āe{"h}‼Τ─īsgQ⅛&šε╬»‘6n┌eF-¡3**41ž┐c3*∙ceF-*¡³ (*ž61ž┼}+1C}@5*┐+e*+d┌@4*Ο;┼øe∫eκƧd:ΚF6*1ž}+┼ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=YiUyMCUzQTJiJTVFJTNBRCV1MjA3MCV1MjIxMWwyK2JJJXUwM0E3Q2MldTI1MEMqJTNBQSUyMC4xJXUwMzlGT0BjKiV1MjUxMDEldTAzOUZkNSoyKyV1MjIxOSUyMCU2MGElMjAlMjcrKyslM0IzMSV1MDE3RSV1MDFBNzAxYkglN0IldTI1NkMldTIwNzAxdyV1MjA0NCVCQiV1MDFBNzAxKiV1MjVBMSslN0RJJTdCJXUyMjExNCV1MjMyMUAlN0QlQjljYi0yKzMldTAxN0VLT0tPJXUwMTAxZDBDJTdCJXUwMTAxZSU3QiUyMmglN0QldTIwM0MldTAzQTQldTI1MDAldTAxMkJzZ1EldTIxNUIlMjYldTAxNjEldTAzQjUldTI1NkMlQkIldTIwMTg2biV1MjUwQ2VGLSVBMTMqKjQxJXUwMTdFJXUyNTEwYzMqJXUyMjE5Y2VGLSolQTElQjMlMjAlMjgqJXUwMTdFNjEldTAxN0UldTI1M0MlN0QrMUMlN0RANSoldTI1MTArZSorZCV1MjUwQ0A0KiV1MDM5RiUzQiV1MjUzQyVGOGUldTIyMkJlJXUwM0JBJXUwMUE3ZCUzQSV1MDM5QUY2KjEldTAxN0UlN0QrJXUyNTND,inputs=NCUwQTU_) Way too long... [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~170~~ 157 bytes ``` NνNδAX²νηA⪫⟦θ:Iη ⟧ωθA⌈⟦νLθ⟧ζ←“ E*lÿxγ∨P3ζgRU#@˜R2$⁴⟧”F⁻δ¹C±⁶¦⁰↓←| F⁻η¹C⁰¦⁵P←×⁺+×-⁵δ⸿P| ←M×⁵η↓Fδ«P⁺d:ιM⁶←»↑←'-←ζ↑`↑²↑×⁵η.-P⁺¶θζ↓.↓²P↓×⁵η←Fη«Fν←§0110÷ιX²κMν⁵ ``` [Try it online!](https://tio.run/##PZC/SgNBEMZ7n@JAQVAuJP5pUtnYS57AEEGLgGBlYZFtjggWF66IhRJESNQY0Xh3e7lsCOz14zvMC@wjnN/EYLGzy/zm@75lWhfNq9Zls12WznzQQkrszJMzmZ3SgjTe/DbmwZCyujOvpD0ejH5uKRNw1xUA0TtlaFPKQcidB@94p10sr@mbuy8n@5SeN5xJNo/sfWNvi1WMSe48OjNkNafYzpx5tl@sUovGJwcRTG48b831igMITZzBQFj0WeW7Rd9Hh2LOlmhDAeLMRGBCGj5wgP1YNCo/qxOMJojBmJ1z0MO97aPIr3unOHaKspZX/D@ZTSmTgaiCY6er/Og/IpQILRHYgviOqrVatdASJfvLkQigkrI82Dj8BQ "Charcoal – Try It Online") [Verbose approximation.](https://tio.run/##ZVLLTsMwEDzTr1j5wlqxq7aiHMoJwaWIoh6AC0UiNG5jkThp4rQ8vz2skz7S9GTvanZmdux56GfzxI/KcmzSwj4U8bvK0PCrTrMOqL7Oc700OE021BgIMFxAeOjfJdrgy0oAGzEBN35uMSQEA/YqYEO31QE78T91XMT4YgTcK7O0Ia74K2G@CTPNtLE4ulcLS@O/M/ML5/JtZjzpQVV1va47XIFSelLKmWE0uEgywIk2RY6BgD7ncJOkX/iglr5VeEn0PUJNkrXC0W2yMadaAC2esMHTEzB080Vkddqce9SxynEaEZ55bFczydwAqQZ8r8RmGWtxPKvM6rkfuagq@dqgo94VNeHQxS1gZ71yGXD46Zw16GoXgXsC7WTPKoJLGtsS/m35n9KT9c8la/ca7/GUEuSNHTcGx@XWKPk8bNyVrY1ri/Rk7kvscQ0ltyBpdVm7NWhFV3cb6bTTqzIKq4yqq@FwtN61HZtAfSLr9fs98jM29lavdaBQC9h/9A/OqyjvijhFU/@Cv7K86AxLuS5lHv0D "Charcoal – Try It Online") Explanation: ``` NνNδAX²νηA⪫⟦θ:Iη ⟧ωθA⌈⟦νLθ⟧ζ ``` Sets up the variables used in the rest of the code. `ν` and `δ` are the inputs, `η` is `2``ν`, `θ` is the label at the top of the box, while `ζ` is one less than the width of the box. ``` ←“ E*lÿxγ∨P3ζgRU#@˜R2$⁴⟧” ``` This compressed string represents the bottom left decoder. This is the one that's most representative, although ironically it first gets printed in the top right and then copied left and down. ``` F⁻δ¹C±⁶¦⁰↓←| ``` The decoder is repeated horizontally, and the `--(` at the top right of the last decoder is changed to a `|`. ``` F⁻η¹C⁰¦⁵P←×⁺+×-⁵δ⸿P| ←M×⁵η↓ ``` The decoder is then repeated vertically, and the `(`s in the top row are changed to `-`s (if you look carefully you'll see that too many `-`s are printed but fortunately the last one gets overwritten by the `0` of the address), after which the `|`s for the top right decoder are removed. ``` Fδ«P⁺d:ιM⁶←» ``` The decoders are numbered right-to-left. ``` ↑←'-←ζ↑`↑²↑×⁵η.-P⁺¶θζ↓.↓²P↓×⁵η← ``` The box is printed, including the label. ``` Fη«Fν←§0110÷ιX²κMν⁵ ``` The Gray codes are printed. ]
[Question] [ # Am I under Budget? Every 2 weeks when I get my cheque, I allocate a certain amount to last me until my next cheque, and bank the rest. To figure out how much I can spend per day and still remain under/on budget, I just need to divide the allocated amount by the number of days it needs to last me. On Day 1 if the budget period is 14 days and I start with $400, I can spend ($400 / 14 =) $28.57 a day. If I go over budget on any days though, I have less to spend during the rest of the budget period. Say I spend $50 on Day 1. I now have $350 starting Day 2, and can only spend ($350 / 13 =) $26.92 a day instead of $28.57 for the remainder of the period. # Problem Write a program/function that when given a starting allocation and a list of daily expenditures, returns a list of how much I could spend on each day to stay on budget, and a symbol indicating whether or not I was over/under/on budget that day. # Example Pretend for this example the budget period is only 5 days. * Period Allocation = $100 * Daily Expenditures = [20, 20, 30, 0, 0] This should return (output variations are allowed. See Output section): ``` ["= 20", "= 20", "^ 20", "V 15", "V 30"] ``` * On Day 1, I can spend (100 / 5 =) $20. I spent the entire daily budget, so I was on budget (`=`). The first entry of the result is "= 20" to show this. * On Day 2, I can spend (80 / 4 =) $20. Again, I spent the entire amount, so the second result entry is the same as the first. * On Day 3, I can again spend (60 / 3 =) $20, but I went over budget by spending $30! I was allowed to spend $20, but went over, so the third result entry is "^ 20"; "^" meaning "over-budget. * On Day 4, I can spend (30 / 2 =) $15. I spent nothing however, so I was under budget. The fourth result entry will be "V 15"; "V" meaning "under-budget". * On Day 5, I can spend (30 / 1 =) $30. I again spent nothing and was under budget, so the fifth and final result entry is "V 30". # Input Input will be: * A number representing the total money allocated for the period. * A sequence representing how much was spent on each day during the period The number of days in a period is = to the length of the daily expenditure list. ## Input Rules: * Your program must handle decimal allocation amounts. * The allocation amount can be taken as a number or string. A dollar sign is allowed for string representations (but optional). * You can assume the budget period will be at least a day long (daily expenditure list will contain at least 1 entry). * You can assume I won't spend more money than I allocated. * A delimited string would also be a acceptable form of input # Output Output will be a sequence of symbols and numbers showing how much I was allowed to spend on that day, and whether or not I went over. Output can be returned or printed to the stdout. ## Output Rules: * Any non-numeric symbols can be used to indicate on/under/over budget, as long as you chose a different symbol for on, under and over. If you don't use "="/"V"/"^", make sure to specify in your answer what symbols you're using. * The symbol can appear before or after the number * Output can be any form of sequence where it's clear what parts belong to what day. The examples here use a sequence of strings, but a sequence of pairs/lists would be fine as well. * Output must be accurate to at least 2 decimal places (but more is fine). It must be properly rounded using 4/5 rounding if only accurate to 2 places. * A long string instead of a sequence of strings is fine too, as long as there's some delimiter separating output for each day so it's readable. # Test Cases ``` 10, [1, 2, 3, 4, 0] ["V 2", "V 2.25", "^ 2.33", "^ 2", "= 0"] 25, [20, 2, 3] ["^ 8.3", "V 2.5", "= 3"] 1000, [123, 456, 400] ["V 333", "^ 438.5", "V 421"] 500, [10, 200, 0, 0, 100, 50, 50] ["V 71.43", "^ 81.67", "V 58", "V 72.5", "^ 96.67", "V 70", "V 140"] ``` This is code golf, so the smallest number of bytes wins. [Answer] # Javascript, ~~67~~ 66 bytes ``` a=>b=>b.map(c=>`v=^`[(c>(e=((a-=c)+c)/d--))-(c<e)+1]+e,d=b.length) ``` # Explanation This is an anonymous function that takes input through currying syntax (`f(a)(b)`). In this case, the fist number is the total budget, and b is an array of the money spent during the time period. The function loops over `b`, but first sets `d` to the length of the array `b`. Then, for each element `c` in `b`, an inner function is executed (``v=^`[(c>(e=((a-=c)+c)/d--))-(c<e)+1]+e`). This inner function calculates the budget for that day by dividing the amount left (`a`) by the number of days left (`d`). This results in `0` if the amount spent today is smaller than the budget, `1` if both are equal, and `2` otherwise. This is then used as index into a string with the correct symbols, and then the budget for this day is appended to that. Afterwards, both the amount of money left and the number of days left are decreased; the former by `c`, the money spent on this day, and the latter by `1`. It turned out that the shortest way to write this is to decrement `a` inside the division, and then add `c` to it, so the actual numerator is just `a`. # Usage Uses currying syntax. There might be a really small error in the intermediate values, because of the way JavaScript deals with arithmetic. # Test it Try all test cases here: ``` let f= a=>b=>b.map(c=>`v=^`[(c>(e=((a-=c)+c)/d--))-(c<e)+1]+e,d=b.length) let testcases = [[100, [20, 20, 30, 0, 0]], [10, [1, 2, 3, 4, 0]], [25, [20, 2, 3]], [1000, [123, 456, 400]], [500, [10, 200, 0, 0, 100, 50, 50]]]; for (let test of testcases) { console.log(`f(${test[0]})(${test[1].join(", ")}): ${f(test[0])(test[1])}`); } ``` [Answer] # [Python 3](https://docs.python.org/3/), 112 97 82 bytes ``` def f(a,b): l=len(b) for i in b:e=a/l;print('=v^'[(e>i)-(e<i)]+str(e));a-=i;l-=1 ``` [Try it online!](https://tio.run/nexus/python3#JYZBCoMwEADvvmJv7lJDTcGLcfsRsZDQDSyEKFH8flpbmBmmviVCRN8FGhtInCRjoAbiWkBBM4RR2N@T24rmA1s@X@2M8lQyKJPSctuPgkLkvGF1ybCtEYe@72C23zyu@2OvHX4uVD8 "Python 3 – TIO Nexus") * **saved 15 bytes!!!! thanks to [Luke](https://codegolf.stackexchange.com/users/63774/luke)** * saved 15 bytes: removed unwanted variable r [Answer] # [Röda](https://github.com/fergusq/roda), 65 bytes ``` f p,e{a=#e;e|{|b|x=p/a-b;[("=V^"/"")[x//x^2^0.5],p/a];p-=b;a--}_} ``` [Try it online!](https://tio.run/nexus/roda#jY5BDoIwEEXXeoofdKFJkVKtG8IBvIAbAjhgDSQIjbogAc6OrehakpnmzzSvr@MNmqmOwpUKVN/1Wd@G2iM3C6KNE54Tx3OcbdR6XpuIhO9kzMxtHGg3zAJy3SEdxjuVNbrl4gafM0Q@g2DYMxwYeIwe0WWdwtTFDnlT5/QyQT/K@oXUYkIaTPCJm0X4nH9Uwmrk0Rx8nkpOnHXZNJVvo/z0XPvvw6b333f@o8N4gtkpFHQFoWgeT4WcqkpdUaiqanRZ0@4N "Röda – TIO Nexus") A simple imperative solution. Returns a letter and a number for each day. Uses `x//x^2^0.5` to calculate the sign of `x`. Functional programming version (76 bytes): ``` f p,e{seq#e,1<>e|[(p-sum(e[:#e-_]))/_1-_,_2]|[("=v^"/"")[_//_1^2^0.5],_1+_]} ``` [Answer] ## Haskell, 75 bytes ``` m#l@(a:b)=((,)=<<("V=^"!!).fromEnum.compare a$m/sum[1|x<-l]):(m-a)#b _#_=[] ``` Usage example: `25 # [20, 2, 3]` -> `[('^',8.333333333333334),('V',2.5),('=',3.0)]`. [Try it online!](https://tio.run/nexus/haskell#@5@rnOOgkWiVpGmroaGjaWtjo6EUZhunpKioqZdWlJ/rmleaq5ecn1uQWJSqkKiSq19cmhttWFNho5sTq2mlkaubqKmcxBWvHG8bHfs/NzEzT8FWISWfS0GhoCgzr0RBRcHIVEFBWSHayEBHwUhHwTgWScrUwAAkZQiSMgASEGQIYpqCcex/AA "Haskell – TIO Nexus") How it works: ``` m#l@(a:b)= -- if the list of spendings has at least one -- element a, the result is (,) -- a pair of two times m/sum[1|x<-l] -- m / <length of the input list> (the library function 'length' is of type 'Int', so I can't use it with '/') =<< -- but the first element is modified by ("V=^"!!).fromEnum.compare a -- picking a char from the string "V=^" -- depending on the result of comparing it to a :(m-a)#b -- followed by a recursive call with all but the first -- spending and m adjusted _#_=[] -- base case: if the list of spendings is empty, the -- result is also the empty list ``` [Answer] # [Python 3](https://docs.python.org/3/), 77 bytes ``` def f(a,l): d=len(l) for i in l:e=a/d;d-=1;print('=v^'[(e>i)-(e<i)],e);a-=i ``` [Try it online!](https://tio.run/nexus/python3#JcZNCsMgEEDhfU4xu8yAUi1kEzu9SLAgOMKA2BJKrm/@4D34epYCBZOpNA@QuUrDSgOU7woK2qDOwumRQ7bsw2/V9seRt8@4oLyVLMpLKRqhkCxrLzg5ZxbvDDwPwJ0/OV1H6js "Python 3 – TIO Nexus") * using `'=v^'[(e>i)-(e<i)]` save a chunk of bytes. Thanks to Luke. * Saved some bytes by assigning `len(l)` to a variable and then decrementing it instead od holding another variable. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 140 bytes ``` class B{void f(float a,float[]l){int d=l.length;for(float i:l){float e=a/d;d--;a-=i;System.out.format("%s%f ",(e<i)?'v':(e>i)?'^':'=',e);}}} ``` [Try it online!](https://tio.run/nexus/java-openjdk#TY9Bi8IwEIXv/RWDIEmgzdYFL43dBe@ePIoLszbRQJqKGZUl5Ld3a9uDl3mP773Dm/7kMATYxkdnGzDcuA4JMB/1cHQiWk/Q1E467c90Uaa7zSVbDelkdY0fjWqKQmFRW7X/C6Rb2d1JDvUWiS@WYWlgkXO9seKbPVjF9dfL/bCK1SzXQqWU@uv919kTTJt2aH3MZhQIaZBxZTsEfE8368@HI4qYef2ELRfS8HVZytLkLzB/EFcjgc8pgfe7mtn6TZJQWcpS/w8 "Java (OpenJDK 8) – TIO Nexus") Ungolfed! ``` class B { void f(float a, float[] l) { int d = l.length; for (float i: l) { float e = a / d; d--; a -= i; System.out.format("%s%f ", (e < i) ? 'v' : (e > i) ? '^' : '=', e); } } } ``` ]
[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/60230/edit). Closed 8 years ago. [Improve this question](/posts/60230/edit) In this challenge, you will be given the source code of a **Java** program. Your task is to write a function or full program that will remove the whitespace from this program. The whitespace-removed program should work exactly the same as the original program. Your program can be in any language. In this challenge, every space, tab, and newline will be considered whitespace. ## Summary Input can be through command-line arguments, function parameters, or STDIN/equivalent. Output will be the input program without whitespace through STDOUT/equivalent, **along with an integer representing the amount of whitespace removed**. Your score will be determined by `(number of bytes) - (whitespace removed in sample program)` ## Sample Program (You can remove 104 whitespace characters from this) ``` class Condition { public static void main(String[] args) { boolean learning = true; if (learning == true) { System.out.println("Java programmer"); } else { System.out.println("What are you doing here?"); } } } ``` <http://pastebin.com/0kPdqZqZ> Whitespace-free version: `class Condition{public static void main(String[]args){boolean learning=true;if(learning==true){System.out.println("Java programmer");}else{System.out.println("What are you doing here?");}}}` ## Clarifications from Comments (see below) * The programs passed as input will be at the same whitespace complexity as the sample program. * The programs will not contain comments. ## Closing question Due to the amount of confusion involved with the question, I have decided to close the competition and accept @MartinBüttner's answer. Sorry for any misunderstanding. However, I would believe the answers to be good as a tool for java golfers, which is why I did not delete the question. [Answer] # CJam, 25 bytes - 83 removed = -58 Since Java doesn't have multiline strings nor significant indentation, we can simply remove all leading spaces. Also, since there won't be any comments, and statements will not be split across lines (as per the OP's comments), I think I should be able to remove all newlines as well. That makes for safe and short code with pretty decent savings for the test file: ``` q_,\N/{S\+e`1>e~}%_oNos,- ``` [Test it here.](http://cjam.aditsu.net/#code=q_%2C%5CN%2F%7BS%5C%2Be%601%3Ee~%7D%25_oNos%2C-&input=class%20Condition%20%7B%0A%20%20%20%20public%20static%20void%20main(String%5B%5D%20args)%20%7B%0A%20%20%20%20%20%20%20%20boolean%20learning%20%3D%20true%3B%0A%0A%20%20%20%20%20%20%20%20if%20(learning%20%3D%3D%20true)%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20System.out.println(%22Java%20programmer%22)%3B%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20else%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20System.out.println(%22What%20are%20you%20doing%20here%3F%22)%3B%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%7D%0A%7D) For the test case it yields ``` class Condition {public static void main(String[] args) {boolean learning = true;if (learning == true) {System.out.println("Java programmer");}else {System.out.println("What are you doing here?");}}} 83 ``` [Answer] # JavaScript (ES6), 72 bytes - 92 removed = -20 (partially invalid?) ``` x=>(z=x.replace(/\s*[{}()=;]\s*/g,y=>y.trim()))+` `+(x.length-z.length) ``` The output: ``` class Condition{public static void main(String[] args){boolean learning=true;if(learning==true){System.out.println("Java programmer");}else{System.out.println("What are you doing here?");}} ``` I believe the one space I could still remove is the one in `(String[] args)`, but this would not be worth it. This is pretty much the lowest score JS can get (for this specific case, anyway). [Answer] # Ruby, 63 bytes - 104 removed = -41 edit: 104 *bytes* that is. ``` $><<j=(i=$<.read).gsub(/(?<=\W)\s|\s(?=\W)/,"") p i.size-j.size ``` Removes all newlines, so the printed number at the end comes on the same line too: ``` $ curl -s http://pastebin.com/raw.php?i=0kPdqZqZ | ruby remove_whitespace.rb class Condition{public static void main(String[]args){boolean learning=true;if(learning==true){System.out.println("Java programmer");}else{System.out.println("What are you doing here?");}}}104 ``` [Answer] # Python, 92 bytes - 88 removed = 4 ``` import re,sys p=sys.stdin.read() s=re.sub('\s+(=|{|}|(|))\s+',r'\1',p) print len(p)-len(s),s ``` [Test it here](http://ideone.com/7FBIUe) Once again, regex to the rescue. There's a strange discrepancy between ideone and my python install - I'm getting 90 chars removed. ![local python](https://i.stack.imgur.com/1DXG8.png) jprog.py source: ``` #!/usr/bin/env python print """class Condition { public static void main(String[] args) { boolean learning = true; if (learning == true) { System.out.println("Java programmer"); } else { System.out.println("What are you doing here?"); } } }""" ``` [Answer] # Java 8 : 79 Bytes ``` s->{System.out.print(s.replaceAll("(\\s+|\\n)?(\\{|\\}|=+|;)(\\s+|\\n)", "$2"));} ``` Regular expression with grouping can remove the extra white spaces between curly braces and equals sign used in assignment or equality check. Regular expression is something like, `(\s+|\n)?({|}|=+|;)(\s+|\n)` It will provide following output, which is valid Java program. ``` class Condition{public static void main(String[] args){boolean learning=true;if (learning==true){System.out.println("Java programmer");}else{System.out.println("What are you doing here?");}}} ``` ]
[Question] [ I need to reduce the length of this code in Python 3 as much as possible (even if it will be less readable): ``` a,b,x,y=[int(i) for i in input().split()] while 1: r='' if y<b:r='S';y+=1 if y>b:r='N';y-=1 if x<a:r+='E';x+=1 if x>a:r+='W';x-=1 print(r) ``` It's a map: you are on (x,y) and you need to go to (a,b). S for South, N for North, NE for North East and so on. After each turn I must tell where to go using print. **Update:** This is what I've got now, but is there any way to shorten it further? ``` a,b,x,y=map(int,input().split()) while 1:c,d=(y>b)-(y<b),(x>a)-(x<a);print((' NS'[c]+' WE'[d]).strip());y-=c;x-=d ``` [Answer] ## Python 3, 107 ``` a,b,x,y=map(int,input().split()) A=abs(a-x);B=abs(b-y) while 1:print('SN'[b>y][:B]+'WE'[a>x][:A]);A-=1;B-=1 ``` A different strategy to generate the directions, tracking each coordinate's absolute displacement to the goal rather than the actual location. For the horizontal direction, finds the absolute displacement `A=abs(a-x)` and direction character `'WE'[a>x]`. Simulates going towards the goal by decrementing `A` and printing the direction character as long as we haven't already reached the goal coordinate (`A>0`). Does the same for vertical. [Answer] Theres a shorter way to `strip()`: ``` (' NS'[c]+' WE'[d]).strip() c%2*' NS'[c]+d%2*' WE'[d] ``` saves two characters. [Answer] There's a shorter way to take the initial input: ``` a,b,x,y=[int(i) for i in input().split()] a,b,x,y=map(int,input().split()) ``` Thanks to @DenDenDo, for pointing out that you can do tuple unpacking assignment on map objects. [Answer] In Python 2, you could use `cmp`, which returns -1, 0, or 1. Use this result to get the correct letter. ``` while 1:c=cmp(y,b);d=cmp(x,a);print((' SN'[c]+' WE'[d]).strip());y-=c;x-=d ``` Martin Büttner suggested saving the `cmp` results to variables, and isaacg noted that now the whole loop can be on one line. Unfortunately, Python 3 doesn't have `cmp`, but using `(y>b)-(y<b)` for `cmp(y,b)` is still shorter than the original. ]
[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/40816/edit). Closed 7 years ago. [Improve this question](/posts/40816/edit) **Situation**: 1. A turtle starts at (0, 0) on a cartesian graph. 2. We have a non-empty zero-indexed "moves" list that contains numbers. 3. Each number represents the distance moved. 4. The first number is the distance north, the second is the distance east, the third is the distance south, the fourth is the distance west, and repeats like this forever. Therefore the directions cycle every four moves. **Goal:** Find an algorithm that gives the move number that makes the turtle cross a point that it has already visited before. The move number is the *index of the "moves" list*. This algorithm should preferably be O(n). **Example:** If given this move list: `[1, 3, 2, 5, 4, 4, 6, 3, 2]` The move number answer is then 6. (It's the 7th move). Draw it on a graph, the turtle will go: (0,0) -> (0,1) -> (3,1) -> (3,-1) -> (-2,-1) -> (-2,3) -> (2,3) -> (2,-3) At this 6 move number (7th move) it will meet (2,1) which is a point that the turtle has already crossed. **Example Implementation** Here was my try in PHP (I think it's kind of like O(n\*(m+m)) where m is the average size of the distance): ``` /** * Logo Turtle Challenge * This solution is somewhat space inefficient, and could become time inefficient if the distance range for a particular move is huge! * There is probably a solution that allows you to persist only the corner coordinates and then using line equations to figure out if they intersect. * The space inefficiency could be partially solved with a lazy range generator. * Could be further micro-optimised by only checking the coordinates on the fourth[3] movement. */ function logo_turtle($movements) { $coordinates = [0 => [0 => true]]; $current_coordinate = [ 'x' => 0, 'y' => 0 ]; $directions = ['n', 'e', 's', 'w']; foreach($movements as $move => $distance){ // cycle through the directions $current_direction = array_shift($directions); array_push($directions, $current_direction); // if the distance is less than 1, then skip it, but we still cycle the direction! if ($distance < 1) { continue; } // clean slate $coordinates_to_check = []; // for each direction, acquire a list of coordinates derived from its traverse // these coordinates will be used to check if turtle crosses its own previous path switch($current_direction){ case 'n': $x_end = $current_coordinate['x']; $y_end = $current_coordinate['y'] + $distance; $start = $current_coordinate['y'] + 1; foreach(range($start, $y_end) as $value){ $coordinates_to_check[] = [ 'x' => $current_coordinate['x'], 'y' => $value]; } break; case 'e': $x_end = $current_coordinate['x'] + $distance; $y_end = $current_coordinate['y']; $start = $current_coordinate['x'] + 1; foreach(range($start, $x_end) as $value){ $coordinates_to_check[] = [ 'x' => $value, 'y' => $current_coordinate['y']]; } break; case 's': $x_end = $current_coordinate['x']; $y_end = $current_coordinate['y'] - $distance; $start = $current_coordinate['y'] - 1; foreach(range($start, $y_end) as $value){ $coordinates_to_check[] = [ 'x' => $current_coordinate['x'], 'y' => $value]; } break; case 'w': $x_end = $current_coordinate['x'] - $distance; $y_end = $current_coordinate['y']; $start = $current_coordinate['x'] - 1; foreach(range($start, $x_end) as $value){ $coordinates_to_check[] = [ 'x' => $value, 'y' => $current_coordinate['y']]; } break; } // if the traversal meets one of the existing coordinates, then the current move is an interception foreach($coordinates_to_check as $xy){ if( isset( $coordinates[ $xy['x'] ][ $xy['y'] ] ) ){ return $move; } // add the point to the list of coordinates that has been traversed $coordinates[$xy['x']][$xy['y']] = true; } // update the current coordinate for the next iteration $current_coordinate = [ 'x' => $x_end, 'y' => $y_end ]; } return -1; } $moves = [1, 3, 2, 5, 4, 4, 6, 3, 2]; $turtle_move = logo_turtle($moves); // returns 6 ``` **Criteria:** 1. Feel free to write it in any language you want. 2. Winning algorithm is the first one that is published with an O(n) implementation. 3. With regards to algorithms with the same time complexity class, whichever code has the least amount of characters win. 4. Time limit is the best answer by 30th November 2014. [Answer] # C, O(n), 65 95 102 bytes After I made at least one additional test case, some more code naturally needed to be added. Thanks to [Serge Mosin](https://codegolf.stackexchange.com/users/42032/serge-mosin) for finding another bug. ``` k(int*m){int*i=m;for(;2[i]>*i++;);for(*i-=i[~1]*(1[i]+(i-m>2)*i[~2]>=i[-1]);2[i]<*i++;);return 1+i-m;} ``` **Test cases**: ``` int a[] = {1, 3, 2, 5, 4, 4, 6, 3, 2}; // -> 6 int b[] = {4, 4, 5, 7, 8, 6, 5}; // -> 6 int c[] = {1, 1, 2, 1, 1}; // -> 4 ``` Behavior is unspecified if there is a 0 in the array, since OP didn't specify whether that counts as the path crossing itself. Also, it is assumed that the path does cross at some point. It might be undefined behavior to have `2[i] > *i++` but in code golf, that's like (negative) bonus points. The first loop processes the part of the path that forms an outward spiral, which continues as long as each segment is longer than the previous parallel segment. The second loop traverses an inward spiral, in which each segment is shorter than the previous segment. At the beginning of the second spiral, there needs to be an adjustment to detect a possible collision with the previous stuff. [Answer] Here is a solution in JavaScript ``` function turtle(A) { for (i=3;i<A.length;i++) { if (A[i-1] <= A[i-3] && (A[i] >= A[i-2] || A[i-1] >= A[i-3]-(A[i-5] || 0) && A[i] >= A[i-2]-A[i-4] && A[i-2] >= A[i-4])) return i } return -1 } ``` Test Cases ``` var a = [1, 3, 2, 5, 4, 4, 6, 3, 2] // -> 6 var b = [4, 4, 5, 7, 8, 6, 5] // -> 6 var c = [1, 1, 2, 1, 1] // -> 4 var d = [1, 1, 2, 2, 4, 2, 1, 1, 2, 5, 10] // -> 8 var e = [1, 1, 1, 1] // -> 3 var f = [1, 1, 5, 3, 3, 2, 2, 1, 1, 3] // -> 9 var g = [1, 2, 2, 1, 1] // -> -1 ``` Basically the turtle can only cross if the line from one time ago is less than or equal to the line from three times ago. Then check two cases, one where the current line is greater than or equal to the line from two times ago, and one where the current line crosses the line from five times ago. The question doesn't specify what happens if the turtle moves 0. If that would be considered crossing his own path it would be easy to check for. If not, it would complicate things a bit. [Answer] I've made this teste just yesterday. This is my Objective-C version. It not meant to be the perfect, the latest and blah blah blah that Cordiality cries for, but a enough and readable version: Its check the segment on vertical or horizontal to check if any previous drawn will be crossed. <https://gist.github.com/dbonates/818d6cea288a81cf888f> Hope it helps, if anyone wanna improve it feel free :) Here goes the code as asked: ``` #import <Foundation/Foundation.h> // Determine the move in which a LOGO turtle crosses a point that it has already visited BOOL isBetween(int valueToTest, int limitOne, int limitTwo) { if (limitOne > limitTwo) { return (limitTwo <= valueToTest && valueToTest <= limitOne); } else { return (limitOne <= valueToTest && valueToTest <= limitTwo); } } int stepColistionCheck(NSMutableArray *stepsArray) { // NSLog(@"stepsArr: [%@]", [stepsArray componentsJoinedByString:@","] ); int cx = 0; int cy = 0; int len = (int)[stepsArray count]; // array with x and y position on grid NSMutableArray *deltaArray = [NSMutableArray array]; for (int i=0; i<len; i++) { int direction = i%4; switch (direction) { case 0: // going NORTH cy -= [stepsArray[i] integerValue]; [deltaArray addObject:@(cy)]; break; case 1: // going EAST cx += [stepsArray[i] integerValue]; [deltaArray addObject:@(cx)]; break; case 2: //going SOUTH cy += [stepsArray[i] integerValue]; [deltaArray addObject:@(cy)]; break; case 3: //going WEST cx -= [stepsArray[i] integerValue]; [deltaArray addObject:@(cx)]; break; default: break; } } // array de deltas produzidos // NSLog(@"deltaArray: [%@]\n\n", [deltaArray componentsJoinedByString:@","] ); // testing starting from third (the first that could colide, with the first vertical in this case) for (int i=3; i< len; i++) { //check if will test horizontal colliding or vertical // 0, stands for vertical, 1 for horizontal int orientation = i%2; if (orientation == 0) { //vertical // the x value for this vertical segment is equal do the x from previous one int segmentX = [deltaArray[i-1] intValue]; // NSLog(@"- testing vertical segment at index: %d, myX = %d:", i, segmentX); //loop from first horizontal to here // j is the horizontal segment int previousValue; for (int j=1; j < i; j+=2) { // first test, cant be adjacents if (j != (i-1) && j != (i+1)) { if (j < 2) { previousValue = 0; } else { previousValue = [deltaArray[j-2] intValue]; } // trying to find if my x (segmentX) is between the values: previousValue e [deltaArray[j] intValue] if (isBetween(segmentX, [deltaArray[j] intValue], previousValue)) { // NSLog(@"\tok, found candidate horizontal contains myX at index %d", j); // that horizontal segment contains my x, // now I should check for y interpolation // the y for current horizontal candidate for colision, // is the y value before this index on delta array int canditateY; canditateY = [deltaArray[j-1] intValue]; // the Y of this horizontal segment found (canditateY), must me in my y range, between [deltaArray[i] intValue] and [deltaArray[ i-2] intValue] if (isBetween(canditateY, [deltaArray[i] intValue], [deltaArray[ i-2] intValue])) { // the candidate Y has been found on current range of y for this segment // NSLog(@"\t\t***** FOUND SEGMENT THAT CROSS at index step %d", (i+1)); return (i+1); } } } } } else if (orientation == 1) { //horizontal int segmentY = [deltaArray[i-1] intValue]; // NSLog(@"- testing horizontal in index: %d, myY = %d:", i, segmentY); //loop from first vertical to here // j is the vertical segment int previousValue; // test which includes my x for (int j=0; j < i; j+=2) { if (j<1) { previousValue = 0; } else { previousValue = [deltaArray[j-2] intValue]; } // first test, cant be adjacents if (j != (i-1) && j != (i+1)) { if (isBetween(segmentY, [deltaArray[j] intValue], previousValue)) { // NSLog(@"\tcandidate vertical contains myY at index %d", j); // that vertical segment contains my y, // now I should check for x interpolation // the x for current vertical candidate for colision, // is the x value before this index on delta array int canditateX; if (j<1) { canditateX = 0; } else { canditateX = [deltaArray[j-1] intValue]; } if (isBetween(canditateX, [deltaArray[i] intValue], [deltaArray[ i-2] intValue])) { // the candidate X has been found on current range of x for this segment // NSLog(@"\t\t***** FOUND SEGMENT THAT CROSS at index step %d", (i+1)); return (i+1); } } } } } // NSLog(@"- no colision with this segment"); } return -1; } int main(int argc, char *argv[]) { @autoreleasepool { NSMutableArray *arr = [NSMutableArray arrayWithObjects: @7, @6, @9, @5, @8, @4, @7, @3, @5, @2, @4, @1, @6, nil]; //return 13 // collide going to north printf("will collide on step %d", stepColistionCheck(arr)); } } ``` [Answer] # EDIT: The bugs were found in this solution so don't use it. Refer to [this](https://codegolf.stackexchange.com/questions/40816/determine-the-move-in-which-a-logo-turtle-crosses-a-point-that-it-has-already-vi/40856#40856) one instead. Here is rich list of different test cases (including the one showing bugs in my solution). ``` int a[] = {1, 1, 1, 2}; // 3 int b[] = {1, 1, 2, 1, 1}; //4 int c[] = {1, 3, 2, 5, 4, 4, 6, 3, 2}; // 6 int d[] = {4, 4, 5, 7, 8, 6, 5}; // 6 int e[] = {1, 1, 2, 2, 4, 2, 1, 1, 2, 5, 10}; // 8 int f[] = {1, 1, 5, 3, 3, 2, 2, 1, 1, 3}; // 9 <-- this is the one I failed on ``` --- # C, O(n), 82 bytes. This is a fix for [feersum](https://codegolf.stackexchange.com/users/30688/feersum)'s solution. I cannot write comments so I post it here as an answer: ``` k(int*m){int*i=m;for(;2[i]>*i++;);for(*i-=(i-m>2)*i[~1];2[i]<*i++;);return 1+i-m;} ``` Here is the case where his solution fails: ``` int a[] = {1, 1, 2, 2, 4, 2, 1, 1, 2, 5, 10}; ``` His function returns `6`, though the correct answer is `8`. All other notes about [his](https://codegolf.stackexchange.com/questions/40816/determine-the-move-in-which-a-logo-turtle-crosses-a-point-that-it-has-already-vi/40856#40856) solution are held here as well. [Answer] Here is my approach done in Ruby, it uses Cramer's Rule to deduce if 2 segments cross each other. Since we are dealing only with horizontal and vertical lines maybe its an overkill but it passed all the test cases. <https://gist.github.com/Janther/089b2a4338760c057cbf> ``` def intersects?(p0, p1, p2, p3) s1_x = p1[0] - p0[0] s1_y = p1[1] - p0[1] s2_x = p3[0] - p2[0] s2_y = p3[1] - p2[1] denom = s1_x * s2_y - s2_x * s1_y # if denom == 0 lines are parallel # TODO: aditional check if they overlap return false if (denom == 0) denomPositive = denom > 0 s3_x = p0[0] - p2[0] s3_y = p0[1] - p2[1] s_numer = s1_x * s3_y - s1_y * s3_x # s must be positive for posible colition # s = s_numer / demom return false if (s_numer < 0) == denomPositive t_numer = s2_x * s3_y - s2_y * s3_x # t must be positive for posible colition # t = t_numer / demom return false if (t_numer < 0) == denomPositive # both t and s must be <= 1 so |s_numer| <= |denom| AND |t_numer| <= |denom| (s_numer <= denom) == denomPositive && (t_numer <= denom) == denomPositive end def solution(a) path = [[0, 0]] directions = [[0, 1], [1, 0], [0, -1], [-1, 0]] a.each.with_index do |steps, solution_index| position = path.last direction = directions[solution_index % 4] path << [position[0] + steps * direction[0], position[1] + steps * direction[1]] next if path.size < 4 end_segment_1 = path[path.size - 1] # Border case when the path ends at the beginning return solution_index + 1 if end_segment_1 == [0, 0] start_segment_1 = path[path.size - 2] # First check is 4 moves ago start_segment_0 = path[path.size - 5] end_segment_0 = path[path.size - 4] if intersects?(start_segment_0, end_segment_0, start_segment_1, end_segment_1) return solution_index + 1 end next if path.size <= 6 # Second check is 6 moves ago start_segment_0 = path[path.size - 7] end_segment_0 = path[path.size - 6] if intersects?(start_segment_0, end_segment_0, start_segment_1, end_segment_1) return solution_index + 1 end end 0 end solution [1, 3, 2, 5, 4, 4, 6, 3, 2] #=> 7 solution [1, 1, 1, 2] #=> 4 solution [1, 1, 2, 1, 1] #=> 5 solution [4, 4, 5, 7, 8, 6, 5] #=> 7 solution [1, 1, 2, 2, 4, 2, 1, 1, 2, 5, 10] #=> 9 solution [1, 1, 5, 3, 3, 2, 2, 1, 1, 3] #=> 10 ``` ## Explanation of intersects? We have 2 segments represented by p0, p1 and p2, p3. Let's call the vector that joins p0 and p1 "s1" and the vector that joins p2 and p3 "s2". ``` s1 = p1 - p0 s2 = p3 - p2 ``` Then we can represent the 2 lines by using the starting point and the vector like this: ``` L1 = p0 + t * s1 L2 = p2 + s * s2 ``` If the two lines were to cross each other we should find a single value for t and s that fulfils the following equation ``` p0 + t * s1 = p2 + s * s2 ``` If we cross multiply each side with s1 we get ``` (p0 + t * s1) x s1 = (p2 + s * s2) x s1 ``` Since s1 x s1 = 0 ``` (p0 - p2) x s1 = s * (s2 x s1) ``` And finally ``` s = (p0 - p2) x s1 / (s2 x s1) ``` Let's follow the same steps to solve for t ``` (p0 + t * s1) x s2 = (p2 + s * s2) x s2 t * (s1 x s2) = (p2 - p0) x s2 t = (p2 - p0) x s2 / (s1 x s2) ``` Having s1 x s2 = - (s2 x s1) ``` t = (p0 - p2) x s2 / (s2 x s1) ``` We have 2 equations ``` s = (p0 - p2) x s1 / (s2 x s1) t = (p0 - p2) x s2 / (s2 x s1) ``` Since we don't want extra calculations let's have 2 more variables ``` denom = s2 x s1 s3 = p0 - p2 ``` If denom is 0 segments are parallel and extra analysis should be made if they overlap. If 0 ≤ t ≤ 1 AND 0 ≤ s ≤ 1 the lines cross inside the given segments, otherwise they cross in some other point. Since floating point division is more CPU demanding than comparing 2 integers the code was modified to avoid dividing but still having the logic of 0 ≤ t ≤ 1 AND 0 ≤ s ≤ 1 and I added comments on the code to explain the logic. Here you can find the original analysis which I used. <https://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect> [Answer] Just adding my php solution, runs in **O(n)**: ``` $arr = [1, 3, 2, 5, 4, 4, 6, 3, 2]; $sol = solution($arr); var_dump($sol); function solution($arr) { $state = 0; $dmax = 0; $arrCount = count($arr); for($i = 2; $i < $arrCount; $i++) { switch ($state) { case 0: if($arr[$i] <= $arr[$i-2]) { $dmax = ($i >= 4 && $arr[$i-4] >= $arr[$i-2]) ? $arr[$i-1] - $arr[$i-3] : $arr[$i-1]; $state = 1; } break; case 1: if ($arr[$i] >= $dmax) { return $i+1; } else { $dmax = $arr[$i-1]; } break; } } return -1; } ``` ]
[Question] [ This challenge asks you to draw the Eiffel Tower in 3D using different ASCII characters to represent the different sides, similar to this cube: ``` @@@ @@@@@@@@@ @@@@@@@@@@@@@@@ x@@@@@@@@@@@@&& xxx@@@@@@@@&&&& xxxxx@@@&&&&&&& xxxxxx&&&&&&&&& xxxxx&&&&&&& xxx&&&& x&& ``` Here is a picture of the Eiffel Tower for you to base your art on: ![enter image description here](https://i.stack.imgur.com/1JBni.gif) Your program will input a rotational angle of the side view, then print the Tower as if you were looking at it from that angle. The up/down angle does not need to be accounted for. Score will be calculated as 1.25\*votes - 0.25\*length as a [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'"). Highest score wins. [Answer] # PHP, 364 \* 0.25 = 91 Accepts a viewing angle as a query string parameter of the form `?a=0`, `?a=45`, `?a=90`, etc. ``` <pre><?php $a=45*floor(.5+intval(@$_GET['a'])/45); $e=array(array(".","|","==","X|","X|","X/","==|","^||","-./","__//","=====","^^-. /"," |__|"), array(".","|","==","X|","X|","X/","|=|","|^|","|./"," ///",":====",":|-. /","_| |_|")); echo "Angle: {$a}°\n\n"; foreach($e[$a&1] as $s){$p=str_pad($s,7);echo strrev($p).substr(strtr($p,'/','\\'),1)."\n";} ?> </pre> ``` **Examples:** **a=135** ``` Angle: 135° . | === |X| |X| /X\ |=|=| |^|^| /.|.\ /// \\\ ====:==== / .-|:|-. \ |_| |_| |_| ``` **a=200 (rounded to nearest increment = 180°)** ``` Angle: 180° . | === |X| |X| /X\ |===| ||^|| /.-.\ //___\\ ========= / .-^^^-. \ |__| |__| ``` (Yes I know, the angular resolution isn't brilliant. I'll improve on that if I have time.) [Answer] BBC BASIC, 66 chars Emulator at bbcbasic.co.uk ``` A=PI/6FORJ=0TO83PRINTTAB(9+EXP(J/40)*SIN(A+J*PI/2),J/4);J MOD4:NEXT ``` With white space for clarity: ``` A=PI/6 FOR J=0 TO 83 PRINT TAB(9+EXP(J/40)*SIN(A+J*PI/2),J/4);J MOD4 NEXT ``` Input is hard coded in radians. Taking user input would add one character, but user would have to input in radians. Removing the MOD4 from the end would still produce a recognisable tower, but might violate the rule regarding character per side. Basically plots a string of zeros at `exp(J/40)*sin(A)` vs `J/4.` Additional values of the sin are added for the remaining three legs. ![enter image description here](https://i.stack.imgur.com/VTMs9.png) [Answer] # C# - 64 bytes ``` namespace System{class m{static void h(){Console.Write(".");}}} ``` Prints the Eiffel Tower viewed from 500 **26.5** kilometers away. Takes the rotational angle as an argument. Example usage: ``` eiffel.exe 90 ``` # EDIT I've made an approximation, and it should be about 26.5 kilometers away. Let's consider the image below, taken from OP and edited to add a "." using the font Monospace 12 without anti-aliasing. ![enter image description here](https://i.stack.imgur.com/dO5nw.gif) The "." is 2 pixels long and 1 pixels wide whereas the tower is 400 pixels long and 663 pixels wide(approximately). Let's assume the tower is viewed from 100 meters away. If we want to make it look like a 2x1 box, we would need to make it (again, approximately) 265.5 times smaller(200 times smaller for the height and 531 times smaller for the width). If we multiply 265.5 with 100 meters, we get 26550 meters, which is 26.5 kilometers. ]
[Question] [ Write a program to convert Polish prefix notation to infix notation, then change it to an RPN-to-infix converter in the shortest number of chars. Your score is 100 minus the number of characters changed, added and deleted. * Don't write one PPN and one RPN function, then do something like: "*I changed `rpn(raw_input())` to `ppn(raw_input())`"* * No ingenious variations of the above rule such as ``` def f(s, rpn = False): if rpn: #rpn logic here else: #ppn logic here ``` * In short, your program must *only* implement one kind of logic, not both. * It must not be possible to *only* delete characters from the original program and so obtain a program which converts RPN to infix. * Try not to use inbuilt libraries. * Accept input from STDIN or from a file. * Note that program length itself does not matter. * Have fun. [Answer] # Python - 100! I'm pretty sure I've met all the criteria. ~~I don't think its possible to make it more identical, without just having a big ol' if block, which *would* violate the criteria.~~ Using `cmp()`, and what @PeterTaylor pointed out you can determine the direction you need to go. Rather than use an if/then which would violate the spirit of the challenge, this get the position of the first number and operator and compares those. While the list comprehensions use an if this is just to safely filter the indices and doesn't direct help determine if we are doing forward or reverse polish notation, but this does bend the rules a bit. ### Rule-bending program: *Both prefix and reverse Polish notation* ``` s = raw_input().strip() # Get input ops = "*-+/^" # A string of operators num="0123456789" # A string of numbers p_num= min([s.index(n) for n in num if n in s]) # Find the first number p_op = min([s.index(o) for o in ops if o in s]) # Find the first operator # We use the above 2 lines to determine what # direction we are going on line '2' below # Just like the original below s=s.split() # 1. Split the input d = cmp(p_op,p_num) # 2. Set the direction... depending on what comes first! # If the first number is before the operator, go forwards # If the first number is after the operator, go backwards def f(i): # 3. Define our recursive function if s[i] in operators: # 4. If its an operator... a = f(i+d) # 5. Recursively get the first argument b = f(i+d) # 6. By the time the above is resolved the array is modified # So we can use the same offset c = [a,b,a] # 7. Mash these in a padded array so the trick below works inf = c[d-1]+s.pop(i)+c[d] # 8. Lets put these in order... BASED ON d!! # And remove the operator from the array return "("+inf+")" # 9. Return the infix version of this operator return s.pop(i) # 10. Just a number?, pop and return. print f([0,-1,42][d-1]) # 11. Call the recursive start case from the head of the array # i.e element 0, or just 0. # Print the final infix ``` --- If the above is too rule bendy, here is the code I had before that **scored 99**. ### Original program: *Polish prefix notation* ``` s = raw_input().split(" ") # 1. Get input d = 1 # 2. Set the direction to forwards # If the first number is before the operator, go forwards # If the first number is after the operator, go backwards def f(i): # 3. Define our recursive function if s[i] in operators: # 4. If its an operator... a = f(i+d) # 5. Recursively get the first argument b = f(i+d) # 6. By the time the above is resolved the array is modified # So we can use the same offset c = [a,b,a] # 7. Mash these in a padded array so the trick below works inf = c[d-1]+s.pop(i)+c[d] # 8. Lets put these in order... BASED ON d!! # And remove the operator from the array return "("+inf+")" # 9. Return the infix version of this operator return s.pop(i) # 10. Just a number?, pop and return. print f([0,-1,42][d-1]) # 11. Call the recursive start case from the head of the array # i.e element 0, or just 0. # Print the final infix ``` ### Modified to produce: *Reverse polish notation* ``` s = raw_input().split(" ") d = -1 # 2. Set the direction to backwards def f(i): if s[i] in "*-+/^": a = f(i+d) b = f(i+d) c = [a,b,a] inf = c[d-1]+s.pop(i)+c[d] return "("+inf+")" return s.pop(i) print f([0,-1,42][d-1]) #11. No change, but this pulls the second last (-2) element # Hence, why we bump it to 3 elements long. ``` Differences (not including the comments): * **Line 2:** 1 char, added `-` to change from +1 to -1 For a total of 1 character changed, which in Polish notation, gives ``` - 100 1 = 99 ``` ]
[Question] [ You are given two functions \$g(x)\$ and \$h(x)\$, each of which takes an integer \$x\$ and returns the number \$ax + b\$ (where \$a\$ and \$b\$ are integers defined in the function). Your task is to write a function \$f(g, h)\$ that takes these two functions, and returns a function \$k(x) = g(h(x))\$, but where the procedure of \$k(x)\$ is also simply of the form \$ax + b\$. For example, given \$g(x) = 2x + 3\$ and \$h(x) = 3x + 4\$, you would need to return \$k(x) = 6x + 11\$, and not \$k(x) = 2(3x + 4) + 3\$. [Answer] ### GolfScript, 41 40 23 19 characters ``` {2,0+%/-{@*+}++}:k; ``` Thanks to Peter Taylor for pointing out this solution. Accepts two function bodies as arguments. The following examples show how to use function `k`: ``` # As function {2*3+} {3*4+} k # => {11 6 @*+} # Apply to value 5 {2*3+} {3*4+} k ~ # => 41 ``` If one wants to retain the original output format, the following 22 character solution is possible: ``` {2,0+%/-{*}+\+{+}+}:k; {2*3+} {3*4+} k # => {6 * 11 +} ``` Explanation of the code: ``` { # on stack are functions g h 2, # build array [0 1] -> g h [0 1] 0+ # append 0 -> g h [0 1 0] % # apply function h to each element -> g [h(0) h(1) h(0)] / # apply function g to each element # and break up the array -> g(h(0)) g(h(1)) g(h(0)) - # subtract last two -> g(h(0)) g(h(1))-g(h(0)) {@*+}++ # append function body to these values }:k; # save function to variable k ``` [Answer] # Mathematica 15 **Define g, h as pure functions** `g` and `h` are defined as pure functions (awaiting a value or independent variable to be assigned) ``` g = 2 # + 3 &; h = 3 # + 4 &; g[x] h[x] ``` > > 3 + 2 x > > 4 + 3 x > > > --- **Method #1: Compose `g` of `h` directly** (15 chars) ``` g@h@x//Simplify ``` > > 11 + 6 x > > > Or, alternatively: (17 chars) ``` g[h[x]]//Simplify ``` --- **Method #2: Define `f`** (25 chars= 13 + 10 chars for Simplify) ``` f=Composition ``` ![composition](https://i.stack.imgur.com/RaS2O.png) ``` f[g, h][x] f[g, h][x] // Simplify Composition[g, h][x]//Simplify f[g, h][1] Table[f[g, h][x], {x, 1, 13}] ``` > > 3 + 2 (4 + 3 x) > > 11 + 6 x > > 11 + 6 x > > 17 > > {17, 23, 29, 35, 41, 47, 53, 59, 65, 71, 77, 83, 89} > > > [Answer] ### Haskell, 31 ``` (f%g)x=f(g 0)+x*(f(g 1)-f(g 0)) ``` Version in which the function body contains only variables (equivalent at run time, but closer to the question's form), 38 characters: ``` (f%g)x=a*x+b where h=f.g;b=h 0;a=h 1-b ``` Note that in both cases, since Haskell uses curried functions, there is no explicit construction of the composed function as it is implicit in `%` being defined with three arguments: function f, function g, value x. Example use: ``` > ((\x -> 2*x + 3)%(\x -> 3*x + 4)) 0 11 > ((\x -> 2*x + 3)%(\x -> 3*x + 4)) 4 35 ``` Ungolfed second form: ``` (f % g) x = a * x + b -- equivalent: (f % g) = \x -> a * x + b where h = f . g -- use built in function composition to bootstrap b = h 0 -- constant term of composed function a = h 1 - h 0 -- linear term of composed function ``` [Answer] ## Lua, 87 ``` function f(g, h)local a,b=g(h(1))-g(h(0)),g(h(0))return function(x)return a*x+b end end ``` [Answer] ## vba, 89 ``` Function f(g,h,x) f=Evaluate(Replace(g,"x","*("&Replace(h,"x","*"&x)&")")) End Function ``` usage/result > > ?f("2x+3","3x+4",1) > > 17 > > > [Answer] # Ruby >=1.9, 55 ``` f=->g,h{a=(g[1]-g[0])*(h[1]-h[0]);b=g[h[0]];->x{a*x+b}} ``` Less golfed: ``` def c(f,g) f_a=f[1]-f[0] g_a=g[1]-g[0] a=f_a*g_a b=f[g[0]] ->x{a*x+b} end ``` [Answer] ## SML (60 chars) ``` fun f g h=let val c=g(h 0)val m=g(h 1)-c in fn x=>m*x+c end; ``` Ungolfed: ``` fun f g h = let val c = g (h 0) val m = g (h 1) - c in fn x => m*x + c end; ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 13 bytes ``` vØ.v@µI,Ḣż⁾×+ ``` [Try it online!](https://tio.run/##ATAAz/9qZWxsef//dsOYLnZAwrVJLOG4osW84oG@w5cr/8On//8iM8OXNCsi/yIyw5czKyI "Jelly – Try It Online") I think I understand what the question is asking for, but it really isn't clear exactly *how* the program is supposed to return \$a\$ and \$b\$, and it seems as though (given the [functional-programming](/questions/tagged/functional-programming "show questions tagged 'functional-programming'") tag) that this is an unobservable requirement) ~~11 bytes sacrificed to clumsy I/O formats.~~ -9 bytes thanks to [Howard](https://codegolf.stackexchange.com/users/1490/howard)'s [method](https://codegolf.stackexchange.com/a/11117/66833) This takes \$g\$ and \$h\$ in Jelly's most natural form for non-black-box functions, as a string representing a Jelly link. As \$g(x)=ax+b\$ (and similar for \$h\$), this is equivalent to `a×b+`. We also return \$k\$ in the form `a×b+`. If this can instead take input and output as two lists `[a, b]` representing \$g\$ and \$h\$, we can reduce this to [8 bytes](https://tio.run/##AScA2P9qZWxsef//w5figqzhuKIrMsKm4bmqe////1syLCAzXf9bMywgNF0). ## How it works ``` vØ.v@µI,Ḣż⁾×+ - Main link. Takes h ("c×d+") on the left and g ("a×b+") on the right Ø. - [0, 1] v - Run h over each; [h(0), h(1)] v@ - Run g over each; [g(h(0)), g(h(1))] µ - New link. Call this pair l and use it as the argument I - Differences; g(h(0)) - g(h(1)) Ḣ - Head; g(h(0)) , - Pair; [g(h(0)) - g(h(1)), g(h(0))] ⁾×+ - Yield "×+" ż - Zip together; [g(h(0)) - g(h(1)), "×", g(h(0)), "+"] Implicitly smash together and print ``` [Answer] # PHP 72 Apparently I completely missed the point of this code-golf. I'm STILL not sure if I understand it correctly. Is no output required? Can I assume the methods of g and h? Here's a new version based off the old one: ``` <?=$f=function($g,$h,$x){return$k=($g[0]*$h[0]*$x)+($g[0]*$h[1])+$g[1];} ``` If this is still wrong, I give up. --- # PHP 176 The requirements are kind of confusing, but here's what I think you meant: ``` <?=f($argv);function f($a){$x=$a[3];$g=explode("x",$a[1]);$h=explode("x",$a[2]);return$k=($g[0]*$h[0])."*$x+".(($g[0]*$h[1])+$g[1])."=".(($g[0]*$h[0]*$x)+($g[0]*$h[1])+$g[1]);} ``` Usage: `php f.php 2x+3 3x+4 5` Output: `6*5+11=41` Another Example Usage: `php f.php 4x-7 3x+4 2` Output: `12*2+9=33` # Method As you described, we can't simply output the answer with `g(h(x))`, we had to create function `f(g,h)` which determines what both the functions would be **together,** and return that as a new function: `k(x)`. Is this what OP meant? **Ungolfed** ``` <?php function f($a) { $x=$a[3]; $g=explode("x",$a[1]); $h=explode("x",$a[2]); $k = $g[0]*$h[0]; $k .= "*"; $k .= $x; $k .= "+"; $k .= ($g[0]*$h[1])+$g[1]; $k .= " = "; $k .= ($g[0]*$h[0]*$x) + ($g[0]*$h[1])+$g[1]; return $k; } echo f($argv); ``` [Answer] **Erlang 54:** ``` 1> F = fun(G,H)->B=G(H(0)),A=G(H(1))-B,fun(X)->A*X+B end end. 2> (F(fun(X) -> 2*X+3 end, fun(X) -> 3*X + 4 end))(0). 11 3> (F(fun(X) -> 2*X+3 end, fun(X) -> 3*X + 4 end))(1) - v(2). 6 ``` [Answer] Common Lisp (108) ``` (defun f(g h)(let*((d(g 0))(c(-(g 1)d))(z(h 0))(e(-(h 1)z))(a(* c e))(b(+(* c z)d)))(lambda(x)(+(* a x)b)))) ``` It could be shorter if I assumed expressions would have constants folded...but I didn't make that assumption to make sure I met the spec. Also, I have implemented Clojure's literal anonymous function syntax as a read macro. I decided against using that as well. [Answer] ## Postscript, 120 ``` /f{1 index 0 get dup 2 index 0 get mul exch 3 2 roll 2 get mul 3 2 roll 2 get add[3 1 roll/mul cvx exch/add cvx]cvx}def ``` Ungolfed and commented with testing. ``` /g{2 mul 3 add}def /h{3 mul 4 add}def /f{ 1 index 0 get % g h g[0] dup 2 index 0 get mul % g h g[0] g[0]*h[0] exch 3 2 roll 2 get mul % g g[0]*h[0] g[0]*h[2] 3 2 roll 2 get add % g[0]*h[0] g[0]*h[2]+g[2] [ 3 1 roll /mul cvx exch /add cvx ] cvx }def //g //h f == ``` Output: ``` GPL Ghostscript 9.10 (2013-08-30) Copyright (C) 2013 Artifex Software, Inc. All rights reserved. This software comes with NO WARRANTY: see the file PUBLIC for details. {6 mul 11 add} GS> ``` ]
[Question] [ The challenge is to give as short code as possible to print an ASCII histogram of a set of data. **Input.** The number of bins followed by a number of integers representing the data. The data are space separated. **Output.** An ASCII histogram of the data using the specified number of bins. **Score.** Number of characters in the code excluding trailing whitespace at the beginning or end of each line. Example input. ``` 2 2 3 4 2 2 5 ``` Example output. ``` * * ** ** ``` **Update.** The answers are all great although I can only ever imagine using the one in **R**. No python contribution? [Answer] ## APL ~~66~~ 51 ``` ' *'[1+(⌽⍳b)∘.≤v←+/(⍳b)∘.=⌈x[⍋x]÷(⌈/x←1↓v)÷b←↑v←⍎⍞] ``` Using the example I quoted in my comment on the question where the bin size is 2.25: ``` 4 1 1 2 2 5 8 9 6 3 * * * ** **** ``` [Answer] ### GolfScript, 57 55 52 characters ``` ~](\$:?;:b,{{\?0=-b*?)\0=-)/=" *"=}+?%$}%zip{32-},n* ``` Taking input as single line from STDIN. Script can be tested [online](http://golfscript.apphb.com/?c=OyI0IDEgMSAyIDIgNSA4IDYgMyIKCn5dKFwkOj87OmIse3tcPzA9LWIqPylcMD0tKS89IiAqIj19Kz8lJH0lemlwezMyLX0sbio%3D&run=true). Example: ``` > 4 1 1 2 2 5 8 6 3 * * * * **** ``` [Answer] ## J, ~~96~~ 86 ``` (' *'{~|.@|:@(>/i.@(>./))@(}:@}:,{:@}:+{:)@(+/@(=/i.@>:@{.)~<.@({.*(%>./)@(-<./)@}.))) ``` In a little more readable format: <http://pastebin.com/2CiaJXjC>. ``` (...) 2 2 3 4 2 2 5 * * ** ** (...) 4 1 1 2 2 5 8 6 3 * * * * **** ``` Step by step on example values: <http://pastebin.com/nXjGcq8L>. [Answer] ## R - ~~133~~ 122 characters ``` a=scan() b=table(cut(a[-1],a[1])) invisible(apply(cbind(sapply(b,function(x)c(rep(" ",max(b)-x),rep("*",x))),"\n"),1,cat)) ``` When sourced, it prompts the user for input (because of `scan`), and output the ascii histogram. ``` > source('asciihist.R') 1: 2 2 3 4 5 2 2 5 9: Read 8 items * * * * * * * > source('asciihist.R') 1: 4 1 1 2 2 5 8 6 3 10: Read 9 items * * * * * * * * ``` ]
[Question] [ This is similar to other hang-man style problems already posted, except, in this case, the computer is the one guessing. Computers are logical, smart, and consider self-preservation to be important, so there are a few RULES for how computers will guess. The user will think of any word, that will be contained in the FULL Ispell word list. some of these may be upwards of 10-15 letters. The wordlist is simply the full ispell wordlist (english, and others, all combined), and may be placed in a folder with the program. The computer will be given 8 lives. The computer will start by simply asking for an input of however many characters the word is. (example game below). After that, the computer will begin guessing, following the ruleset below! 1. the computer will analyze all possible word outputs, and determine what letter guess has the most possible correct answers, and guess that letter. It will not duplicate any prior guesses. 2. the computer will then ask for an updated word input, determine if it was correct at all, or wrong, and if wrong, will deduct 1 life. 3. Lastly, the computer will state the lives remaining. ``` EXAMPLE GAME User picks the word "Engineer" Computer asks for Letter count, User replies 8. Computer searches for most likely letter to be used in 8 letter words, determines it is letter H (not correct). Guesses H. User replies _ _ _ _ _ _ _ _ Computer outputs "7 lives remaining" and then picks the next most likely letter, an E User replies e _ _ _ _ e e _ computer outputs "7 lives remaining" and then recalculates based on its current knowledge what is the most likely next letter. Game continues until computer will state WIN, or LOSE. ``` SCORING: every program should follow the EXACT same method to arrive at the final answer. If yours follows the order of every other program, you receive -100 points. If yours is different (aka wrong), you receive 1000 points. each byte of code is worth 1 point. a 30 letter code, is 30 points. if your code manages to play each step of the game in less than 5 seconds, award yourself -100 points. The winner will be chosen 1 week from the first answer, and a new question related to this one, will be asked. Obviously those with the best code here will have a head start on the new one! EDIT: forgot to make note that as in golf, the lowest score wins. [Answer] # K, 196 215 240 (40 points) When reduced to a single line it's 240 chars but I've added newlines here for readability. The question doesn't state exactly what the output needs to look like so I've come up with something fairly minimal. ``` r:0#t:#[c:#w:_0:0;"?"] a:_:'0:`a; l:8; while[~(l=0)|(c=0); q:{x@&~x in y}[>#:'=,/a:a@&a like\:t;r]; if[1=#a;-1 a;j:-1"WIN";exit 0]; -1"Guess ",u:*q; r,:u; $[|/u=w;[c-:+/u=w;@[`t;&u=w;:;u]];-1($l-:1)," lives remaining"]; -1 t; $[0=l;-1"LOSE";0=c;j;]] ``` The wordlist is a file called a in same directory as the code. ``` $ q hm.k -q engineer Guess e e????ee? Guess s 7 lives remaining e????ee? Guess i e??i?ee? engineer WIN ``` EDIT: It now reanalyses the word on each step and determines which is the most likely letter based on previous guesses. EDIT2: If there is only one possible answer (after reanalysis) the computer wins, rather than continuing to guess each individual letter [Answer] ## Python (~~386 352 328 294~~ 300 chars, 100 points) This was fun to do. Produces an error to stop the program. When inputting please give your word in uppercase. Put the Ispells word list in a file called "a", no file extensions. ``` import re a=input() l=8 b=open('a').read().upper() c=0 L=map(chr,range(65,91)) while 1: E=max((b.count(i),i)for i in L)[1];L.remove(E);print E,'\n',l,"lives remaining";d=c;c=raw_input();l-=d==c;b=''.join(re.findall(c.replace('_','[%s]'%sum(L)),b)) if len(b)==a:print"WIN",b;Z if l==0:print"LOSE";Z ``` [Answer] ## Haskell, 781 - 100n Takes the dictionary file name as command line argument. Notices when you try to cheat. words tested and able to beat this on my 90k English word dictionary: 'zappa' and quite a few words of form '.u..y', such as putty It used to have nice prompts and more descriptive output but I ended up golfing those away. It sanitizes dictionary file, filtering out words including non-alphabets and making it all lower case. Removing that would save me 48 bytes, but it's functionality I don't like to remove. I believe this is fast enough for the -100, but I haven't tested it with anything bigger than that 90k words. Also my first haskell program that really does something in IO. All comments welcome. ``` import System.Environment import Data.List import Data.Char import Data.Ord import qualified Data.Set as S import Control.Monad a=['a'..'z'] r=putStrLn z=show k=length fb False=0 fb True=1 lp l=map fst.filter((==l).snd).zip[1..] gu m@(g,p,t)l=fmap(\e-> (l:g,S.filter((==e).lp l)p,t-(fb$null e)))$fmap(lp l)(putStrLn[l]>>getLine) y m@(g,p,t)=case((S.size)p,t)of{(_,0)->r"I lost :<";(1,_)->r$'=':S.toList p!!0; (0,_)->r"Cheater >:|";_->r(z t++" turns left.")>> (gu m$fst.last.sortBy(comparing snd).filter(not.flip elem g.fst).zip a$ S.fold(zipWith(+).(\x->[fb$k`elem`x|k<-a]).nub.sort)(repeat 0)p)>>=y} cg p=fmap(\h->([],S.filter((==(read h)).k)p,8))(r"Word length?">>getLine) pd n=fmap(S.fromList.filter(all isAlpha).words.map toLower)(readFile n) main=getArgs>>=pd.(!!0)>>=cg>>=y ``` **Edit, 868 -> 830** Re-thought the input so I was able to golf away the unsafeIO which required not only a long function call but also an import. Took away the stupid prompt nobody has (for this reason I also updated my example run). Made one or two lambdas point-free, the only one remaining is the `(\x->[fb$k`elem`x|k<-a])` which gets longer if made point free. **Edit, 830 -> 781** Huge thanks to leftaroundbout here. Removed some unnecessary `do`s, changed some `return`s to `fmap`s and unpacked tuples at binding. I guess I still didn't understand all his advice, but this already got me a long way forward. Unfortunately I had to include one space for indentation to keep my lines under 80 chars, since now I don't have those `do` blocks with `;`s delimiting expressions. Run with *hangover* ``` % ./reversehangman /usr/share/dict/british Word length? 8 8 turns left. e ______e_ 8 turns left. s ______e_ 7 turns left. d ______e_ 6 turns left. r ______er 6 turns left. i ______er 5 turns left. a _a____er 5 turns left. n _an___er 5 turns left. o _an_o_er 5 turns left. w _an_o_er =hangover ``` [Answer] ## PHP - ~~367 431 402 367 321~~ 312 bytes (-100 for flow, -100 for quick turns, 112 total) Requires PHP 5.4 (short array syntax) and short open tags (saves 3 bytes!) which is on by default with PHP 5.4. It takes the number of letters in the word as a command line argument. Example command line `php -d short_open_tag=1 golf.php 8` Submitted solution - 312 bytes on disk - there are some deliberate hard newlines in here for pretty output formatting. ``` <?foreach(file('l',2)as$w)$L[]=strlen($w)^$argv[1]?'':$w;for($l=8,$i=[];$l;){$s=$i+count_chars(join($L));arsort($s);$i[$g=key($s)]=0;$h=chr($g);echo"$h ";$r=count_chars($u=trim(fgets(STDIN)));$r[46]||die('WIN');$L=preg_replace($r[$g]||$l--<0?"/^((?!$u).)*$/i":"/.*$h.*/i",'',$L);echo"$l lives remaining ";}?>LOSE ``` Before fat-trimming, with some comments to explain what's going on ``` foreach(file('l',2)as$w) // Words from file called $L[]=strlen($w)^$argv[1]?'':$w; // Only words matching wordlen for($l=8,$i=[];$l;){ // Loop, init lives + used guesses $s=$i+count_chars(join($L)); // Character frequency without guesses arsort($s); // Most frequent first $i[$g=key($s)]=0; // Guess is first item $h=chr($g); // Printable output echo"$h "; // Literal newline saves us a byte $r=count_chars($u=trim(fgets(STDIN))); // User response $r[46]||die('WIN'); // short circuit win, and magic regex below $L=preg_replace($r[$g]||$l--<0 ? "/^((?!$u).)*$/i" : "/.*$h.*/i", '', $L); echo"$l lives remaining "; } // End parsing because it's shorter than echoing ?>LOSE ``` Output with "engineer" - Spaces are not allowed, I'm using full stops instead of underscores due to uh... magic. The program actually knows the word after 3 guesses, but continues 1 guess at a time anyway to save space. ``` e e....ee. 8 lives remaining s e....ee. 7 lives remaining n en..nee. 7 lives remaining i en.inee. 7 lives remaining g enginee. 7 lives remaining r engineer WIN ``` Variation using the same logic as beary605 - 269 bytes, -200 = 69 points. ``` <?$L=file('l',2);for($l=8,$i=[];$l;){$s=$i+count_chars(strtolower(join($L)));arsort($s);$i[$g=key($s)]=0;$h=chr($g);echo"$h ";$r=count_chars($u=trim(fgets(STDIN)));$r[46]||die('WIN');$r[$g]?$L=preg_replace("/^((?!$u).)*$/i",'',$L):$l--;echo"$l lives remaining ";}?>LOSE ``` There's some unaddressed comments about how strictly the output/user prompts needs to be, obviously I have taken liberties here as have other solutions. **Edits** > > **Edit 1** > > Fatal logic error. I wasn't re-analysing correctly when the computer guessed correctly. This got me solving engineer with 5 lives remaining instead of 2, although at the expense of 64 bytes. I can probably improve this later. > > > **Edit 2** > > Drastically improved matching by switching to a regex based filter. Also means I have to use full stops instead of underscores because the user input is essentially feeding regex patterns into the program. > > > **Edit 3** > > Remembered to short-circuit evaluation to remove if statements, and use ternary operator to reduce 2 regex statements to 1. > > > **Edit 4** > > Removed some verbosity with user prompting. Taking initial input on the command line. Removed an unnecessary staging variable. Removed case sensitivity. > > > **Edit 5** > > Sacrificed efficiency for size, xoring word length with user supplied letter count to indicate inclusion. join is an alias of implode. Moved variable initialisation from outside the while loop to inside a for loop initiator saves me a byte! > > > ]
[Question] [ A similar play on the boggle problem from before (some text from that has been used below, edited to fit) any code that solves the familiar "text-twist" game ### Objective 7 letters are given at random, to which there is a minimum 1 word that uses all 7 letters, and multiple words using less (3 or more required) The letters may be used in any order, however not duplicated (unless duplicates are included in the 7) Your code should run for no more than 1 minute (60 seconds). At that time, it should have solved all results. Final challenge score will be the character count of the program. In the event of a tie, the winner will be the fastest output, decided by an average of 3 inputs, the same being given to both. In the event there is still a tie, the winner will be whichever algorithm found more long (6+) words. ### Rules / constraints Please refer to wordlist.sourceforge.net for a word list (use ISPELL "english.0" list - the SCOWL list is missing some pretty common words). This listing may be referenced in your code any way you wish. [Answer] ## Perl, 90 chars ``` $_++for@q{<>=~/./g};open E,"E";while(<E>){%p=%q;$.*=$p{$_}--for/./g;y///c>3&&$.&&print} ``` The program takes the list of letters as a line on standard input. The word list is referenced as a file in the current directory named "E". (Presumably this falls under the umbrella of "any way you wish".) Some other assumptions I made that were not spelled out in the problem description: * that the goal was to produce a program (as opposed to a function); * that the input was case-sensitive; * that apostrophes and hyphens were not to be ignored; * that the program was required to not match on words in the word list that were too short. Also, I wonder if the time limit given in the original description is necessary. Even when given a huge list of letters such that every word in "english.0" matches, my program still runs to completion in under 1s. [Answer] ## Python, 158 chars ``` w=raw_input() q=dict.fromkeys(w,0) for c in w:q[c]+=1 for b in open('E'): p=dict(q) for c in b[:-1]: if p.get(c,0):p[c]-=1 else:b='' if len(b)>3:print b, ``` This seems larger than it needs to be, but I'm just starting to learn Python from a golfing perspective. Hopefully someone more Python-savvy will submit a better answer. [Answer] # bash 152 ``` s(){ echo $1|sed -r 's/(.)/\1\n/g'|sort|tr -d "\n" } o=`s $1|sed -r 's/(.)/\1?/g'` for s in `egrep "^[$1]{3,7}$" e`;do s $s|egrep -q ^$o$&& echo $s;done ``` The file has to be renamed to 'e' (line 1) to make it work. Ungolfed: Let's generate the testdata ourself: ``` alpha=({a..z}) word=$(for n in {1..7}; do r=$((RANDOM%26)); echo -n ${alpha[r]}; done ; echo) echo $word # $word=owimvhl ``` In above code, $word is $1 - user input. ``` text=$(egrep "^[$word]{3,7}$" english.0) # t=hill him hollow how howl iii ill loom low mill mom mow oil owl vii viii vow whim who whom will willow woo wool ``` We take every word of len 3 to 7 from the english.0 dict, ^...$ prevent unwanted characters to slip in. We still might have unwanted duplicates, however. ``` sort () { echo $w | sed -r 's/(.)/\1\n/g' | sort | tr -d '\n' } # sort $w7 => hilmovw ``` We now split the word, to sort the characters, and rebuild the word. Now we insert a ? after every character: ``` optional=$(sort $word|sed -r 's/(.)/\1?/g') # h?i?l?m?o?v?w? ``` This way we only use every character, which appears only once, only once. ``` for s in $text ; do sort $s | egrep -q "^$optional$" && echo $s; done him how howl low mow oil owl vow whim who whom ``` Hm. Assertion that there is a match with 7 characters didn't hold. Try something else: ``` time ./cg-5947-text-twist.sh unknown know known non noun now nun own unknown real 0m0.207s user 0m0.200s sys 0m0.052s ``` [Answer] ### Ruby ~~154 152~~ 151 ``` require 'set' d=Set.new(File.read(?e).split) (3..7).each{|t|puts (0..6).to_a.permutation(t).map{|p|p.map{|i|$*[0][i]}.join}.select{|w|d.include? w}|[]} ``` Expects the 7 letter input as the first command line argument (ex: `ruby texttwist.rb abcdefg`). Dictionary is in a file called "e" in the same dir. [Answer] ### C# 412 ``` void F(string l){ for(var i=3;i<8;i++) foreach(var s in P(l.Length,i,new int[]{}) .Select(p=>new string(p.Select(c=>l[c]).ToArray())) .Where(File.ReadAllLines("e").Contains) .Distinct()) Console.WriteLine(s); } IEnumerable<int[]>P(int n,int r,int[]c){ if(c.Length<r) for(var i=0;i<n;i++)foreach(var j in P(n,r,c.Concat(new[]{i}).ToArray()))yield return j; else if(c.Length==c.Distinct().Count())yield return c; } ``` Not really the right language to golf in, but it was fun. :) The entry point is the `F` method, which needs to be called with a `string` argument representing the 7 letters. I tested it with the input `"indents"` got this output: <http://pastebin.com/uBuwr50R> (unfortunately I don't think it's possible to run this on ideone.com because of the dictionary file dependency). The above test executes in about 7.5s on my machine. If I replace `File.ReadAllLines("e")` with `new HashSet<string>(File.ReadAllLines("e"))`, the execution time drops to about 1.5s, but at a pretty high character count cost. Just like breadbox (in [his Perl answer](https://codegolf.stackexchange.com/a/5951/3527)), I: * named the dictionary file `e` and considered it's present in the current dir * made the string comparisons case sensitive * did not ignore special characters (apostrophes, hyphens) in string comparisons *Update:* Here's an ungolfed (and slightly refactored for readability) version: <http://pastebin.com/b1wxv4zU> ]