36
\$\begingroup\$

In this challenge, you need to solve 4 different tasks using the same set of characters. You can rearrange the characters, but you can't add or remove characters.

The winner will be the submission that solves all tasks using the smallest number of characters. All tasks must be solved in the same language.

Note that it's the smallest number of characters, not the smallest number of unique characters.

Task 1:

Output the first N numbers of every third composite number. The codeblock below shows the first 19 composite numbers in the first row, and every third composite number on the row below.

4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30
4,       9,         14,         18,         22,         26,         30

If N=5 then the output should be 4, 9, 14, 18, 22. You must support 1<=N<=50.

Composite numbers are positive numbers that aren't prime numbers or 1.

The result for N=50 is:

4, 9, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50, 54, 57, 62, 65, 69, 74, 77, 81, 85, 88, 92, 95, 99, 104, 108, 112, 116, 119, 122, 125, 129, 133, 136, 141, 144, 147, 152, 155, 159, 162, 166, 170, 174, 177, 182, 185, 188, 192

Task 2:

Output a N-by-N multiplication table. You must support 1<=N<=20

Example:

N = 4
1   2   3   4
2   4   6   8
3   6   9  12
4   8  12  16

The output format is optional, the following is acceptable output [[1,2,3,4],[2,4,6,8],[3,6,9,12],[4,8,12,16]].

Task 3:

Determine if a number is a Fibonacci number. You must support positive N up to the default integer limit of your language. If there are both 32-bit integers and 64-bit integers then you can choose to use the one that requires the shortest code. For instance, use int instead of long int if you have the choice. You can not choose a smaller integers than 32-bit unless that's default (you can't use 8-bit integers if 32-bit is default).

true/false, false/true, 1/0, 1/-1, a/b are all acceptable output as long as it's consistent.

Task 4:

Take N as input and output the result of 1^1+2^2+3^3+...N^N. You must support 1<=N<=10.

The 10 different results are:

1, 5, 32, 288, 3413, 50069, 873612, 17650828, 405071317, 10405071317

This is , so the shortest submission in each language wins!

This Stack Snippet will help check your solution. It measures the minimum set of characters needed to include all four solutions, and shows the leftover characters.

function update() {
  var m = {};
  var a = [q1.value, q2.value, q3.value, q4.value];
  var o = [{}, {}, {}, {}]
  for (var i = 0; i < 4; i++) {
    for (var j = 0; j < a[i].length; j++) o[i][a[i][j]] = -~o[i][a[i][j]];
    for (var c in o[i]) if (!(o[i][c] < m[c])) m[c] = o[i][c];
  }
  var t = 0;
  for (var c in m) t += m[c];
  for (var i = 0; i < 4; i++) {
    t += "\n";
    for (var c in m) t += c.repeat(m[c] - ~~o[i][c]);
  }
  p.textContent = t;
}
<div oninput="update();">
  <textarea id="q1"></textarea>
  <textarea id="q2"></textarea>
  <textarea id="q3"></textarea>
  <textarea id="q4"></textarea>
</div>
<pre id="p"></pre>

\$\endgroup\$
  • 1
    \$\begingroup\$ Binary: two characters \$\endgroup\$ – coredump Jan 9 '17 at 10:24
  • \$\begingroup\$ @coredump Yes, two unique characters... \$\endgroup\$ – Stewie Griffin Jan 9 '17 at 10:28

11 Answers 11

12
\$\begingroup\$

Python, 88 87 bytes

lambda n:[a for a in range(11*n)if any(a%b<1for b in range(2,a))][:3*n:3]#1,,,=====bd++
lambda n:[[a*b for b in range(1,n+1)]for a in range(1,n+1)]#,,::ybaaa(*i%n< =====2)d33f
f=lambda n,a=1,b=1:a<n and f(n,b,a+b)or n==a#2eerrrfo::((**iii11[[aannn+     ]]y))%33gg
f=lambda n,a=1:a<=n and a**a+f(n,a+1)#::ooeeiii]]      y))bbbgg,,rrrra((11[[nnnnf==2%33

Didn't put too much effort into sharing characters or the golfs themselves, this will almost surely be beat.

\$\endgroup\$
  • 1
    \$\begingroup\$ Will range(11*n) always contain enough composites? \$\endgroup\$ – FlipTack Jan 8 '17 at 20:50
  • 1
    \$\begingroup\$ @FlipTack Yes, 5*n is sufficient. \$\endgroup\$ – Martin Ender Jan 8 '17 at 21:04
12
\$\begingroup\$

Jelly, 19 18 17 characters

Task 1

Ḟþe*S
×5µḊḟÆRm3ḣ³

Try it online!

Task 2

5µḊḟÆRm3ḣ³Ḟe*S
×þ

Try it online!

Task 3

5µḊḟmḣþ*S
×3RÆḞ³e

Try it online!

Task 4

×5ḊḟÆm3ḣ³þe
Rµ*ḞS

Try it online!

How it works

Every line in a Jelly program defines a separate link (function). The last one is the main link and is called automatically when the program is executed. Unless that main link references the others somehow, they have no effect. Note that even uncalled links may not contain parser errors.

Task 1

×5µḊḟÆRm3ḣ³  Main link. Argument: n

×5           Yield 5n.
  µ          Begin a new chain, with argument 5n.
   Ḋ         Dequeue; yield [2, ..., 5n].
     ÆR      Prime range; yield all primes in [1, ..., 5n].
    ḟ        Filter; remove the elements to the right from the ones to the left.
       m3    Pick every third element.
         ḣ³  Keep the first n results.

Task 2

This one's trivial: × is the multiplication atom, and the quick þ (table) applies × to each combination of elements in the left and in the right argument. If the arguments are integers (which they are here), it also casts them to range first.

Task 3

×3RÆḞ³e  Main link. Argument: n

×3       Yield 3n.
  R      Range; yield [1, ..., 3n].
   ÆḞ    Fibonacci; yield [F(1), ... F(3n)].
     ³e  Test if n exists in the result.

Task 4

Rµ*ḞS  Main link. Argument: n

R      Range; yield [1, ..., n].
 µ     Begin a new chain with argument [1, ..., n].
   Ḟ   Floor; yield [1, ..., n].
  *    Yield [1**1, ..., n**n].
    S  Take the sum.
\$\endgroup\$
  • \$\begingroup\$ Glad to see ÆḞ is already proving to be useful! \$\endgroup\$ – Lynn Jan 9 '17 at 1:24
9
\$\begingroup\$

Mathematica, 60 characters

Task 1: Composites

#/AFF^abcinoruy{};Select[Range[2,9#],!PrimeQ@#&][[;;3#;;3]]&

Task 2: Multiplication Table

!29;F@FPQRS[];a^b;c[c[e]];eeegiilmnnotu;Array[3##&,{#,#}]/3&

Task 3: Fibonacci

##&;239;A/PS[]^e[];lmrtuy;{,};!FreeQ[Fibonacci@Range[3#],#]&

Task 4: Sum of powers

!###&;23/39;A@F;F[P[Q[]]];Raabccegiilnnorrty;Sum[e^e,{e,#}]&

Each submission is a set of expressions that are ignored, followed by an unnamed function which implements the given task.

I wrote a simple CJam script which "optimally" combines raw solutions by prepending a comment. I then ended up saving three bytes on top of that by manually getting rid of each comment (which required some rearranging to get valid syntax in each case). The script made it a lot easier to try out simple variations of the solutions to see if they would bring down the overall score. Feel free to use the script yourself.

\$\endgroup\$
  • \$\begingroup\$ I have a comment, but it's not about your code itself :P. (Nice answer, btw). Your CJam script overlooks a simple flaw: If I enter ab and ba as the scripts, it will give me (**)ab and (**)ba, instead of ab and ba. \$\endgroup\$ – HyperNeutrino Jan 9 '17 at 3:25
  • \$\begingroup\$ @AlexL. Yes, it also doesn't consider the fact that (**) itself could be used to cover some characters if they were used in any of the other programs. \$\endgroup\$ – Martin Ender Jan 9 '17 at 6:07
9
\$\begingroup\$

MATL, 29 28 26 characters

Task 1 (every third composite number)

6*:tZp~)G:3*q)%G"$]vwm^sl+

Try it online!

Task 2 (multiplication table)

:l$*%6*tZp~)G:3q)G"]vwm^s+

Try it online!

Task 3 (Fibonacci detector)

l6Zp~G:"3q$t+]vGwm%):*)^s*

This displays 1 / 0 for Fibonacci / non-Fibonacci respectively.

Try it online!

Task 4 (sum of powers)

:t^s%6*Zp~)G:3*q)G"$]vwml+

Try it online!

Check

This program inputs the four strings and displays them sorted, to visually check that they use the same characters.

Explanations

% is the comment symbol. Everything to its right is ignored.

Task 1 (every third composite number)

6*    % Input N. Multiply by 6
:     % Range [1 2 ... 6*N]. This is enough because every even number is composite,
      % so this contains at least 3*N composite numbers
t     % Duplicate
Zp    % Isprime
~     % Negate
)     % Use as index to select composite numbers, including 1, from [1 2 ... 6*N]
G:    % Push [1 2 ... N]
3*q   % Multiply by 3 and subtract 1: gives [2 5 ... 3*N-1]
)     % Pick those composite numbers. Implicitly display

Task 2 (multiplication table)

:     % Input N. Range [1 2 ... N]
l     % Push 1
$     % Specify that next function will take 1 input
*     % Product of array. With 1 input it produces all pair-wise products
      % Implicitly display

Task 3 (Fibonacci detector)

l     % Push 1
6     % Push 6
Zp    % Isprime. Gives false
~     % Negate. Gives true, or 1
G:    % Push [1 2 ... N], where N is the input
"     % For each
  3q  %   3, subtract 1
  $   %   Specify that next function will take 2 inputs
  t   %   Duplicate the top two elements of the stack
  +   %   Add
]     % End
v     % Vertically concatenate the entire stack. This produces a column vector
      % with a sufficient amount of Fibonacci numbers
G     % Push input N
w     % Swap
m     % Ismember. Gives true if input is in the vector of Fibonacci numbers
      % Implicitly display

Task 4 (sum of powers)

:     % Implicitly input N. Push [1 2 ... N]
t     % Duplicate
^     % Power, element-wise
s     % Sum of array. Implicitly display
\$\endgroup\$
  • \$\begingroup\$ When I first looked at the challenge, I thought Hey MATL would be perfect for this! You beat me to it. +1 \$\endgroup\$ – DJMcMayhem Jan 8 '17 at 20:42
  • \$\begingroup\$ @DJMcMayhem Sorry, I tend to answer a lot. Next time ping me and I'll refrain if you are working on it :-) Anyway, why not go ahead? Maybe you can outgolf this \$\endgroup\$ – Luis Mendo Jan 8 '17 at 20:43
  • 3
    \$\begingroup\$ @DJMcMayhem, please post an answer too, even if you don't manage to outgolf Luis. I wish more people would post answers in languages that are already used, even if they don't manage to outgolf the first one. \$\endgroup\$ – Stewie Griffin Jan 8 '17 at 21:05
  • \$\begingroup\$ @stewiegriffin Haha, okay sure. I don't have a valid answer yet, but if I get one (and it's sufficiently different) I'll post it. \$\endgroup\$ – DJMcMayhem Jan 8 '17 at 21:39
7
\$\begingroup\$

Perl 6, 61 bytes

{(4..*).grep(!*.is-prime)[0,3...^*>=$_*3]}#$$&+1==>X[]__oot{}
{[X*](1..$_,!0..$_).rotor($_)}#&***+-..334===>>[]^eegiimpps{}
{(1,&[+]...*>=$_)[*-!0]==$_}#$()**....334>X^_eegiimoopprrst{}
{[+]((1..$_)>>.&{$_**$_})}#!**,-....0334===X[]^eegiimoopprrst

The second one returns ((1,2,3,4),(2,4,6,8),(3,6,9,12),(4,8,12,16)) when given 4

Perl 6 doesn't really have a maximum integer, but the third one works instantly with an input of 15156039800290547036315704478931467953361427680642. The only limiting factors would be memory and time.

Otherwise they will all run "instantly" for inputs well beyond what is necessary.

Try it online

\$\endgroup\$
6
\$\begingroup\$

JavaScript (ES6), 101 100 95 93 91 bytes

(n,r=[],a=(y,m)=>n?y%m?a(y,++m):a(y+1,2,y==m||n--%3||r.push(y)):r)=>a(4,2,n*=3)//>....p*A&&
n=>[...Array(n)].map((r,y,m)=>m.map((s,n)=>y*++n,y+=1))//22334(,,,,===ayy)??%%::||||--uh*&&
r=(n,y=1,a=2)=>n==y||n>y&&r(n,a,y+a)//2334((((,,,,r=[]ayymmmm))))>??%%++::||--.....ppush**A
r=y=>y&&y**y+r(y-1)//22334(((((nnnn,,,,,,,,r=====[]aaaaymmmm)))))>>??%%++::||||-.....ppushA

Edit: Saved 1 byte by not supporting 0 as a Fibonacci number. Saved 5 bytes plus a further 2 bytes (1 thanks to @Arnauld) by renaming variables. Saved 2 bytes by switching between +1, ++ and +=1.

\$\endgroup\$
  • \$\begingroup\$ Replacing all occurrences of the c variable with A should save one byte. \$\endgroup\$ – Arnauld Jan 9 '17 at 17:44
  • \$\begingroup\$ (I was about to suggest that you can also replace d with y, but d is undefined in the current version, so you probably want to fix that first) \$\endgroup\$ – Arnauld Jan 9 '17 at 18:02
  • \$\begingroup\$ @Arnauld Thanks for pointing that out, but I managed to fix things up and save a further byte by renaming a to m. \$\endgroup\$ – Neil Jan 9 '17 at 19:42
4
\$\begingroup\$

MATL, 30 characters

The character set I went with is:

!%))*+001233::<=GGQZ\]^`pstvyy~

I couldn't outgolf the other MATL answer, but I had fun coming up with this solution.

Task 1:

Third composite numbers.

4t^:QtZp~)G3*:3\1=)%!`yy+<]vGs

Try it online!

Task 2:

Multiplication table. Definitely the easiest task, due to the way MATL works

:t!*%4QZp~)G3:3\1=)`yy+<]vGs^t

Try it online!

Task 3:

Fibonacci tester. Prints a positive integer (1 or 2) for truthy inputs, and 0 for falsy inputs.

1t`yy+tG<]vG=s%4:QZp~)3*:3\)!^

Try it online!

Task 4:

Sum of powers

:t^s%1`yy+tG<]vG=4QZp~)3*:3\)!

Try it online!

I'll post a more thorough explanation later, but for now, you should note that % is the comment character, so the programs are really:

4t^:QtZp~)G3*:3\1=)
:t!*
1t`yy+tG<]vG=s
:t^s
\$\endgroup\$
4
\$\begingroup\$

PowerShell, 95 94 bytes

(TimmyD savin' my bacon yet again)

Task 1:

(""..999|?{'1'*$_-match'^(?=(..+)\1+$)..'})[(0..("$args"-1)|%{$_*3})]#|$$$$===ss%``iiex!!nnnq;

Try it online!


Task 2:

($s=1.."$args")|%{"`$s|%{$_*`$_}"|iex}#0113999((((......??''''*$$$--match^===++))))\[]i!!nnnq;

Try it online!


Task 3:

!!(($i="$args")..($s=1)|?{($n=($s+=$n)-$n)-eq$i})#0113999......||?{''''**__match^+\}[""%%]``x;

Try it online!


Task 4:

"$args"..1|%{$s+="$_*"*$_+1|iex};$s#013999(((((......|??{''''$$$--match^===)))))\}[%]``i!!nnnq

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Oh, that stringification "$args" instead of $args[0] is brilliant. I'm going to use that from here on. \$\endgroup\$ – AdmBorkBork Jan 9 '17 at 19:07
  • \$\begingroup\$ @TimmyD Yeah I've been using that for the single byte savings on anything with a single parameter. \$\endgroup\$ – briantist Jan 9 '17 at 19:08
  • \$\begingroup\$ @TimmyD good point! I'd have to re-write all of them to be sure though, I might revisit it and apply that. Once I finished all 4 I kind of petered out in terms of optimizing. \$\endgroup\$ – briantist Jan 9 '17 at 20:13
  • \$\begingroup\$ Well I meant re-doing the TIO links and such but FINE @TimmyD I'll stop being lazy and use your generous suggestion that's not at all as much work as I'm making it out to be! (edited) :-p \$\endgroup\$ – briantist Jan 9 '17 at 20:33
  • \$\begingroup\$ You can eliminate the ; from Task 4 by manipulating the calculation with ("$args"..1|%{$s+="$_*"*$_+1|iex})-(-$s) to save another overall byte. \$\endgroup\$ – AdmBorkBork Jan 10 '17 at 2:18
3
\$\begingroup\$

Haskell, 77 76 characters

m n=[[x|x<-[1..],2/=sum[1|0<-mod x<$>[1..x]]]!!y|y<-[1,4..3*n]]--2 n===y();^
s n=[(*y)<$>[1..n]|y<-[1..n]]--0112234mmm  ====[[[xxxx||<<--..]]],,/uod!!y;^
n x|x<2=1|1<3=sum(n<$>[x-1,x-2]);d y=[0|m<-[1..y],y==n m]--4[[[....]]]/o!!*^
o n=sum[x^x|x<-[1..n]]--01112234mm  n====[[[[x||<<<--....]]]],,/d$>!!yyy*();

Try it online!

-- starts a line comment, so all four programs are of the form <program>--<unused chars>.

Task 1:

m n=[[x|x<-[1..],2/=sum[1|0<-mod x<$>[1..x]]]!!y|y<-[1,4..3*n]]

The longest program. [x|x<-[1..],2/=sum[1|0<-mod x<$>[1..x]]] yields a infinite list of composite numbers plus a starting 1 which corrects the 0-indexing. Usage:

Prelude> m 5
[4,9,14,18,22]

Task 2:

s n=[(*y)<$>[1..n]|y<-[1..n]]

Usage:

Prelude> s 5
[[1,2,3,4,5],[2,4,6,8,10],[3,6,9,12,15],[4,8,12,16,20],[5,10,15,20,25]]

Task 3:

n x|x<2=1|1<3=sum(n<$>[x-1,x-2]);d y=[0|m<-[1..y],y==n m]

Returns [0] for truthy and [] for falsy. Usage:

Prelude> d 5
[0]
Prelude> d 6
[]

Task 4:

o n=sum[x^x|x<-[1..n]]

Usage:

Prelude> o 5
3413
\$\endgroup\$
3
\$\begingroup\$

05AB1E, 21 bytes

Task 1

3ÅFOL¦DâPÙï{3ôø¬¹£qåm

Try it online!

Task 2

LDâP¹ôq3m¦Ùï{3ø¬£ÅFåO

Try it online!

Task 3

3mÅF¹åqL¦DâPÙï{3ôø¬£O

Try it online!

Task 4

LDmOq3¦âPÙï{3ôø¬¹£ÅFå

Try it online!

Explanations

For all tasks, the q ends the program so the code that follows never gets executed.

Task 1

This is the biggest byte-hog. An small improvement here could go a long way.

3ÅFO                 # sum the first 4 fibonacci numbers
    L¦               # range [2 ... above]
      Dâ             # cartesian product with itself
        P            # product
         Ù           # remove duplicates
          ï{         # sort
            3ô       # split in pieces of size 3
              ø      # transpose
               ¬     # get the first lits
                ¹£   # get the first input-nr elements of the list

Task 2

L       # range [1 ... input]
 D      # duplicate
  â     # cartesian product
   P    # product
    ¹ô  # split in pieces of input size

Task 3

3m      # input**3
  ÅF    # get a list of that many (+1) fibonacci numbers
    ¹å  # check if input is in that list

Task 4

L     # range [1 ... input]
 D    # duplicate
  m   # elementwise power of ranges
   O  # sum
\$\endgroup\$
1
\$\begingroup\$

Ruby, 83 82 80 78 characters

->m{'*+-=';[*0..m-1].map{|b|(4..516).select{|p|(2...p).any?{|n|p%n==0}}[3*b]}}
->n{'()%**+--......00123456==?[[]]clmnsty{||}';(b=1..n).map{|e|b.map{|p|e*p}}}
->m{'%+-......001236bclnnpt[[]]{{||||}}';(1..e=m*m).any?{|p|(p*p-5*e).abs==4}}
->n{'%*.......023456=?[]abbceelnsty{{||||}}';((m=0)..n).map{|p|m+=p**p}[-1]-1}

Note: Fibonacci numbers detector using the perfect square method described on Wikipedia: https://en.wikipedia.org/wiki/Fibonacci_number#Recognizing_Fibonacci_numbers

\$\endgroup\$
  • \$\begingroup\$ if you have characters to burn, why not use a comment at the end instead of a string? It saves you 2 characters per line ''; vs # \$\endgroup\$ – Alexis Andersen Jan 9 '17 at 16:20
  • \$\begingroup\$ Thanks, but to me it feels like cheating. \$\endgroup\$ – G B Jan 9 '17 at 18:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.