9
\$\begingroup\$

Idea from the doubler challenge, this may be more difficult.

The program should output a positive integer or decimal point value higher than 0.

If I duplicate the source code, the output should halve the original integer or decimal point value.
But the trickier part is: If I duplicate your code any integer value \$n\$ times, the output should divide by the original integer or decimal point value \$n\$ times too! Edit: As per my mistake (see Jonah's comment) you can divide by 2^n too.

Rules

  • The output must be printed to the program's default STDOUT.
  • The initial source must be at least 1 byte long.
  • Both the integers (or decimal point values) must be in base 10 (outputting them in any other base or with scientific notation is forbidden).
  • Your program must not take input (or have an unused, empty input).
  • Outputting the integers with trailing / leading spaces is allowed.
  • You may not assume a newline between copies of your source.
  • This is , so the shortest (original) code in each language wins!
  • Default Loopholes apply.

Example

Let's say your source code is ABC and its corresponding output is 2. If I write ABCABC instead and run it, the output must be 1. If I write ABCABCABC instead and run it, the output must be 0.5 (or 0.3333333).

This uses uses @manatwork's layout.

/* Configuration */

var QUESTION_ID = 222818; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 96037; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });  
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    
  });
  
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (! /<a/.test(lang)) lang = '<i>' + lang + '</i>';
    lang = jQuery(lang).text().toLowerCase();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.uniq > b.uniq) return 1;
    if (a.uniq < b.uniq) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/Sites/codegolf/all.css?v=617d0685f6f3">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr>
  </tbody>
</table>

Disclaimer: Example and Rules from the original challenge with modifications.

\$\endgroup\$
9
  • 5
    \$\begingroup\$ I was just going to post answer with 0...... \$\endgroup\$ – Wasif Apr 3 at 12:07
  • 1
    \$\begingroup\$ Personally, I'd consider this a dupe of I double the source, you double the output, but given that I have a hammer and the two aren't exact duplicates, I won't VTC unless others agree \$\endgroup\$ – caird coinheringaahing Apr 3 at 13:16
  • 1
    \$\begingroup\$ I wonder how is the "scientific notation forbidden" output rule not broken? \$\endgroup\$ – AZTECCO Apr 3 at 14:04
  • 2
    \$\begingroup\$ @math, I read this as... "the 2 case should divide the original number by 2, the 3 case should divide the original number by 3, etc" but now I see other answers are dividing by 2^n instead of n. Are both allowed or is mine incorrect? \$\endgroup\$ – Jonah Apr 4 at 1:02
  • 1
    \$\begingroup\$ @Peter Cordes right, I wouldn't even attempt a C answer! But if I multiply code of many answers I get a scentific notation output, so is one rule completely ignored or am I missing something ? \$\endgroup\$ – AZTECCO Apr 4 at 19:21

16 Answers 16

14
\$\begingroup\$

Jelly, 3 bytes

o⁹H

Try it online!

Try it online!Try it online!

Try it online!Try it online!Try it online!

How It Works

o⁹H - Main link. Takes implicit argument of 0
o⁹  - Logical OR of 0 and 256
  H - Halve to 128

o⁹Ho⁹H - Main link. Takes implicit argument of 0
o⁹     - Logical OR of 0 and 256
  H    - Halve to 128
   o⁹  - Logical OR of 128 and 256
     H - Halve to 64

And so on

\$\endgroup\$
2
  • \$\begingroup\$ Isn't the logical OR of 128 and 256 384? \$\endgroup\$ – the default. Apr 3 at 13:08
  • 11
    \$\begingroup\$ @thedefault. The bitwise OR of 128 and 256 is 384. Logical OR is a fancy way of saying "replace only 0s with the right argument" \$\endgroup\$ – caird coinheringaahing Apr 3 at 13:10
8
\$\begingroup\$

R, 9 bytes

a=T=T/2;T

Try it online!

T is a (built-in) shortcut for TRUE, which is automatically initialized to a numeric value of 1. We redefine it to half what it was before using T=T/2. R outputs the values of statements consisting of unassigned expressions, so T on its own outputs the current value of T (now equal to 0.5 if there's only one copy of the code).

When we double (or triple...) the code, the final T is appended with a=T=T/2 to become Ta=T=T/2: so, the previously-final unassigned T now becomes an assignment for the variable Ta, which we will never use, but which stops the value from being outputted. T is then halved (again), and its value (now 0.25) output, unless there's another copy of the code...

\$\endgroup\$
7
\$\begingroup\$

Bash, 23

trap echo\ $[8>>n++] 0

Try it online!

Try it online!Try it online!

Try it online!Try it online!Try it online!

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

Python 2, 28 bytes

+0and'',;True/=2.
print True

Try it online! - Outputs 0.5
Try it online! x2 - Outputs 0.25
Try it online! x3 - Outputs 0.125

Explanation

The built-in constant True is modified to be halved after every duplication with True/=2. This prevents the hassle of declaring a new variable. The tricky part is making sure that True is outputted only once. Now is where the +0and'', comes in. It basically fills every print statement with print True+0and'',, which outputs a space. Then on the very last line, print True will output the correct result.

\$\endgroup\$
1
  • \$\begingroup\$ Nice use of the allowed leading spaces! \$\endgroup\$ – justhalf Apr 4 at 10:01
5
\$\begingroup\$

Python 2, 42 41 bytes

print.5**(len(open(__file__).read())/41)#

Try it online!

Read the source file and divide it's byte count by 41 (the length of the original code). Then raise 2 to that power and print it.

thanks to Jonathan Allan for -1 byte

\$\endgroup\$
2
  • \$\begingroup\$ Save one like so \$\endgroup\$ – Jonathan Allan Apr 3 at 16:24
  • 1
    \$\begingroup\$ You can save 6 bytes by assuming an empty filename. Since it is empty, it does not count towards the bytecount (well, it counts as 0 extra bytes), and '' is 6 bytes shorter than __file__. \$\endgroup\$ – Makonede Apr 3 at 23:09
3
\$\begingroup\$

Japt, 4 bytes

I*=½ 
I    // Builtin variable, initially equals 64
 *=  // times equals
   ½ // half.

Try it here.

\$\endgroup\$
3
\$\begingroup\$

Charcoal, 6 bytes

⎚≦⊘φIφ

Try it online! Outputs 500. Try it online! Try it online! Outputs 250. Try it online! Try it online! Try it online! Outputs 125. Explanation:

Clear canvas of previous iterations.

≦⊘φ

Halve the predefined variable for 1,000.

Iφ

Print its current value.

\$\endgroup\$
3
\$\begingroup\$

R, 22 17 bytes

cat(T<-T/2,"\r");

Try it online!

Carriage return doesn't work as intended in TIO, but on my machine the next output flushes the previous one.

-5 bytes using @Dominic's approach

\$\endgroup\$
3
  • \$\begingroup\$ Ah, I always am scared by the "print output" and feel obligated to use cat. Go upvote Dominic's solution: codegolf.stackexchange.com/a/222843/55372 \$\endgroup\$ – pajonk Apr 3 at 20:08
  • \$\begingroup\$ ...and I always forget about the funny R output-formatting! Anyway, I think this one is a beautiful solution itself, that completely avoids any formatting worries: everyone should upvote this, too! \$\endgroup\$ – Dominic van Essen Apr 4 at 13:04
  • 1
    \$\begingroup\$ ...and, possibly you could even save 5 more bytes using the same approach, with cat(T<-T/2,"\r");...? \$\endgroup\$ – Dominic van Essen Apr 4 at 13:06
3
\$\begingroup\$

Perl 5 (-0777l070p), 10, 6 bytes

;$\/=2

switches :
-0777 : undef input record separator (read whole input once).
-l070 : set output record separator to 070 octal character 8.
-p : to print

$\/=2 : divide output record separator (coerced to number) by 2

Try it online!

Try it online!Try it online!Try it online!Try it online!Try it online!

\$\endgroup\$
2
\$\begingroup\$

Javascript ES6, 60 bytes

[0];b=function(){console.log(a)};b[0]=Map;var a=a/2||1;new b

Try it online!

Makes use of the fact that we can call a function without parantheses using new, and the fact that brackets, or computed member access has a higher precedence than new

\$\endgroup\$
2
\$\begingroup\$

Befunge-93, 32 30 bytes

82>:0\g7%!#v_\.@
  v\/2 \+2 <

Try it online!

To reduce the size, the code starts with 8 and does what is required. However, at some point the output will be always zero, due to the lack of the fp division.

Since it's not guaranteed that the copy will have a new line char, I have included the new line char at the end of the second line in the byte count (it's really required for this to work).

Code need to be back to back for it to work (I hope this is acceptable), e.g.:

82>:0\g7%!#v_\.@
  v\/2 \+2 <
82>:0\g7%!#v_\.@
  v\/2 \+2 <

will output 4.

Edit: saved 2 bytes by changing the comparison from subtraction to modulo.

Explanation

82                    Push 8 and 2
>                     Execution goes right (this is where the other copies of the program start executing)
:                     Duplicate the top of the stack (this is n*2, the line of the next copy of the program)
0g                    Push 0 and get the char in (0,n*2). If there are other copies
                      of the program, this will read '8', otherwise ' ' (space)
7%!                   Push 7, do modulo, and not the result. 8 is 56 in ascii, 56%7=0; with space char is 32%7≠0
#v_\.@                If not zero, go down, if zero, swap the stack, print, and end the program
<                     If not zero before, continue left.
\+2                   Add two to the top of the stack (the line of the next copy of the program) and swap (executed right to left)
\/2                   Divide the future output by 2 and swap the stack to get the correct order
v                     Continue the execution in the code below (matches the > at the beginning).
\$\endgroup\$
2
\$\begingroup\$

JavaScript, 44 bytes

Uses a custom getter property o.l to execute console.log. Duplicating the program produces the useless code o.lo={...}.

o={get l(){console.log(o.x)},x:2};o.x/=2;o.l

Try it online!
Try it online!Try it online!
Try it online!Try it online!Try it online!


JavaScript, 44 bytes

Same approach, but using a top-level variable instead of a property.

o={get l(){console.log(x)}};var x=x/2||1;o.l

Try it online!
Try it online!Try it online!
Try it online!Try it online!Try it online!

\$\endgroup\$
2
\$\begingroup\$

Scratch, 42 bytes

Try it online!

I'm pretty certain that this is optimized:

when gf clicked
change[D v]by(1
say((1)/(D

Alternatively, 5 blocks.

\$\endgroup\$
1
\$\begingroup\$

Pyth, 8 6 bytes

e[=cT2

Try it online!

Explanation

e    # Last element of list
[    # Begin list
=    # Set to
cT2  # Float division T/2

thanks to FryAmTheEggman for -2 bytes

\$\endgroup\$
1
  • \$\begingroup\$ I think just e[=cT2 works. \$\endgroup\$ – FryAmTheEggman Apr 3 at 16:12
1
\$\begingroup\$

J, 18 bytes

a=.1+a"_ ::0:0
%a

Try it online! - Returns 1

Try it online!Try it online! - Returns 0.5

Try it online!Try it online!Try it online! - Returns 0.33333

This is the body of an explicit function in J. Note that while J does not have 0 argument functions, this function ignores its input, and so should not be in violation of the "no input" rule.

how

  • a is a local variable, and a"_ is a verb that returns the value stored in a.
  • ::0 says that if the verb a"_ errors while executing, return 0. This will only happen on the first line, when a is undefined. After this line is executed the first time, a will be set to 1, since the first line will resolve as 1+0.
  • On the next run of 1+a"_ ::0:0, a will already be 1, and so it will resolve as 1+1, or 2.
  • Meanwhile %a -- the reciprocal of a -- will be a no-op on all lines in the middle of the function (it won't result in any output). However, the final instance of %a is the return value of the function.

2^n version, 19 bytes

1: :*g(g=.1r2"_ :*)

Try it online!

Try it online!Try it online!Try it online!

This starts with 1/2, and divides by 2 one more time each time the source is repeated.

This works by combining J trains with verbs that behave differently depending on if they are being called with 1 or 2 arguments. Though again, the input itself is always ignored.

\$\endgroup\$
1
\$\begingroup\$

Desmos, 5 bytes

Original - Outputs 0.5

(1/2)

Doubled - Outputs 0.25

(1/2)(1/2)

Tripled - Outputs 0.125

(1/2)(1/2)(1/2)

Try It On Desmos!

\$\endgroup\$
3
  • \$\begingroup\$ Great Answer! I like desmos. \$\endgroup\$ – math Apr 7 at 18:20
  • \$\begingroup\$ Doesn't (.5) work? \$\endgroup\$ – att Apr 9 at 2:56
  • \$\begingroup\$ @att (.5) technically doesn't "output" anything because it doesn't show the "=(something)" part. \$\endgroup\$ – Aiden Chow Apr 9 at 3:00

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.