问:
King of the Hill - Spacewar!

If you've ever played Spacewar!, you know it was a fun game. If you haven't, know this: it was (and is) one of the very first and most important computer games. And it's still fun! The clone I grew up on is this one, which is, apparently and unfortunately, Windows only. So I recreated it!

The KotH is hosted here: PPCG - Spacewar! King of the Hill. I encourage you to play as a human against at least one other bot to get a feel for how the game works.

The Game

One frame is 30 milliseconds (thus, about 33 frames per second).

The field is 800 pixels wide and 600 pixels tall.

The field is toroidal, meaning that spaceships and missiles that move outside of the field reappear on the opposite side.

There are two spaceships, red and blue.

Red is positioned at x=50 and random y between 50, (field height - 50) pixels.

Blue is positioned at x=(field width - 50) and random y between 50, (field height - 50) pixels.

Both face x = (field width)/2.

The available controls are:

Turn left - 5 degrees per frame counterclockwise.

Turn right - 5 degrees per frame clockwise.

Fire missile - travels at an extra 10 pixels per frame in addition to the velocity of the ship, in the direction the ship was pointing.

Fire engine - accelerates the spaceship at 0.30 pixels per frame in the direction the spaceship is pointing.

Hyperspace jump - teleports to some random coordinates in the field, with a 25% chance of exploding. These random coordinates may be on top of the sun.

The maximum speed for ships is 15 pixels per frame under engine power and 40 pixels per frame when gravity-boosted.

When traveling faster than 15 pixels per frame, engine thrust may only change direction or slow down.

Regarding missiles:

Missiles travel in a straight line.

Missiles may be fired at a maximum rate of 1 per 0.1 seconds.

Missiles have a lifetime of 2.25 seconds.

Ships have a maximum of 20 missiles each.

Missiles are point particles internally.

There is a sun in the very center that is extremely hazardous to your ship. The slightest contact is fatal. This sun also destroys missiles.

The sun has gravity. The resultant acceleration is 5000/(distance^2) pixels/frame^2, where distance is in pixels. Spaceships and missiles are affected.

Both ships have three strike zones: the nose, the left wing, and the right wing.

A hit on the nose is instant death.

A hit on either wing reduces the spaceship's turn rate and engine acceleration by half.

If both wings are destroyed, the spaceship cannot be maneuvered and can only fire missiles.

Ships may collide with each other.

A nose-nose impact is fatal for both ships.

A nose-wing impact destroys the wing.

A wing-wing impact destroys both wings.

Dead ships are solid and frozen until they explode 1 second later.

After at least one ship has died, the field is reset 3 seconds later. Until then, the sun and any remaining missiles are still hazardous.

The original game also has deadly and indestructible asteroids, but I won't include those.

The Rules

Your bot must be written in JavaScript.

Your bot should limit its decision to about 10 milliseconds. If I notice consistent lag because of your bot, I'll disqualify it and let you know so you can fix it.

Bots will have access to the following:

Field width and field height

Sun position and radius

The position, rotation, velocity, shape, missile stock, and in-hyperspace status of both ships

The position and velocity of all missiles

When prompted, your bot should return a list of strings.

These strings should be one of the following: turn left, turn right, fire engine, fire missile, hyperspace. Any other string will be ignored.

If there are any duplicates, only the first will be noted.

hyperspace takes precedence over all others.

turn left and turn right at the same time will have no effect.

fire engine will have no effect if the ship only has the nose or is dead.

fire missile will have no effect if a missile was fired too recently.

In a change from the usual, your bot is allowed to exploit the behavior of other bots. I want to encourage a metagame.

Bots may not emulate other bots. (I.e., no mind-reading.)

Bots may not set any variables used by the game and physics code. (I.e., no cheating.)

Bot Implementation Details

I will be storing your bot in its own JavaScript file that is automatically included, with the filename bot_<name>.js. So don't put any spaces or characters that would interfere with this or with naming a function in JavaScript. That's because you should define the following functions: <name>_setup(team) and <name>_getActions(gameInfo, botVars). Further down the page, there exist textareas for the userbot, which you can edit to test your code.

<name>_setup(team)

This function is for you to define any variables that you want to persist. team will be either "red" or "blue". This function must return an object. Define variables like so:

var vars = {};
vars['example'] = "example";
return vars;
```

<p>This <code>vars</code> object will be passed in to the other function:</p>

<h3><code><name>_getActions(gameInfo, botVars)</code></h3>

<p><code>botVars</code> is the object returned by <code><name>_setup(team)</code>. <code>gameInfo</code> is an object containing the following variables:</p>

<pre class="lang-js prettyprint-override"><code>redScore
blueScore
timeLeft

fieldWidth
fieldHeight

sun_x
sun_y
sun_r //sun's radius

gravityStrength //acceleration in pixels/frame^2 at 1 pixel away from the sun's center
engineThrust    //acceleration in pixels/frame^2

speedLimit //maximum speed under engine power
maxSpeed   //maximum speed from gravity boosts

red_x
red_y
red_rot          //rotation in degrees
red_xv           //x velocity
red_yv           //y velocity
red_shape        //one of "full ship", "left wing", "right wing", "nose only"
red_missileStock //the number of missiles red has left
red_inHyperspace //true if red is in hyperspace
red_exploded     //until red explodes, it is still solid and hazardous
red_alive
// likewise for blue //

numMissiles
missiles //this is a list of objects, each with the following variables
  x
  y
  xv
  yv
</code>```

Your bot has full access to these. I'm pretty sure that you can write to them and not affect the original variables, but don't do it anyway. A note on rotations: ships point in the +y direction, downwards, so anything that you want to align with the ship needs to be offset by 90 degrees. Also, positive rotation is clockwise.

This function must return a list of strings, representing your bot's actions. For example, ["turn right","thrust"]. More details on this are in the Rules section.

Additional Details

You may also make use of the following:

LineIntersection(L1, L2)

L1 and L2 are two-element arrays of two-element arrays. That is, L1 := [[x1,y1],[x2,y2]] and L2 := [[u1,v1],[u2,v2]]. This function computes the intersection of two lines and returns this: [[x,y], [a,b]]. [x,y] are the coordinates of the intersection point and [a,b] is a pair of ratios that express how far along each line the intersection point is. As in, a = 0.25 would mean that the intersection point is a quarter of the way from [x1,y1] to [x2,y2], and likewise for b. If there is no intersection, an empty array is returned.

window["shipShapes"]

var shipShapes = {
    'full ship': [[-8,16],[0,-8],[8,16]],
    'left wing': [[-8,16],[0,-8],[4,4],[0,8],[0,16]],
    'right wing':[[-4,4],[0,-8],[8,16],[0,16],[0,8]],
    'nose only': [[-4,4],[0,-8],[4,4],[0,8]]
};
```

<p>These are the coordinates of the ships' polygons. To make getting the current coordinates easier, you may also use...</p>

<h3><code>getShipCoords(<color>)</code></h3>

<p><code>getShipCoords("red")</code> will return the current coordinates of the vertices of Red's ship, and likewise for <code>getShipCoords("blue")</code> and Blue. These coordinates are in a list like so: <code>[[x1,y1],[x2,y2],[x3,y3],...]</code>. Polygons are implicitly closed, so there is a line between the first and last coordinate pairs.</p>

<p><strong>You may not access or alter any other variables or functions in use by the game/website.</strong> And definitely don't name your functions the same. I don't foresee that this will be a problem, but if your bot breaks the game code, that's one possibility. There is no logging or catching of exceptions.</p>

<h2>Winning</h2>

<ul>
<li>Every pairing of bots shall be played at least 10 times, both ways. (So, at least 20 games total.)</li>
<li>Aim to have the highest win/loss ratios <em>overall</em>. If your bot does super well against one other bot, but loses against the other three, that's not as good as winning against two and losing against two (as a general rule of thumb).</li>
<li>For every bot, the ratios (wins+1)/(losses+1) will be calculated, then the mean and standard deviation of these ratios will be calculated. A higher mean will have priority, and in case means are within 1 unit of each other, the lower variance will have priority.</li>
<li>Scoring will begin either in a week from today or after three days of no new submissions. This is so I don't have to repeat any pairing of bots.</li>
</ul>

<p><strong>Above all, have fun!</strong></p>

<hr>

<h2>Leaderboard (2016-01-08 05:15):</h2>

<pre class="lang-js prettyprint-override"><code>#   Name                       Mean      StdDev
1.  Helios                     13.625    6.852
2.  EdgeCase                    8.335    8.155
3.  OpponentDodger              8.415    8.186
4.  OrbitBot                    5.110    6.294
5.  SunAvoider                  5.276    6.772
6.  DangitBobby                 3.320    4.423
7.  SprayAndPray                3.118    4.642
8.  Engineer                    3.903    6.315
9.  RighthandedSpasms           1.805    2.477
10. AttackAndComeBack           2.521    2.921
11. PanicAttack                 2.622    3.102
12. FullSpeedAhead              2.058    3.295
13. UhhIDKWhatToCallThisBot     2.555    3.406
14. MissilesPlusScore           0.159    0.228
15. Hyper                       0.236    0.332
16. RandUmmm                    0.988    1.329
17. Kamikaze                    0.781    1.793
</code>```

Note: This is subject to change as I run more games. Plus, the ordering of ranks 9-13 bothers me, so I may tweak the scoring method to better match one's intuition of how they should be ranked.

(Means and standard deviations were rounded to three decimal digits. Also, Hyper should be HYPER but that messes up the highlighting. :P)

答:
Spy

The story

The prototype to this bot was a bot that had two modes: crazy mode and normal mode. When it was in crazy mode, it stayed there for a constant number of ticks. There was a contant probability of entering crazy mode. It also hyperspaced when it was close to the sun. In crazy mode, it aimed to the other bot and fired constantly. In normal mode, it flew away from the other bot, not firing.

I tweaked that prototype so that it would be in crazy mode if and only if the enemy was close enough. Then I had a crazy idea: what if it only stayed in crazy mode? After some experimentation (I added making the bot fire randomly when it was in normal mode) I found me new bot beat every bot but Helios. This is my code at the end of this process, but before cleaning up.

I wrote my entire bot in the KotH textarea or the JS beautifier. (I did briefly use the Atom editor when cleaning up - but for like two lines of code)

The bot

This bot contains a lot of code borrowed from other bots. It flips the code from Kamikaze to run away from the other bot instead of running to the other bot and it takes code from EdgeCase for hyperspacing when it's close to the sun.

It's arch nemesis is Helios. It being the odd one out and long chats with a martini.

It runs away from the other bot with a 70% chance of firing a missile and hyperspaces when it's close to the sun. As simple as that. Yep.

Edit: I tested my bot with the new code and it fails for every other bot. I'm working on fixing it. I just confirmed this is only for my new bot.

The code

```<code>function Spy_setup(team) {
  // Typical setup. Nothing to see here. ;)
  var botVars = {};
  botVars["color"] = team;
  return botVars;
}

function Spy_getActions(gameInfo, botVars) {
    var actions = [];
    var us, them, red = {
            rotation: gameInfo.red_rot,
            x: gameInfo.red_x,
            y: gameInfo.red_y,
            alive: gameInfo.blue_alive
        },
        blue = {
            rotation: gameInfo.blue_rot,
            x: gameInfo.blue_x,
            y: gameInfo.blue_y,
            alive: gameInfo.blue_alive
        };
    if (botVars.color == "red") {
        us = red;
        them = blue;
    } else if (botVars.color == "blue") {
        us = blue;
        them = red;
    }

    function distance(x1, y1, x2, y2) {
        return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    }

    // Get our ship's position
    var rotation, x, y, opponentAlive;
    if (botVars.color == "red") {
        rotation = gameInfo.red_rot;
        x = gameInfo.red_x;
        y = gameInfo.red_y;
        opponentAlive = gameInfo.blue_alive;
    } else if (botVars.color == "blue") {
        rotation = gameInfo.blue_rot;
        x = gameInfo.blue_x;
        y = gameInfo.blue_y;
        opponentAlive = gameInfo.red_alive;
    }

    // Calculate our rotation compared to the sun in degrees
    var sunX = gameInfo.sun_x,
        sunY = gameInfo.sun_y,
        angle = Math.atan2(sunY - y, sunX - x) * 180 / Math.PI,
        rotationToSun = (rotation - angle + 360) % 360;

    // Check if we need to hyperspace to avoid the sun
    var rX = x - sunX,
        rY = y - sunY,
        distanceFromSun = Math.sqrt(rX * rX + rY * rY) - gameInfo.sun_r;
    if (distanceFromSun < 30) {
        actions.push("hyperspace");
        console.log("Command Module is Hyperspacing.")
    }
    if (gameInfo[botVars["color"] + "_alive"]) {
        var angle = Math.degrees(Math.atan2(them.y - us.y, them.x - us.x)),
            rotationToOpponent = (us.rotation - angle + 360) % 360;
        if (rotationToOpponent > 90 && rotationToOpponent < 270) {
            actions.push("turn right");
        } else {
            actions.push("turn left");
        };
        actions.push("fire engine");
        if (Math.random() > 0.3) {
            actions.push("fire missile")
        }

    }
    return actions;
}
</code>```

The misc

Note: I might've broke something when cleaning up the code because I didn't test the bot after cleaning up the code.

It's also much much much better than all my other bots - it actually beat every other bot except for Helios (edit) , SetCourseFor30Degrees, and OrbitBot! It ties with SunAvoider.

Side note: I'm horrible at javascript, don't know why.

Title: King of the Hill - Spacewar!

Body:
Spy

The story

The prototype to this bot was a bot that had two modes: crazy mode and normal mode. When it was in crazy mode, it stayed there for a constant number of ticks. There was a contant probability of entering crazy mode. It also hyperspaced when it was close to the sun. In crazy mode, it aimed to the other bot and fired constantly. In normal mode, it flew away from the other bot, not firing.

I tweaked that prototype so that it would be in crazy mode if and only if the enemy was close enough. Then I had a crazy idea: what if it only stayed in crazy mode? After some experimentation (I added making the bot fire randomly when it was in normal mode) I found me new bot beat every bot but Helios. This is my code at the end of this process, but before cleaning up.

I wrote my entire bot in the KotH textarea or the JS beautifier. (I did briefly use the Atom editor when cleaning up - but for like two lines of code)

The bot

This bot contains a lot of code borrowed from other bots. It flips the code from Kamikaze to run away from the other bot instead of running to the other bot and it takes code from EdgeCase for hyperspacing when it's close to the sun.

It's arch nemesis is Helios. It being the odd one out and long chats with a martini.

It runs away from the other bot with a 70% chance of firing a missile and hyperspaces when it's close to the sun. As simple as that. Yep.

Edit: I tested my bot with the new code and it fails for every other bot. I'm working on fixing it. I just confirmed this is only for my new bot.

The code

function Spy_setup(team) {
  // Typical setup. Nothing to see here. ;)
  var botVars = {};
  botVars["color"] = team;
  return botVars;
}

function Spy_getActions(gameInfo, botVars) {
    var actions = [];
    var us, them, red = {
            rotation: gameInfo.red_rot,
            x: gameInfo.red_x,
            y: gameInfo.red_y,
            alive: gameInfo.blue_alive
        },
        blue = {
            rotation: gameInfo.blue_rot,
            x: gameInfo.blue_x,
            y: gameInfo.blue_y,
            alive: gameInfo.blue_alive
        };
    if (botVars.color == "red") {
        us = red;
        them = blue;
    } else if (botVars.color == "blue") {
        us = blue;
        them = red;
    }

    function distance(x1, y1, x2, y2) {
        return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    }

    // Get our ship's position
    var rotation, x, y, opponentAlive;
    if (botVars.color == "red") {
        rotation = gameInfo.red_rot;
        x = gameInfo.red_x;
        y = gameInfo.red_y;
        opponentAlive = gameInfo.blue_alive;
    } else if (botVars.color == "blue") {
        rotation = gameInfo.blue_rot;
        x = gameInfo.blue_x;
        y = gameInfo.blue_y;
        opponentAlive = gameInfo.red_alive;
    }

    // Calculate our rotation compared to the sun in degrees
    var sunX = gameInfo.sun_x,
        sunY = gameInfo.sun_y,
        angle = Math.atan2(sunY - y, sunX - x) * 180 / Math.PI,
        rotationToSun = (rotation - angle + 360) % 360;

    // Check if we need to hyperspace to avoid the sun
    var rX = x - sunX,
        rY = y - sunY,
        distanceFromSun = Math.sqrt(rX * rX + rY * rY) - gameInfo.sun_r;
    if (distanceFromSun < 30) {
        actions.push("hyperspace");
        console.log("Command Module is Hyperspacing.")
    }
    if (gameInfo[botVars["color"] + "_alive"]) {
        var angle = Math.degrees(Math.atan2(them.y - us.y, them.x - us.x)),
            rotationToOpponent = (us.rotation - angle + 360) % 360;
        if (rotationToOpponent > 90 && rotationToOpponent < 270) {
            actions.push("turn right");
        } else {
            actions.push("turn left");
        };
        actions.push("fire engine");
        if (Math.random() > 0.3) {
            actions.push("fire missile")
        }

    }
    return actions;
}

The misc

Note: I might've broke something when cleaning up the code because I didn't test the bot after cleaning up the code.

It's also much much much better than all my other bots - it actually beat every other bot except for Helios (edit) , SetCourseFor30Degrees, and OrbitBot! It ties with SunAvoider.

Side note: I'm horrible at javascript, don't know why.


问:
Add two numbers
Input: Two integers. Preferably decimal integers, but other forms of numbers can be used. These can be given to the code in standard input, as arguments to the program or function, or as a list.

Output: Their sum. Use the same format for output integers as input integers. For example, the input 5 16 would lead to the output 21.

Restrictions: No standard loopholes please. This is code-golf, answer in lowest amount of bytes wins.

Notes: This should be fairly trivial, however I'm interested to see how it can be implemented. The answer can be a complete program or a function, but please identify which one it is.

Test cases:

```<code>1 2 -> 3
14 15 -> 29
7 9 -> 16
-1 8 -> 7
8 -9 -> -1
-8 -9 -> -17
</code>```

Or as CSV:

```<code>a,b,c
1,2,3
14,15,29
7,9,16
-1,8,7
8,-9,-1
-8,-9,-17
</code>```

Leaderboard

var QUESTION_ID=84260,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
Yup, 6 bytes

```<code>0*-*-#
</code>```

Try it online!

Explanation

```<code>0*-*-#
0        push 0 to the stack   [0]
 *       place input           [0 a]
  -      subtract              [-a]
   *     place input           [-a b]
    -    subtract              [-a-b]
                             = [b+a]
     #   output
</code>```

As a function on -cheat mode, 9 bytes:

```<code>0~--0~-=+
</code>```

Try it online!

ContentLicense: CC BY-SA 3.0

Title: Add two numbers

Body:
Yup, 6 bytes

0*-*-#

Try it online!

Explanation

0*-*-#
0        push 0 to the stack   [0]
 *       place input           [0 a]
  -      subtract              [-a]
   *     place input           [-a b]
    -    subtract              [-a-b]
                             = [b+a]
     #   output

As a function on -cheat mode, 9 bytes:

0~--0~-=+

Try it online!


问:
Fibonacci reversed!

Introduction

We all know and love our Fibonacci sequence and have seen a myriad of challenge on it here already. However, we're still lacking a very simple case which this answer is going to provide: Reversed fibonacci! So given F_n your job is to find n.

Specification

Input

Your input will be a non-negative integer, which is guaranteed to be part of the fibonacci sequence.

Output

The output must be a non-negative integer as well.

What to do?

The introduction already said: Given a fibonacci number, output its index. Fiboancci number hereby is defined as F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2) and you're given F(n) and must return n.

Potential Corner Cases

0 is a valid in- and output.

If given "1" as input you may either output "1" or "2", as you prefer.

You may always assume that your input actually is a fibonacci number.

You may assume that the input is representable as a 32-bit signed integer.

Who wins?

This is code-golf so the shortest answer in bytes wins!

Standard rules apply of course.

Test-cases

```<code>0 -> 0
2 -> 3
3 -> 4
5 -> 5
8 -> 6
13 -> 7
1836311903 -> 46
</code>```

答:
Perl 6 <s> 33 30 </s> 27 bytes

<s>{first *==$_,:k,(0,1,*+*...*>$_)}
{first *==$_,:k,(0,1,*+*...*)}</s>
{first $_,:k,(0,1,*+*...*)}```

<p>Try it</p>

<h3>Explanation:</h3>

<pre class="lang-perl6 prettyprint-override"><code># lambda with implicit ｢$_｣ parameter
{
  first           # find the first element
    $_,           # where something is equal to the block's argument
    :k,           # return the key rather than the value

    # of the Fibonacci sequence
    ( 0, 1, * + * ... * )
    # ^--^ first two values
    #       ^---^ lambda used to generate the next in the series
    #             ^-^ generate until
    #                 ^ Whatever
}
</code>```

Test:

#! /usr/bin/env perl6
use v6.c;
use Test;

# using the safer version that stops generating
# values bigger than the input
my &fib-index = {first $_,:k,(0,1,*+*...*>$_)}

my @tests = (
  0 => 0,
  2 => 3,
  3 => 4,
  5 => 5,
  8 => 6,
  13 => 7,
  1836311903 => 46,
  1836311904 => Nil, # this is why the safe version is used here
  12200160415121876738 => 93,
  19740274219868223167 => 94,
  354224848179261915075 => 100,
);

plan +@tests + 1;

for @tests -> $_ ( :key($input), :value($expected) ) {
  cmp-ok fib-index($input), &[eqv], $expected, .gist
}

cmp-ok fib-index((0,1,*+*...*)[1000]), &[eqv], 1000, 'works up to 1000th element of Fibonacci sequence'
```

<pre class="lang-perl6 prettyprint-override"><code>1..13
ok 1 - 0 => 0
ok 2 - 2 => 3
ok 3 - 3 => 4
ok 4 - 5 => 5
ok 5 - 8 => 6
ok 6 - 13 => 7
ok 7 - 1836311903 => 46
ok 8 - 1836311904 => Nil
ok 9 - 12200160415121876738 => 93
ok 10 - 19740274219868223167 => 94
ok 11 - 354224848179261915075 => 100
ok 12 - works up to 1000th element of Fibonacci sequence
</code>```

Title: Fibonacci reversed!

Body:
Perl 6 <s> 33 30 </s> 27 bytes

<s>{first *==$_,:k,(0,1,*+*...*>$_)}
{first *==$_,:k,(0,1,*+*...*)}</s>
{first $_,:k,(0,1,*+*...*)}

<a href="https://tio.run/nexus/perl6#ZZDPboJAEMbvPMUcjIKuZGeBBTSanvoEvRnT4LpUggLKYjXGx@7Z7q6tbdPbb/58M/NN10o4cl9MnU7Ti2zV1HF2Z@jnxWpcVGt5ghncLnlxaBX0XsmkJC4lSIajoe/7Q@96081PSuta3eg6ABRmc6BEEzMUGAoMhYYiQ5GhxBA3hLYcW0wCHiCm9K64lxmjFDkNMUKGSczjwGpTOxrTOKQsDhmmCU8YC5DHtmrXBVHIWJiECcYp45hiRGN7AlJ9oqe9NtusgtGXgxGgTuX14dvSeK5NgwuTUp7dXlE1nfIITI7ZtpNuT54aKZRce@DBRW8Tu2Zcl/B43Y@iv5D745LAQ0LAfyta5Vwd55/qz4MX@lK6/DXCxAQG7/WhbKFrQNU2pTYgt3InKwV1Ds/Fqq4yIQpo5b6TlZCD20dVj0UmNvIT" rel="nofollow noreferrer" title="Perl 6 – TIO Nexus">Try it

Explanation:

# lambda with implicit ｢$_｣ parameter
{
  first           # find the first element
    $_,           # where something is equal to the block's argument
    :k,           # return the key rather than the value

    # of the Fibonacci sequence
    ( 0, 1, * + * ... * )
    # ^--^ first two values
    #       ^---^ lambda used to generate the next in the series
    #             ^-^ generate until
    #                 ^ Whatever
}

Test:

#! /usr/bin/env perl6
use v6.c;
use Test;

# using the safer version that stops generating
# values bigger than the input
my &fib-index = {first $_,:k,(0,1,*+*...*>$_)}

my @tests = (
  0 => 0,
  2 => 3,
  3 => 4,
  5 => 5,
  8 => 6,
  13 => 7,
  1836311903 => 46,
  1836311904 => Nil, # this is why the safe version is used here
  12200160415121876738 => 93,
  19740274219868223167 => 94,
  354224848179261915075 => 100,
);

plan +@tests + 1;

for @tests -> $_ ( :key($input), :value($expected) ) {
  cmp-ok fib-index($input), &[eqv], $expected, .gist
}

cmp-ok fib-index((0,1,*+*...*)[1000]), &[eqv], 1000, 'works up to 1000th element of Fibonacci sequence'

1..13
ok 1 - 0 => 0
ok 2 - 2 => 3
ok 3 - 3 => 4
ok 4 - 5 => 5
ok 5 - 8 => 6
ok 6 - 13 => 7
ok 7 - 1836311903 => 46
ok 8 - 1836311904 => Nil
ok 9 - 12200160415121876738 => 93
ok 10 - 19740274219868223167 => 94
ok 11 - 354224848179261915075 => 100
ok 12 - works up to 1000th element of Fibonacci sequence


问:
Write a program to display directory treehouse
Given a directory (such as C:/), given from stdin or read from a file, produce a directory tree, with each file/folder indented based on its depth.

Example

If I have a C:/ drive which only contains two folders foo and bar, and bar is empty while foo contains baz.txt, then running with input C:/ produces:

```<code>C:/
    bar/
    foo/
        baz.txt
</code>```

while running with input C:/foo/ should produce

```<code>foo/
    baz.txt
</code>```

As this is codegolf, lowest byte count wins. The file extensions (such as baz.txt) are optional.
Extra notes: hidden files can be ignored, directories must actually exist, it can be assumed that files do not contain unprintable characters or new lines but all other printable ASCII characters are fine (file names with spaces must be supported). Output can be written to file or stdout. The indentations can be made up of either a tab character or 4 spaces.

答:
Dyalog APL, 48 bytes

```<code>(⊂∘⊃,1↓'[^\\]+\\'⎕R'    ')r[⍋↑r←⎕SH'dir/s/b ',⍞]
</code>```

⍞ prompt for character input

'dir/s/b ', prepend text

⎕SH execute in shell

r← store in r

↑ make list of strings into character matrix

⍋ indices for ascending sorting

r[...] reorder r [sorted]

(...) on the standard out of the shell command, do:

'[^\\]+\\'⎕R'    ' regex replace backslash-terminated runs of non-backslashes by four spaces

1↓ drop the first line

⊂∘⊃, prepend the enclosed first [line]

Result of inputting "\tmp" to the prompt begins as follows on my computer:

```<code>C:\tmp\12u64
            keyboards64.msi
            netfx64.exe
            setup.exe
            setup_64_unicode.msi
            setup_dotnet_64.msi
        AdamsReg.reg
        AdamsReg.zip
        qa.dws
        ride-experimental
            win32
                d3dcompiler_47.dll
                icudtl.dat
                libEGL.dll
</code>```

⋮

Body:
Dyalog APL, 48 bytes

(⊂∘⊃,1↓'[^\\]+\\'⎕R'    ')r[⍋↑r←⎕SH'dir/s/b ',⍞]

⍞ prompt for character input

'dir/s/b ', prepend text

⎕SH execute in shell

r← store in r

↑ make list of strings into character matrix

⍋ indices for ascending sorting

r[...] reorder r [sorted]

(...) on the standard out of the shell command, do:

'[^\\]+\\'⎕R'    ' regex replace backslash-terminated runs of non-backslashes by four spaces

1↓ drop the first line

⊂∘⊃, prepend the enclosed first [line]

Result of inputting "\tmp" to the prompt begins as follows on my computer:

C:\tmp\12u64
            keyboards64.msi
            netfx64.exe
            setup.exe
            setup_64_unicode.msi
            setup_dotnet_64.msi
        AdamsReg.reg
        AdamsReg.zip
        qa.dws
        ride-experimental
            win32
                d3dcompiler_47.dll
                icudtl.dat
                libEGL.dll

⋮


问:
m3ph1st0s's programming puzzle 3 (C): “Easy bug”
This is the 3rd of my series of C/C++ puzzles; in case you missed the first 2 they are here:
(1) m3ph1st0s's programming puzzle 1 (C++)
(2) m3ph1st0s's programming puzzle 2 (C++): "Call hard!"

I must say that my puzzles are 100% original. If not, I will always state so in the text.
 My 3rd puzzle has 2 parts as follows:

Puzzle 3.1

This part (3.1) is not an original puzzle of mine, it is collected from some internet page I've read a while ago. I use it here as a starting point and a warm-up for you. Solve this one and then move on to the 2nd part.

Some one tried to print the "+" sign 20 times and came up with the following program:

```<code>#include <stdio.h>
int main() {
   int i;
   int n = 20;
   for( i = 0; i < n; i-- )
      printf("+");
   return 0;
}
</code>```

The fact that it did not have the expected result is obvious - the program never ends. Fix it!
Easy?
Now fix the program by changing ONLY ONE CHARACTER - non-space character of course! For this challenge there are 3 solutions. Find all 3 of them. Just to make it clear: the program must output 20 "+" signs and must end fast. Before criticizing me on what "fast" means, I'll say it means at most a couple of seconds (which by the way is too much but just to make it crystal clear).

Puzzle 3.2

EDITED
It was pointed to me earlier that the solution for the 3.2.2 puzzle might be compiler-dependent. In order to eliminate any possible discussion on the subject, I'll modify the idea and improve it on a next puzzle when I'll take extra care not to generate controversy.
 However, in order to keep this puzzle going, I'll make a small modification for 3.2.2 (the solution will be easier but cleaner).

When I first saw the puzzle I found it pretty awesome. I did manage to solve it but not immediately since it requires some careful attention.
 If you are here it means you too solved it. If you did so by writing a program to replace all possible characters with all possible values and test every solution, you are lost. Hard working guy though.
 Now having corrected the program that writes 20 "+" signs:

3.2.1: Insert one single letter and nothing more in the code so that the result is valid and outputs the same thing in all 3 corrected programs. Needless to say, the letter must be before the enclosing } of main (I say that because I don't want to hear people who just put a letter after the program and somehow their compiler was very friendly).

EDITED (see bellow) - For these final questions consider that the counter i starts from -1 instead of 0.

3.2.1.5: Repeat all previous problems with the condition that the output is at least 19 "+" signs (but still a finite output). Changing spaces is allowed. Now you might have found more solutions than in the first case. Some of these will most definitely fit for the 3.2.2 question.

3.2.2: Choose another value to initialize the variable n so that the resulting output will remain the same for at least one corrected programs in 3.2.1.5(not necessarily for all of them).

LAST EDIT1: changing the program so that it outputs 21 "+" signs is still a good solution, as the original text did not say "exactly" 20 signs. However, the infinite output is forbidden. Obviously this doesn't mean let's all start outputting hundreds of "+"signs since it's not forbidden. But eliminating a beautiful 21 output would not be in the spirit of this competition.

LAST EDIT2: considering LAST EDIT1 and accepting space changing it seems that now we have 5 possible solutions, four of which have already been pointed out in the responses. The last challenge however hasn't been touched and I must make it clear once more: n must be assigned another value, solutions that assign 20 to n by some tricks won't do it (like n=20L). Also I prefer to see the 3rd solution that does not change spaces.

LAST EDIT3: I've edited the last questions, please read!

The challenge is to solve both parts of the puzzle. The first one to do it wins.

I hope it's all clear, if not please post any questions and I'll edit as quickly as possible. Cheers.
emphasized text

答:
Puzzle 3.1 Answers

Change i-- to n-- (demo: http://ideone.com/l0Y10)

Change i < n to i + n (demo: http://ideone.com/CAqWO)

Change [SPACE]i < n to -i < n. (demo: http://ideone.com/s5Z2r)

Puzzle 3.2.1

Change int n = 20 to int n = 20L (add an L to the end).

Puzzle 3.2.2

Haven't found an answer yet...


问:
Calculate Swatch Internet Time
Output the current time of day as Swatch Internet Time.

Specifically, output a three-digit (zero-padded) number of ".beats" (1000ths of a day) which represent the current time of day in the Swatch Internet Time time zone of UTC+01:00 ("Biel Meantime").

For example, if the current time in UTC is 23:47, then it is 00:47 in UTC+1 ("Biel Meantime"), and the output would be 032.

Examples:

```<code>UTC Current Time  ->  SIT Output
23:47             ->  032
23:00             ->  000
11:00             ->  500
14:37             ->  651
</code>```

The program should produce this output then immediately exit.

Output is to standard output (or equivalent). Must be a complete, runnable program, not a function. The program takes no input; it outputs the current time.

答:
C#, 112 bytes

```<code>class P{static void M(){System.Console.Write((int)((DateTime.UtcNow.TimeOfDay.TotalSeconds%86400+3600)/86.4));}}
</code>```

C#, 68 bytes

```<code>()=>(int)((DateTime.UtcNow.TimeOfDay.TotalSeconds%86400+3600)/86.4);
</code>```

A simple port of @veganaiZe's code. Thanks to him :)

Try it online!

Title: Calculate Swatch Internet Time

Body:
C#, 112 bytes

class P{static void M(){System.Console.Write((int)((DateTime.UtcNow.TimeOfDay.TotalSeconds%86400+3600)/86.4));}}

C#, 68 bytes

()=>(int)((DateTime.UtcNow.TimeOfDay.TotalSeconds%86400+3600)/86.4);

A simple port of @veganaiZe's code. Thanks to him :)

Try it online!


答:
SML, 176 bytes

```<code>open OS.FileSys;val! =chDir;fun&n w=(print("\n"^w^n);!n;print"/";c(openDir(getDir()))(w^"\t");!"..")and c$w=case readDir$of SOME i=>(&i w handle _=>();c$w)|x=>()fun%p=(&p"";!p)
</code>```

Declares (amongst others) a function % which takes a string as argument. Call with % "C:/Some/Path"; or % (getDir()); for the current directory.

I'm using the normally rather functionally used language StandardML whose FileSys-Library I discovered after reading this challenge.

The special characters !, &, $ and % have no special meaning in the language itself and are simply used as identifiers; however they can't be mixed with the standard alphanumeric identifiers which allows to get rid of quite some otherwise needed spaces.

```<code>open OS.FileSys;
val ! = chDir;                       define ! as short cut for chDir

fun & n w = (                        & is the function name
                                     n is the current file or directory name
                                     w is a string containing the tabs
    print ("\n"^w^n);                ^ concatenates strings
    ! n;                             change in the directory, this throws an
                                     exception if n is a file name
    print "/";                       if we are here, n is a directory so print a /
    c (openDir(getDir())) (w^"\t");  call c with new directory and add a tab to w
                                     to print the contents of the directory n
    ! ".."                           we're finished with n so go up again
)
and c $ w =                          'and' instead of 'fun' must be used
                                     because '&' and 'c' are mutual recursive
                                     $ is a stream of the directory content
    case readDir $ of                case distinction whether any files are left
        SOME i => (                  yes, i is the file or directory name
            & i w handle _ => ();    call & to print i an check whether it's a
                                     directory or not, handle the thrown exception
            c $ w )                  recursively call c to check for more files in $
        | x    => ()                 no more files, we are finished

fun % p = (                          % is the function name,
                                     p is a string containing the path
    & p "";                          call & to print the directory specified by p
                                     and recursively it's sub-directories
    ! p                              change back to path p due to the ! ".." in &
)
</code>```

Can be compiled like this with SML/NJ or with Moscow ML* by prefixing with load"OS";.

*See mosml.org, can't post more than 2 links.

Title: Write a program to display directory treehouse

Body:
Given a directory (such as C:/), given from stdin or read from a file, produce a directory tree, with each file/folder indented based on its depth.

Example

If I have a C:/ drive which only contains two folders foo and bar, and bar is empty while foo contains baz.txt, then running with input C:/ produces:

```<code>C:/
    bar/
    foo/
        baz.txt
</code>```

while running with input C:/foo/ should produce

```<code>foo/
    baz.txt
</code>```

As this is codegolf, lowest byte count wins. The file extensions (such as baz.txt) are optional.
Extra notes: hidden files can be ignored, directories must actually exist, it can be assumed that files do not contain unprintable characters or new lines but all other printable ASCII characters are fine (file names with spaces must be supported). Output can be written to file or stdout. The indentations can be made up of either a tab character or 4 spaces.

Body:
SML, 176 bytes

open OS.FileSys;val! =chDir;fun&n w=(print("\n"^w^n);!n;print"/";c(openDir(getDir()))(w^"\t");!"..")and c$w=case readDir$of SOME i=>(&i w handle _=>();c$w)|x=>()fun%p=(&p"";!p)

Declares (amongst others) a function % which takes a string as argument. Call with % "C:/Some/Path"; or % (getDir()); for the current directory.

I'm using the normally rather functionally used language StandardML whose FileSys-Library I discovered after reading this challenge.

The special characters !, &, $ and % have no special meaning in the language itself and are simply used as identifiers; however they can't be mixed with the standard alphanumeric identifiers which allows to get rid of quite some otherwise needed spaces.

open OS.FileSys;
val ! = chDir;                       define ! as short cut for chDir

fun & n w = (                        & is the function name
                                     n is the current file or directory name
                                     w is a string containing the tabs
    print ("\n"^w^n);                ^ concatenates strings
    ! n;                             change in the directory, this throws an
                                     exception if n is a file name
    print "/";                       if we are here, n is a directory so print a /
    c (openDir(getDir())) (w^"\t");  call c with new directory and add a tab to w
                                     to print the contents of the directory n
    ! ".."                           we're finished with n so go up again
)
and c $ w =                          'and' instead of 'fun' must be used
                                     because '&' and 'c' are mutual recursive
                                     $ is a stream of the directory content
    case readDir $ of                case distinction whether any files are left
        SOME i => (                  yes, i is the file or directory name
            & i w handle _ => ();    call & to print i an check whether it's a
                                     directory or not, handle the thrown exception
            c $ w )                  recursively call c to check for more files in $
        | x    => ()                 no more files, we are finished

fun % p = (                          % is the function name,
                                     p is a string containing the path
    & p "";                          call & to print the directory specified by p
                                     and recursively it's sub-directories
    ! p                              change back to path p due to the ! ".." in &
)

Can be compiled like this with SML/NJ or with Moscow ML* by prefixing with load"OS";.

*See mosml.org, can't post more than 2 links.


答:
SML, 3 bytes

```<code>op+
</code>```

This is the prefix version of the infix +. If we input it like this in an interpreter (for example Moscow ML), it's type is displayed

```<code>- op+;
> val it = fn : int * int -> int
</code>```

which tells us how to use it: Given a tuple of integers, an integer will be returned.

```<code>- op+(17,25);
> val it = 42 : int
</code>```

Title: Add two numbers

Body:
Input: Two integers. Preferably decimal integers, but other forms of numbers can be used. These can be given to the code in standard input, as arguments to the program or function, or as a list.

Output: Their sum. Use the same format for output integers as input integers. For example, the input 5 16 would lead to the output 21.

Restrictions: No standard loopholes please. This is code-golf, answer in lowest amount of bytes wins.

Notes: This should be fairly trivial, however I'm interested to see how it can be implemented. The answer can be a complete program or a function, but please identify which one it is.

Test cases:

```<code>1 2 -> 3
14 15 -> 29
7 9 -> 16
-1 8 -> 7
8 -9 -> -1
-8 -9 -> -17
</code>```

Or as CSV:

```<code>a,b,c
1,2,3
14,15,29
7,9,16
-1,8,7
8,-9,-1
-8,-9,-17
</code>```

Leaderboard

var QUESTION_ID=84260,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
SML, 3 bytes

op+

This is the prefix version of the infix +. If we input it like this in an interpreter (for example Moscow ML), it's type is displayed

- op+;
> val it = fn : int * int -> int

which tells us how to use it: Given a tuple of integers, an integer will be returned.

- op+(17,25);
> val it = 42 : int


问:
Find numbers within the Copeland–Erdős constant

Background

The Copeland–Erdős constant is the concatenation of "0." with the base 10 representations of the prime numbers in order. Its value is

```<code>0.23571113171923293137414...
</code>```

See also OEIS A033308.

Copeland and Erdős proved that this is a normal number. This implies that every natural number can be found at some point in the decimal expansion of the Copeland-Erdős  constant.

The challenge

Given a positive integer, express it in base 10 (without leading zeros) and output the index of its first appearance within the sequence of decimal digits of the Copeland–Erdős constant.

Any reasonable input and output format is allowed, but input and output should be in base 10. In particular, the input can be read as a string; and in that case it can be assumed not to contain leading zeros.

Output may be 0-based or 1-based, starting from the first decimal of the constant.

The actual results may be limited by data type, memory or computing power, and thus the program may fail for some test cases. But:

It should work in theory (i.e. not taking those limitations into account) for any input.

It should work in practice for at least the first four cases, and for each of them the result should be produced in less than a minute.

Test cases

Output is here given as 1-based.

```<code>13       -->         7   # Any prime is of course easy to find
997      -->        44   # ... and seems to always appear at a position less than itself
999      -->      1013   # Of course some numbers do appear later than themselves
314      -->       219   # Approximations to pi are also present
31416    -->     67858   # ... although one may have to go deep to find them
33308    -->     16304   # Number of the referred OEIS sequence: check
36398    -->     39386   # My PPCG ID. Hey, the result is a permutation of the input!
1234567  -->  11047265   # This one may take a while to find
</code>```

答:
Python 2, 64 bytes

f=lambda n,k=2,m=1,s='':-~s.find(`n`)or f(n,k+1,m*k*k,s+m%k*`k`)
```

Returns the 1-based index. Test it on Ideone.

Body:
Python 2, 64 bytes

f=lambda n,k=2,m=1,s='':-~s.find(`n`)or f(n,k+1,m*k*k,s+m%k*`k`)

Returns the 1-based index. Test it on Ideone.


答:
TSQL, 143 bytes

Input goes in @n as in DECLARE @n INT = 1836311903;

```<code>DECLARE @O BIGINT=0;WITH F(R,P,N)AS(SELECT @O,@O,@O+1 UNION ALL SELECT R+1,N,P+N FROM F WHERE N<=@n)SELECT MAX(R)FROM F OPTION(MAXRECURSION 0);
</code>```

Title: Fibonacci reversed!

Body:
Introduction

We all know and love our Fibonacci sequence and have seen a myriad of challenge on it here already. However, we're still lacking a very simple case which this answer is going to provide: Reversed fibonacci! So given F_n your job is to find n.

Specification

Input

Your input will be a non-negative integer, which is guaranteed to be part of the fibonacci sequence.

Output

The output must be a non-negative integer as well.

What to do?

The introduction already said: Given a fibonacci number, output its index. Fiboancci number hereby is defined as F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2) and you're given F(n) and must return n.

Potential Corner Cases

0 is a valid in- and output.

If given "1" as input you may either output "1" or "2", as you prefer.

You may always assume that your input actually is a fibonacci number.

You may assume that the input is representable as a 32-bit signed integer.

Who wins?

This is code-golf so the shortest answer in bytes wins!

Standard rules apply of course.

Test-cases

```<code>0 -> 0
2 -> 3
3 -> 4
5 -> 5
8 -> 6
13 -> 7
1836311903 -> 46
</code>```

Body:
TSQL, 143 bytes

Input goes in @n as in DECLARE @n INT = 1836311903;

DECLARE @O BIGINT=0;WITH F(R,P,N)AS(SELECT @O,@O,@O+1 UNION ALL SELECT R+1,N,P+N FROM F WHERE N<=@n)SELECT MAX(R)FROM F OPTION(MAXRECURSION 0);


答:
Jelly, 17 bytes

```<code>ÆRDFṡL}i
Ḥçßç?
çD
</code>```

Returns the 1-based index. Try it online! or verify most test cases.

I've verified the last test case locally; it took 8 minutes and 48 seconds.

How it works

```<code>çD        Main link. Argument: n (integer)

 D        Decimal; yield A, the array of base 10 digits of n.
ç         Call the second helper link with arguments n and A.

Ḥçßç?     Second helper link. Left argument: n. Right argument: A.

Ḥ         Unhalve; yield 2n.
    ?     If...
   ç        the first helper link called with 2n and A returns a non-zero integer:
 ç            Return that integer.
          Else:
  ß           Recursively call the second helper link with arguments 2n and A.

ÆRDFṡL}i  First helper link. Left argument: k. Right argument: A.

ÆR        Prime range; yield the array of all primes up to k.
  DF      Convert each prime to base 10 and flatten the resulting nested array.
     L}   Yield l, the length of A.
    ṡ     Split the flattened array into overlapping slices of length l.
       i  Find the 1-based index of A in the result (0 if not found).
</code>```

Alternate version, 11 bytes (non-competing)

```<code>ÆRVw³
ḤÇßÇ?
</code>```

The w atom did not exist when this challenge was posted. Try it online!

How it works

```<code>ḤÇßÇ?  Main link. Argument: n (integer)

Ḥ      Unhalve; yield 2n.
    ?  If...
   Ç     the helper link called with argument 2n returns a non-zero integer:
 Ç         Return that integer.
       Else:
  ß      Recursively call the main link with argument 2n.

ÆRVw³  Helper link. Argument: k (integer)

ÆR     Prime range; yield the array of all primes up to k.
  V    Eval; concatenate all primes, forming a single integer.
    ³  Yield the first command-line argument (original value of n).
   w   Windowed index of; find the 1-based index of the digits of the result to
       the right in the digits of the result to the left (0 if not found).
</code>```

Title: Find numbers within the Copeland–Erdős constant

Body:
Background

The Copeland–Erdős constant is the concatenation of "0." with the base 10 representations of the prime numbers in order. Its value is

```<code>0.23571113171923293137414...
</code>```

See also OEIS A033308.

Copeland and Erdős proved that this is a normal number. This implies that every natural number can be found at some point in the decimal expansion of the Copeland-Erdős  constant.

The challenge

Given a positive integer, express it in base 10 (without leading zeros) and output the index of its first appearance within the sequence of decimal digits of the Copeland–Erdős constant.

Any reasonable input and output format is allowed, but input and output should be in base 10. In particular, the input can be read as a string; and in that case it can be assumed not to contain leading zeros.

Output may be 0-based or 1-based, starting from the first decimal of the constant.

The actual results may be limited by data type, memory or computing power, and thus the program may fail for some test cases. But:

It should work in theory (i.e. not taking those limitations into account) for any input.

It should work in practice for at least the first four cases, and for each of them the result should be produced in less than a minute.

Test cases

Output is here given as 1-based.

```<code>13       -->         7   # Any prime is of course easy to find
997      -->        44   # ... and seems to always appear at a position less than itself
999      -->      1013   # Of course some numbers do appear later than themselves
314      -->       219   # Approximations to pi are also present
31416    -->     67858   # ... although one may have to go deep to find them
33308    -->     16304   # Number of the referred OEIS sequence: check
36398    -->     39386   # My PPCG ID. Hey, the result is a permutation of the input!
1234567  -->  11047265   # This one may take a while to find
</code>```

Body:
Jelly, 17 bytes

ÆRDFṡL}i
Ḥçßç?
çD

Returns the 1-based index. Try it online! or verify most test cases.

I've verified the last test case locally; it took 8 minutes and 48 seconds.

How it works

çD        Main link. Argument: n (integer)

 D        Decimal; yield A, the array of base 10 digits of n.
ç         Call the second helper link with arguments n and A.

Ḥçßç?     Second helper link. Left argument: n. Right argument: A.

Ḥ         Unhalve; yield 2n.
    ?     If...
   ç        the first helper link called with 2n and A returns a non-zero integer:
 ç            Return that integer.
          Else:
  ß           Recursively call the second helper link with arguments 2n and A.

ÆRDFṡL}i  First helper link. Left argument: k. Right argument: A.

ÆR        Prime range; yield the array of all primes up to k.
  DF      Convert each prime to base 10 and flatten the resulting nested array.
     L}   Yield l, the length of A.
    ṡ     Split the flattened array into overlapping slices of length l.
       i  Find the 1-based index of A in the result (0 if not found).

Alternate version, 11 bytes (non-competing)

ÆRVw³
ḤÇßÇ?

The w atom did not exist when this challenge was posted. Try it online!

How it works

ḤÇßÇ?  Main link. Argument: n (integer)

Ḥ      Unhalve; yield 2n.
    ?  If...
   Ç     the helper link called with argument 2n returns a non-zero integer:
 Ç         Return that integer.
       Else:
  ß      Recursively call the main link with argument 2n.

ÆRVw³  Helper link. Argument: k (integer)

ÆR     Prime range; yield the array of all primes up to k.
  V    Eval; concatenate all primes, forming a single integer.
    ³  Yield the first command-line argument (original value of n).
   w   Windowed index of; find the 1-based index of the digits of the result to
       the right in the digits of the result to the left (0 if not found).


答:
Python, <s>36</s> <s>34</s> 32 bytes

lambda n:len(str(66*n**6))//1.24
```

<h3>Previous versions:</h3>

<pre class="lang-python prettyprint-override"><code>f=lambda n:len(str(66*n**6))//1.24
f=lambda n:(n*n*7).bit_length()//1.4
</code>```

Explanation

The core idea is to invert the formula

fibonacci(n) ~ ( (1 + sqrt(5)) / 2)**n / sqrt(5)
```

<p>which tells us that</p>

<pre class="lang-python prettyprint-override"><code>log fibonacci(n) ~ n log((1 + sqrt(5)) / 2) - log(sqrt(5))
</code>```

to get

f(n) ~ (log(n) + log(sqrt(5))) / log((1 + sqrt(5))/2)
```

The golfing optimizations are:

Use len(str(n)) to compute log base 10 without importing log (old version used .bit_length() to compute log base 2)

Raise n to a power, so that the approximation of the logarithm can distinguish between successive Fibonacci numbers

Multiplying by a constant scales up the values to get them in the correct range

Then the divisor was truncated to as little precision as I could manage and the multiplier chosen to give the correct results for all 32-bit fibonacci numbers.

Title: Fibonacci reversed!

Body:
Python, <s>36</s> <s>34</s> 32 bytes

lambda n:len(str(66*n**6))//1.24

Previous versions:

f=lambda n:len(str(66*n**6))//1.24
f=lambda n:(n*n*7).bit_length()//1.4

Explanation

The core idea is to invert the formula

fibonacci(n) ~ ( (1 + sqrt(5)) / 2)**n / sqrt(5)

which tells us that

log fibonacci(n) ~ n log((1 + sqrt(5)) / 2) - log(sqrt(5))

to get

f(n) ~ (log(n) + log(sqrt(5))) / log((1 + sqrt(5))/2)

The golfing optimizations are:

Use len(str(n)) to compute log base 10 without importing log (old version used .bit_length() to compute log base 2)

Raise n to a power, so that the approximation of the logarithm can distinguish between successive Fibonacci numbers

Multiplying by a constant scales up the values to get them in the correct range

Then the divisor was truncated to as little precision as I could manage and the multiplier chosen to give the correct results for all 32-bit fibonacci numbers.


问:
Output the Juggler sequence
The Juggler sequence is described as follows. Beginning with an input \$a_1\$, the next term is defined by the recurrence relation

$$a_{k+1} = \begin{cases}
\left\lfloor a_k ^ \frac 1 2 \right\rfloor,\text{ if } a_k \text{ is even} \\
\left\lfloor a_k ^ \frac 3 2 \right\rfloor,\text{ if } a_k \text{ is odd} \\
\end{cases}$$

The sequence terminates when it reaches 1, as all subsequent terms would then be 1.

Task

Given an input \$n\$ greater than or equal to 2, write a program/function/generator/etc. that outputs/returns the respective juggler sequence. The output can be in any reasonable form. You may not use a built-in that computes the juggler sequence, or any built-in that directly yields the result. You may assume that the sequence terminates in \$1\$.

Test Cases

```<code>Input: output
2: 2, 1
3: 3, 5, 11, 36, 6, 2, 1
4: 4, 2, 1
5: 5, 11, 36, 6, 2, 1
</code>```

This is a code golf. Shortest code in bytes wins.

答:
dc, 22 21 bytes

```<code>[pd2%2*1+^vd1<F]dsFxn
</code>```

Explained:

```<code>[                # Begin macro definition
 p               # Peek at top of stack (print without popping, followed by newline)
 d               # Duplicate top of stack
 2%              # Mod 2: If even, 0; if odd, 1
 2*1+            # If even: 0*2+1==1; if odd: 1*2+1==3
 ^v              # Raise, then square root: equivalent to `^(0.5)' or `^(1.5)'
 d1<F            # If result is not 1, run macro again
]dsFx            # Duplicate macro, store as `F', execute
n                # Print the final "1"
</code>```

There's a bug: When the input is 1, the output consists of two 1s.

ContentLicense: CC BY-SA 4.0

Title: Output the Juggler sequence

Body:
dc, 22 21 bytes

[pd2%2*1+^vd1<F]dsFxn

Explained:

[                # Begin macro definition
 p               # Peek at top of stack (print without popping, followed by newline)
 d               # Duplicate top of stack
 2%              # Mod 2: If even, 0; if odd, 1
 2*1+            # If even: 0*2+1==1; if odd: 1*2+1==3
 ^v              # Raise, then square root: equivalent to `^(0.5)' or `^(1.5)'
 d1<F            # If result is not 1, run macro again
]dsFx            # Duplicate macro, store as `F', execute
n                # Print the final "1"

There's a bug: When the input is 1, the output consists of two 1s.


问:
Holiday Gift Exchange
Another problem from our internal golfing...this one around the holidays last year.

PROBLEM

Andy, Barb, Carl, Didi, Earl, and Fran are buying gifts for each other. Draw names for a gift exchange.

Each person buys one gift and receives one gift.

Nobody buys their own gift.

Running the solution multiple times should produce different results (giver-receiver pair should not be predictable or identical from run to run).

INPUT

None.

OUTPUT

Formatted as in this example:

Andy buys for Barb

  Barb buys for Carl

  Carl buys for Didi

  Didi buys for Earl

  Earl buys for Fran

  Fran buys for Andy

答:
J, 57

```<code>(,.' buys for ',"1|.)(?~6){6 4$'AndyBarbCarlDidiEarlFran'
</code>```

eg

```<code>   (,.' buys for ',"1|.)(?~6){6 4$'AndyBarbCarlDidiEarlFran'
Carl buys for Earl
Andy buys for Barb
Fran buys for Didi
Didi buys for Fran
Barb buys for Andy
Earl buys for Carl
</code>```

ContentLicense: CC BY-SA 2.5

Title: Holiday Gift Exchange

Body:
J, 57

(,.' buys for ',"1|.)(?~6){6 4$'AndyBarbCarlDidiEarlFran'

eg

   (,.' buys for ',"1|.)(?~6){6 4$'AndyBarbCarlDidiEarlFran'
Carl buys for Earl
Andy buys for Barb
Fran buys for Didi
Didi buys for Fran
Barb buys for Andy
Earl buys for Carl


问:
Ascending matrix
The "ascending matrix" is an infinite matrix of whole numbers (0 included) in which any element is the smallest available element which has not been previously used on the respective row and column:

```<code>  | 1 2 3 4 5 6 ...
--+----------------
1 | 0 1 2 3 4 5 ...
2 | 1 0 3 2 5 4 ...
3 | 2 3 0 1 6 7 ...
4 | 3 2 1 0 7 6 ...
5 | 4 5 6 7 0 1 ...
6 | 5 4 7 6 1 0 ...
. | ...............
</code>```

Your task is to write a program that will output the element found at the row and column specified by the input. (standard input and output)

Test cases:

```<code>5 3 -> 6
2 5 -> 5
</code>```

Code Golf rules apply—the shortest code wins.

P.S. Even if this has an algorithmic nature the code can be very, very concise.

EDIT: I wasn't expecting to see the xor solution so early. I was really hoping to see 10 posts with an algorithmic approach and THEN the xor solution. Now, having in mind that it's not much fun to see how to write xor in different languages I recommend that you also try an algorithmic approach.

So, yes, I think no one can beat the 5 character mark now—therefore I congratulate Ilmari Karonen for the smartest and shortest solution. But there's a new challenge up ahead: write the shortest algorithmic solution.

答:
Haskell 174

Figured I'd make a solution that did not rely on XOR. Too lazy to golf it properly.

```<code>a 0 0=0
a b c
 |m==n=a(b-m)(c-n)
 |m>n=m+a(b-m)c
 |m<n=n+a b(c-n)
 where{g f=until(>f)(*2)1`div`2;m=g b;n=g c;}
main=do
 [x,y]<-fmap(map read.words)getLine
 print$a(x-1)(y-1)
</code>```

Edit: I realized a day later that this is just calculating XOR. Thus if this counts as an algorithmic solution, so should Ilmari Karonen's.

Title: Ascending matrix

Body:
Haskell 174

Figured I'd make a solution that did not rely on XOR. Too lazy to golf it properly.

a 0 0=0
a b c
 |m==n=a(b-m)(c-n)
 |m>n=m+a(b-m)c
 |m<n=n+a b(c-n)
 where{g f=until(>f)(*2)1`div`2;m=g b;n=g c;}
main=do
 [x,y]<-fmap(map read.words)getLine
 print$a(x-1)(y-1)

Edit: I realized a day later that this is just calculating XOR. Thus if this counts as an algorithmic solution, so should Ilmari Karonen's.


答:
Julia, 55 bytes

\(n,s="$n",r=searchindex(n|>primes|>join,s))=r>0?r:3n\s
```

Returns the 1-based index. Completes all test cases in under a second. Try it online!

Body:
Julia, 55 bytes

\(n,s="$n",r=searchindex(n|>primes|>join,s))=r>0?r:3n\s

Returns the 1-based index. Completes all test cases in under a second. Try it online!


答:
Actually, 19 bytes

```<code>╗1`r♂Pεj╜@íu`;)╓i@ƒ
</code>```

Takes a string as input and outputs the 1-based index of the substring

Try it online!

Explanation:

```<code>╗1`r♂Pεj╜@íu`;)╓i@ƒ
╗                    push input to register 0
  `r♂Pεj╜@íu`;)      push this function twice, moving one copy to the bottom of the stack:
   r♂Pεj               concatenate primes from 0 to n-1 (inclusive)
        ╜@íu           1-based index of input, 0 if not found
1              ╓     find first value of n (starting from n = 0) where the function returns a truthy value
                i@   flatten the list and move the other copy of the function on top
                  ƒ  call the function again to get the 1-based index
</code>```

Body:
Actually, 19 bytes

╗1`r♂Pεj╜@íu`;)╓i@ƒ

Takes a string as input and outputs the 1-based index of the substring

Try it online!

Explanation:

╗1`r♂Pεj╜@íu`;)╓i@ƒ
╗                    push input to register 0
  `r♂Pεj╜@íu`;)      push this function twice, moving one copy to the bottom of the stack:
   r♂Pεj               concatenate primes from 0 to n-1 (inclusive)
        ╜@íu           1-based index of input, 0 if not found
1              ╓     find first value of n (starting from n = 0) where the function returns a truthy value
                i@   flatten the list and move the other copy of the function on top
                  ƒ  call the function again to get the 1-based index


问:
Wait a minute – in less than ten seconds

Task

Using any type of parallelisation, wait multiple periods, for a total sleep time of at least a minute (but less than a minute and a half).

The program/function must terminate within 10 seconds and return (by any means and in any format) two values: the total elapsed time, and the total executed sleep time. Both time values have to have a precision of at least 0.1 seconds.

This is similar to the concept of man-hours: a job that takes 60 hours can be completed in only 6 hours if 10 workers are splitting the job. Here we can have 60 seconds of sleep time e.g. in 10 parallel threads, thus requiring only 6 seconds for the whole job to be completed.

Example

The program MyProgram creates 14 threads, each thread sleeps for 5 seconds:

MyProgram → [5.016,70.105]

The execution time is greater than 5 seconds, and the total sleep time is greater than 70 seconds because of overhead.

答:
Common Lisp (Lispworks), 457 bytes

```<code>(defun f(n)(labels((h(n b v)(mp:process-run-function nil nil #'(lambda(b v)(progn(let((s(get-internal-real-time)))(sleep 5)(setf(svref v n)(-(get-internal-real-time)s)))(mp:barrier-wait b :pass-through t)))b v)))(let((s(get-internal-real-time))(e 0)(q 0)(v(make-sequence 'vector n :initial-element 0))(b(mp:make-barrier(1+ n))))(dotimes(i n)(h i b v))(mp:barrier-wait b)(setf e(-(get-internal-real-time)s))(dotimes(p n)(setf q(+ q(svref v p))))(list e q))))
</code>```

ungolfed:

```<code>    (defun f (n-thread)
      (labels ((my-process (process-name n barrier vec)
                 (mp:process-run-function
                  process-name
                  nil
                  #'(lambda (barrier vec)
                      (progn
                        (let ((start-time (get-internal-real-time)))
                          (sleep 5)
                          (setf (svref vec n)
                                (- (get-internal-real-time) start-time)))
                        (mp:barrier-wait barrier :pass-through t)))
                  barrier
                  vec)))

        (let ((total-start-time (get-internal-real-time))
              (total-time 0)
              (sum-per-process-time 0)
              (vector (make-sequence 'vector n-thread :initial-element 0))
              (barrier (mp:make-barrier (1+ n-thread))))
          (dotimes (i n-thread)
            (my-process
             (concatenate 'string "process-" (write-to-string i))
             i
             barrier
             vector))
          (mp:barrier-wait barrier)
          (setf total-time (- (get-internal-real-time) total-start-time))
          (dotimes (p n-thread)
            (setf sum-per-process-time
                  (+ sum-per-process-time (svref vector p))))
          (list total-time sum-per-process-time))))
</code>```

Usage:

```<code>CL-USER 1 > (f 14)
(5028 70280)
</code>```

Body:
Common Lisp (Lispworks), 457 bytes

(defun f(n)(labels((h(n b v)(mp:process-run-function nil nil #'(lambda(b v)(progn(let((s(get-internal-real-time)))(sleep 5)(setf(svref v n)(-(get-internal-real-time)s)))(mp:barrier-wait b :pass-through t)))b v)))(let((s(get-internal-real-time))(e 0)(q 0)(v(make-sequence 'vector n :initial-element 0))(b(mp:make-barrier(1+ n))))(dotimes(i n)(h i b v))(mp:barrier-wait b)(setf e(-(get-internal-real-time)s))(dotimes(p n)(setf q(+ q(svref v p))))(list e q))))

ungolfed:

    (defun f (n-thread)
      (labels ((my-process (process-name n barrier vec)
                 (mp:process-run-function
                  process-name
                  nil
                  #'(lambda (barrier vec)
                      (progn
                        (let ((start-time (get-internal-real-time)))
                          (sleep 5)
                          (setf (svref vec n)
                                (- (get-internal-real-time) start-time)))
                        (mp:barrier-wait barrier :pass-through t)))
                  barrier
                  vec)))

        (let ((total-start-time (get-internal-real-time))
              (total-time 0)
              (sum-per-process-time 0)
              (vector (make-sequence 'vector n-thread :initial-element 0))
              (barrier (mp:make-barrier (1+ n-thread))))
          (dotimes (i n-thread)
            (my-process
             (concatenate 'string "process-" (write-to-string i))
             i
             barrier
             vector))
          (mp:barrier-wait barrier)
          (setf total-time (- (get-internal-real-time) total-start-time))
          (dotimes (p n-thread)
            (setf sum-per-process-time
                  (+ sum-per-process-time (svref vector p))))
          (list total-time sum-per-process-time))))

Usage:

CL-USER 1 > (f 14)
(5028 70280)


问:
Unzip some numbers
Your task is to create a program or function that generates a zipper with a length of 10 lines. Each line of the zipper is represented by two dashes --:

```<code>--
--
--
--
--
--
--
--
--
--
</code>```

The program/function will take a percentage (divisible by 10) as input, and the output will be the zipper "unzipped" (dashes separated) from the top by the percentage, revealing the 1-indexed, lowest level repeated 2 times, with all prior levels repeated 4, 6, 8, ...etc. times, while keeping the bottom of the zipper centered.

Examples

```<code>>>10%
-11-
 --
 --
 --
 --
 --
 --
 --
 --
 --

>>50%
-1111111111-
 -22222222-
  -333333-
   -4444-
    -55-
     --
     --
     --
     --
     --

>>100%
-11111111111111111111-
 -222222222222222222-
  -3333333333333333-
   -44444444444444-
    -555555555555-
     -6666666666-
      -77777777-
       -888888-
        -9999-
         -10-
</code>```

The input (percentage) can be formatted however you like (50%, .5, 50, 5 [zero implied], etc), and it will always be in the range of 0 to 100 and divisible by 10. The spacing in the examples must be preserved in your output.

Title: Unzip some numbers

Body:
Common Lisp (Lispworks),  314 bytes

(defun f()(let((s(string(read))))(let((n(/(parse-integer(subseq s 0(1-(length s))))10)))(if(> n 0)(progn(dotimes(r n)(progn(dotimes(c r)#1=(format t" "))(format t"-")(if(=(1+ r)10)(format t"10")(dotimes(j(* 2(- n r)))(format t"~S"(1+ r))))(format t"-~%")))(dotimes(d(- 10 n))(dotimes(c n)#1#)(format t"--~%")))))))

ungolded:

    (defun f ()
      (let ((s (string (read))))
        (let ((n (/ (parse-integer (subseq s 0 (1- (length s)))) 10)))
          (if (> n 0)
              (progn
                (dotimes (r n)
                  (progn
                    (dotimes (c r)
                      (format t " "))
                    (format t "-")
                    (if (= (1+ r) 10)
                        (format t "10")
                      (dotimes (j (* 2 (- n r)))
                        (format t "~S" (1+ r))))
                    (format t "-~%")))
                (dotimes (d (- 10 n))
                  (dotimes (c n)
                    (format t " "))
                  (format t "--~%")))))))

Usage:

    CL-USER 2515 > (f)
    10%
    -11-
     --
     --
     --
     --
     --
     --
     --
     --
     --
    NIL

    CL-USER 2516 > (f)
    50%
    -1111111111-
     -22222222-
      -333333-
       -4444-
        -55-
         --
         --
         --
         --
         --
    NIL

    CL-USER 2517 > (f)
    100%
    -11111111111111111111-
     -222222222222222222-
      -3333333333333333-
       -44444444444444-
        -555555555555-
         -6666666666-
          -77777777-
           -888888-
            -9999-
             -10-
    NIL


问:
Draw the national flag of Iceland
This year's UEFA Euro 2016 is over and besides a couple of negative headlines there has been a very positive surprise as well – the Iceland national football team. Let's draw their national flag.

Input

Well, obviously this challenge has no input.

Output

Draw the flag of Iceland in any applicable visual format of at least 100 x 72 pixels or 25 x 18 characters.

Save the output to a file or present it instantly – example formats are: images like png, jpg etc., vector graphics, draw on HTML canvas or even use non-whitespace characters for visualization.

Use these colors: blue: #0048e0, white: #ffffff and red: #d72828.

If your language doesn't support specific color values, use the standard values for red, blue and white from the ANSI color codes.

Draw the flag with the correct proportions, as shown in the figure below:

Boilerplate

You can write a program or a function. If it is an anonymous function, please include an example of how to invoke it.

This is code-golf so shortest answer in bytes wins.

Standard loopholes are disallowed.

Leaderboard

var QUESTION_ID = 85141; // 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 = 41859; // This should be the user ID of the challenge author.
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 = '
' + c.body.replace(OVERRIDE_REG, '') + '
';});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 = '' + lang + '';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);}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>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;}</code>```

<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/Sites/codegolf/all.css?v=617d0685f6f3">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}

{{LANGUAGE}}	{{NAME}}	{{SIZE}}

```

If you can't find your answer, format your language and byte count as explained in the Leaderboard's "Info Section".

This challenge is inspired by Draw the national flag of france.

答:
Common Lisp (Lispworks), 465 bytes

```<code>(capi:contain(make-instance'capi:output-pane :display-callback #'(lambda(#4=pane x y #5=width #6=height)(let((a(/ #5# 25))(b(/ #6# 18)))(progn(#1=gp:draw-rectangle #4# x y #5# #6# #2=:filled t #3=:foreground :blue)(#1# #4# x(+ y(* b 7))#5#(+ y(* b 4))#2# t #3# :white)(#1# #4#(+ x(* a 7))y(+ x(* a 4)) #6# #2# t #3# :white)(#1# #4# x(+ y(* b 8))#5#(+ y(* b 2))#2# t #3# :red)(#1# #4#(+ x(* a 8))y(+ x(* a 2))(+ y(* b 18))#2# t #3# :red)))):width 200 :height 144))
</code>```

ungolfed:

```<code>    (defun draw-a-flag (pane x y width height)
      (let ((a (/ width 25)) (b (/ height 18)))
        (progn
          (gp:draw-rectangle pane x y width height :filled t :foreground :blue)
          (gp:draw-rectangle pane x (+ y (* b 7)) width (+ y (* b 4)) :filled t :foreground :white)
          (gp:draw-rectangle pane (+ x (* a 7)) y (+ x (* a 4)) height :filled t :foreground :white)
          (gp:draw-rectangle pane x (+ y (* b 8)) width (+ y (* b 2)) :filled t :foreground :red)
          (gp:draw-rectangle pane (+ x (* a 8)) y (+ x (* a 2)) (+ y (* b 18)) :filled t :foreground :red))))

    (capi:contain
     (make-instance
      'capi:output-pane
      :display-callback 'draw-a-flag)
     :best-width 200
     :best-height 144)
</code>```

Usage:

Title: Draw the national flag of Iceland

Body:
Common Lisp (Lispworks), 465 bytes

(capi:contain(make-instance'capi:output-pane :display-callback #'(lambda(#4=pane x y #5=width #6=height)(let((a(/ #5# 25))(b(/ #6# 18)))(progn(#1=gp:draw-rectangle #4# x y #5# #6# #2=:filled t #3=:foreground :blue)(#1# #4# x(+ y(* b 7))#5#(+ y(* b 4))#2# t #3# :white)(#1# #4#(+ x(* a 7))y(+ x(* a 4)) #6# #2# t #3# :white)(#1# #4# x(+ y(* b 8))#5#(+ y(* b 2))#2# t #3# :red)(#1# #4#(+ x(* a 8))y(+ x(* a 2))(+ y(* b 18))#2# t #3# :red)))):width 200 :height 144))

ungolfed:

    (defun draw-a-flag (pane x y width height)
      (let ((a (/ width 25)) (b (/ height 18)))
        (progn
          (gp:draw-rectangle pane x y width height :filled t :foreground :blue)
          (gp:draw-rectangle pane x (+ y (* b 7)) width (+ y (* b 4)) :filled t :foreground :white)
          (gp:draw-rectangle pane (+ x (* a 7)) y (+ x (* a 4)) height :filled t :foreground :white)
          (gp:draw-rectangle pane x (+ y (* b 8)) width (+ y (* b 2)) :filled t :foreground :red)
          (gp:draw-rectangle pane (+ x (* a 8)) y (+ x (* a 2)) (+ y (* b 18)) :filled t :foreground :red))))

    (capi:contain
     (make-instance
      'capi:output-pane
      :display-callback 'draw-a-flag)
     :best-width 200
     :best-height 144)

Usage:


问:
Remove duplicated & switched case

Goal

The goal of this challenge is: given a string as input, remove duplicate pairs of letters, if the second item in the pair is of opposite capitalization. (i.e. uppercase becomes lowercase and vice-versa).

Pairs should be replaced from left to right. For example, aAa should become aa and not aA.

Inputs & outputs:

```<code>Input:         Output:
bBaAdD         bad
NniIcCeE       Nice
Tt eE Ss tT    T e S t
sS Ee tT       s E t
1!1!1sStT!     1!1!1st!
nN00bB         n00b
(eE.gG.)       (e.g.)
Hh3lL|@!       H3l|@!
Aaa            Aa
aaaaa          aaaaa
aaAaa          aaaa
</code>```

The input consists of printable ASCII symbols.

You shouldn't remove duplicated digits or other non-letter characters.

Acknowledgement

This challenge is the opposite of @nicael 's "Duplicate & switch case". Can you reverse it?

Thank you for all contributors from the sandbox!

Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
JavaScript (ES6), <s>61 bytes</s>, 57 Bytes

s=>s.replace(/./g,c=>l=c!=l&/(.)\1/i.test(l+c)?'':c,l='')

Thanks to Neil for saving 5 bytes.

Title: Remove duplicated & switched case


答:
J, 37 bytes

```<code>(0{":@[I.@E.[:;<@":@p:@i.@]) ::($:+:)
</code>```

Input is given as a base 10 integer and the output uses zero-based indexing.

Usage

```<code>   f =: (0{":@[I.@E.[:;<@":@p:@i.@]) ::($:+:)
   f 1
4
   f 13
6
   f 31416
67857
</code>```

Explanation

This first call treats the verb as a monad, however subsequent calls which may occur recursively treat it as a dyad.

```<code>0{":@[I.@E.[:;<@":@p:@i.@]  Input: n on LHS, k on RHS
                         ]  Get k
                      i.@   Get the range [0, 1, ..., k-1]
                   p:@      Get the kth prime of each
                ":@         Convert each to a string
              <@            Box each string
           [:;              Unbox each and concatenate to get a string of primes
     [                      Get n
  ":@                       Convert n to a string
      I.@E.                 Find the indices where the string n appears in
                            the string of primes
0{                          Take the first result and return it - This will cause an error
                            if there are no matches

(...) ::($:+:)  Input: n on RHS, k on LHS
(...)           Execute the above on n and k
      ::(    )  If there is an error, execute this instead
           +:   Double k
         $:     Call recursively on n and 2k
</code>```

Body:
J, 37 bytes

(0{":@[I.@E.[:;<@":@p:@i.@]) ::($:+:)

Input is given as a base 10 integer and the output uses zero-based indexing.

Usage

   f =: (0{":@[I.@E.[:;<@":@p:@i.@]) ::($:+:)
   f 1
4
   f 13
6
   f 31416
67857

Explanation

This first call treats the verb as a monad, however subsequent calls which may occur recursively treat it as a dyad.

0{":@[I.@E.[:;<@":@p:@i.@]  Input: n on LHS, k on RHS
                         ]  Get k
                      i.@   Get the range [0, 1, ..., k-1]
                   p:@      Get the kth prime of each
                ":@         Convert each to a string
              <@            Box each string
           [:;              Unbox each and concatenate to get a string of primes
     [                      Get n
  ":@                       Convert n to a string
      I.@E.                 Find the indices where the string n appears in
                            the string of primes
0{                          Take the first result and return it - This will cause an error
                            if there are no matches

(...) ::($:+:)  Input: n on RHS, k on LHS
(...)           Execute the above on n and k
      ::(    )  If there is an error, execute this instead
           +:   Double k
         $:     Call recursively on n and 2k


问:
Stock Time Machine

Stock Time Machine

You've gained access to a dataset, tomorrowStocks, which contains the stock prices from your favorite business on the NASDAQ. This dataset is a container indexed by minutes past opening. Each index contains the price of the stock at that time.

```<code>// Assume the stock market opens at 9:30AM EDT
// tomorrowStocks[] contains the prices of your target stock.
// If the stock is $22 @ 10:30AM EDT
tomorrowStocks[60] == 22
</code>```

Output

Your task is to determine the best possible outcome of 1 purchase and 1 sale of 1 stock from the given dataset.

Gotchas

You must buy and sell exactly 1 stock.

You may not buy and sell in the same time slot.

You must buy before you sell.

Test Data

```<code>[1,2,3,4,5]    # 4
[1,99,2,105]   # 104
[99,1,99,100]  # 99
[99,1,1,2,1,3] # 2
[5,4,3,3,1]    # 0
[5,4,3,1]      # -1
[5,2,1]        # -1
[5,4,1]        # -1
[55,45,20,1]   # -10
[5,1]          # -4
[10,7,5,1]     # -2
[7]            # Invalid input -- assume size >= 2
</code>```

This is a code-golf; submit the shortest answer in your favorite language!

答:
Java, 116

Another java solution, i used this one to prove that, streams might looks nice, but not always useful for golfing.

```<code>int a(int[]a){int t,d=a[1]-a[0],i,j,l=a.length;for(i=0;i<l;i++)for(j=i+1;j<l;j++){t=a[j]-a[i];d=d<t?t:d;}return d;}
</code>```

there is lot of space for improvements in this solution

Title: Stock Time Machine

Body:
Java, 116

Another java solution, i used this one to prove that, streams might looks nice, but not always useful for golfing.

int a(int[]a){int t,d=a[1]-a[0],i,j,l=a.length;for(i=0;i<l;i++)for(j=i+1;j<l;j++){t=a[j]-a[i];d=d<t?t:d;}return d;}

there is lot of space for improvements in this solution


答:
Pyth, 13 bytes

```<code>J1tf>=Z+~JZZQ
</code>```

Test suite.

Approximation in Python 2:

Z=0;J=1;T=1;Q=input()
while not J+Z>Q:
    temp=J
    J=Z
    Z=temp+J
    T += 1
print(T-1)
```

<h3>alternative approach, 18 bytes</h3>

```L?<b2bsyMtBtbs.IyG
```

Test suite.

This uses .I for inverse.

Title: Fibonacci reversed!

Body:
Pyth, 13 bytes

J1tf>=Z+~JZZQ

Test suite.

Approximation in Python 2:

Z=0;J=1;T=1;Q=input()
while not J+Z>Q:
    temp=J
    J=Z
    Z=temp+J
    T += 1
print(T-1)

alternative approach, 18 bytes

L?<b2bsyMtBtbs.IyG

Test suite.

This uses .I for inverse.


答:
Pyth, 17 bytes

```<code> fhJxs`MfP_YSTz2J
</code>```

Leading space is important.

Test suite.

Body:
Pyth, 17 bytes

 fhJxs`MfP_YSTz2J

Leading space is important.

Test suite.


问:
JSON tips: filter objects from array of objects where object name is alpha

What could be the shortest code for filtering the following array in Javascript without any library?

My code is:

filtered_obj = _.where(obj, { name: "Alpha" });
```

<p>This uses a JS library called <code>underscore</code>.</p>

<p>Test case:</p>

<pre class="lang-javascript prettyprint-override"><code>objs = [{'id':1,'name':'Alpha'},{'id':2,'name':'Beta'},
{'id':3,'name':'Gamma'},{'id':4,'name':'Eta'},
{'id':5,'name':'Alpha'},{'id':6,'name':'Zeta'},
{'id':7,'name':'Beta'},{'id':8,'name':'Theta'},
{'id':9,'name':'Alpha'},{'id':10,'name':'Alpha'}];

filtered_obj =[{'id':1,'name':'Alpha'},{'id':5,'name':'Alpha'},
{'id':9,'name':'Alpha'},{'id':10,'name':'Alpha'}]
</code>```

答:
45 bytes

filtered_obj=objs.filter(n=>n.name=='Alpha');
```

This uses the filter function for arrays.

Ideone it!

Body:
45 bytes

filtered_obj=objs.filter(n=>n.name=='Alpha');

This uses the filter function for arrays.

Ideone it!


答:
Julia, <s>27</s> <s>26</s> 18 bytes

!n=log(3n+.7)÷.48
```

This uses the inverse of Binet's formula, with just enough precision for  32-bit integers; it actually works up to F(153) = 42,230,279,526,998,466,217,810,220,532,898 > 2105.

Try it online!

How it works

Binet's formula states the following.

Restricting F to the set of Fibonacci, the map n → Fn has a right inverse F → nF.

We have that

and all that is left to do is dealing with the edge case 0.

Since the input is restricted to 32-bit integers, we can use short decimal literals instead of the constants in the formula.

log φ = 0.481211825059603447… ≈ 0.48

Unfortunately, 0.5 isn't precise enough.

√5 = 2.2360679774997896964… ≈ 3

That might seem like an awful approximation at first glance, but we're taking logarithms and since log 3 - log √5 = 0.29389333245105…, the result before rounding will be off by a small constant factor.

0.5 ≈ 0.7

Because of the excess from the previous approximation, we could actually omit this term altogether and still get correct results for F > 0. However, if F = 0, the logarithm will be undefined. 0.7 turned out to be the shortest value that extends our formula to F = 0.

Title: Fibonacci reversed!

Body:
Introduction

We all know and love our Fibonacci sequence and have seen a myriad of challenge on it here already. However, we're still lacking a very simple case which this answer is going to provide: Reversed fibonacci! So given F_n your job is to find n.

Specification

Input

Your input will be a non-negative integer, which is guaranteed to be part of the fibonacci sequence.

Output

The output must be a non-negative integer as well.

What to do?

The introduction already said: Given a fibonacci number, output its index. Fiboancci number hereby is defined as F(0)=0, F(1)=1, F(n)=F(n-1)+F(n-2) and you're given F(n) and must return n.

Potential Corner Cases

0 is a valid in- and output.

If given "1" as input you may either output "1" or "2", as you prefer.

You may always assume that your input actually is a fibonacci number.

You may assume that the input is representable as a 32-bit signed integer.

Who wins?

This is code-golf so the shortest answer in bytes wins!

Standard rules apply of course.

Test-cases

```<code>0 -> 0
2 -> 3
3 -> 4
5 -> 5
8 -> 6
13 -> 7
1836311903 -> 46
</code>```

Body:
Julia, <s>27</s> <s>26</s> 18 bytes

!n=log(3n+.7)÷.48

This uses the inverse of Binet's formula, with just enough precision for  32-bit integers; it actually works up to F(153) = 42,230,279,526,998,466,217,810,220,532,898 > 2105.

Try it online!

How it works

Binet's formula states the following.

Restricting F to the set of Fibonacci, the map n → Fn has a right inverse F → nF.

We have that

and all that is left to do is dealing with the edge case 0.

Since the input is restricted to 32-bit integers, we can use short decimal literals instead of the constants in the formula.

log φ = 0.481211825059603447… ≈ 0.48

Unfortunately, 0.5 isn't precise enough.

√5 = 2.2360679774997896964… ≈ 3

That might seem like an awful approximation at first glance, but we're taking logarithms and since log 3 - log √5 = 0.29389333245105…, the result before rounding will be off by a small constant factor.

0.5 ≈ 0.7

Because of the excess from the previous approximation, we could actually omit this term altogether and still get correct results for F > 0. However, if F = 0, the logarithm will be undefined. 0.7 turned out to be the shortest value that extends our formula to F = 0.


答:
05AB1E, 14 bytes

Uses 0-indexed output. Prime functions in osabie are very inefficient. Code:

```<code>[NØJD¹å#]¹.Oð¢
</code>```

Explanation:

```<code>[       ]        # Infinite loop...
 N               # Get the iteration value
  Ø              # Get the nth prime
   J             # Join the stack
    D            # Duplicate this value
     ¹å#         # If the input is in this string, break out of the loop
         ¹.O     # Overlap function (due to a bug, I couldn't use the index command)
            ð¢   # Count spaces and implicitly print
</code>```

Uses the CP-1252 encoding. Try it online!.

Body:
Background

The Copeland–Erdős constant is the concatenation of "0." with the base 10 representations of the prime numbers in order. Its value is

```<code>0.23571113171923293137414...
</code>```

See also OEIS A033308.

Copeland and Erdős proved that this is a normal number. This implies that every natural number can be found at some point in the decimal expansion of the Copeland-Erdős  constant.

The challenge

Given a positive integer, express it in base 10 (without leading zeros) and output the index of its first appearance within the sequence of decimal digits of the Copeland–Erdős constant.

Any reasonable input and output format is allowed, but input and output should be in base 10. In particular, the input can be read as a string; and in that case it can be assumed not to contain leading zeros.

Output may be 0-based or 1-based, starting from the first decimal of the constant.

The actual results may be limited by data type, memory or computing power, and thus the program may fail for some test cases. But:

It should work in theory (i.e. not taking those limitations into account) for any input.

It should work in practice for at least the first four cases, and for each of them the result should be produced in less than a minute.

Test cases

Output is here given as 1-based.

```<code>13       -->         7   # Any prime is of course easy to find
997      -->        44   # ... and seems to always appear at a position less than itself
999      -->      1013   # Of course some numbers do appear later than themselves
314      -->       219   # Approximations to pi are also present
31416    -->     67858   # ... although one may have to go deep to find them
33308    -->     16304   # Number of the referred OEIS sequence: check
36398    -->     39386   # My PPCG ID. Hey, the result is a permutation of the input!
1234567  -->  11047265   # This one may take a while to find
</code>```

Body:
05AB1E, 14 bytes

Uses 0-indexed output. Prime functions in osabie are very inefficient. Code:

[NØJD¹å#]¹.Oð¢

Explanation:

[       ]        # Infinite loop...
 N               # Get the iteration value
  Ø              # Get the nth prime
   J             # Join the stack
    D            # Duplicate this value
     ¹å#         # If the input is in this string, break out of the loop
         ¹.O     # Overlap function (due to a bug, I couldn't use the index command)
            ð¢   # Count spaces and implicitly print

Uses the CP-1252 encoding. Try it online!.


答:
Python, 29 bytes

g=lambda n:n>.7and-~g(n/1.61)
```

<p>Recursively divides the input by the golden-ratio approximation 1.61 until it's below 0.7, and outputs the number of divisions.</p>

<p>For 0, the code outputs <code>False</code>, which equals 0 in Python. This can be avoided for 2 bytes</p>

<pre class="lang-python prettyprint-override"><code>g=lambda n:n//.7and 1+g(n/1.61)
</code>```

Title: Fibonacci reversed!

Body:
Python, 29 bytes

g=lambda n:n>.7and-~g(n/1.61)

Recursively divides the input by the golden-ratio approximation 1.61 until it's below 0.7, and outputs the number of divisions.

For 0, the code outputs False, which equals 0 in Python. This can be avoided for 2 bytes

g=lambda n:n//.7and 1+g(n/1.61)