How did the chicken cross the road? Cluck cluck. No one knows why the chicken crossed the road, maybe there was a good looking rooster on the other side. But we can figure out how. Write a program, that, left to right, crosses this (or any) "road".

1356 | 1738
3822 | 1424
3527   3718
9809 | 5926
0261 | 1947
7188   4717
6624 | 9836
4055 | 9164
2636   4927
5926 | 1964
3144 | 8254

Your program "crosses" it, moving left to right. You start on any number on the leftmost column you like. From there, you can move to any adjacent character to the right. If you started at the top left corner, 1, you could go to either 3 or 8. Every number you go to, including the starting number, is added to a sum. Spaces do not add to your sum. "|" forces you to move up or down, rather than somewhere to the right. (You CAN'T move forward on this character) Your goal is to get to the other side with the smallest possible sum. Your program must print out the sum at the end, and it must be able to solve any road. Preferably, it could also have input for a road, but it's not required. Your program must print both the path and the sum. Fewest bytes of code wins.

To clarify, you can move diagnally unless you are on a vertical bar. You can only move up and down when you are on a vertical bar.

For a clearer specification of roads, it is basically a string of text (Or an array of columns or rows, should you prefer to think that way) that follows the rules of the characters, and there can't be anything BUT those characters in the road. There can be any number, a space, a bar ("|"), or a newline. If a road was paved by a drunk guy, as in ProgrammerDan's answer, it is still a valid road, and your program must be able to solve such a road. It is not considered a road if it is impossible to get to the other side (For example, there is no way out of a straight line of bars).

Your program is not required to determine if a road is invalid.

Key:
Any number - adds the number to your sum, move forward.
Space - Move forward, nothing is added to your sum.
"|" - Move up or down, nothing is added to your sum.

EDIT:
An example solution, as suggested. I can't make a horribly big one, I can't get on an IDE to solve it for me ATM.

Take this small road:

9191 | 8282
1919 | 2727
5555   5555

The solution would be a path of 1, 1, 1, 1, space, divider, divider, space, space, 2, 2, 2, 2 for a total of 12.

EDIT #2:
The solution to the first road on this question, as determined by Geobits and peoples programs, is 0,2,0,1, , , ,1,4,1,4 for a sum of 13.

Java, 955 bytes
Obviously not going to win any awards, being Java and all, but I love this problem and wanted to throw in my own entry.
Features and limits:

Can support irregular roads (super drunk!) including variable widths, complex lines, etc.
Expects road to be input as parameters on execution; the ungolfed version also supports reading from stdin, but since input method wasn't specified the golfed version expects smallest!
Uses some dynamic programming technique I haven't used in, oh, 6 years or so to efficiently solve in O(n*m) time, where n is rows and m is columns.

Solves from right to left, marking the best direction to take from the current index to the next index.
"lines" are handled by resolving their column, then addressing them if reachable on the next column over. They resolve by storing direction up or down, with the cost of the eventually reachable non-line.

Tracks, but doesn't print (in golf'd version) the starting index of the best solution.

Ok, enough jibba jabba. Golfed version:
class C{public static void main(String[]a){int n=a.length,m=0,i=0,j=0,h=0,p=0,q=0,s=0,t=0,b=-1,c=2147483647,x=0,y=0;char[][]r=new char[n][];char u;for(String k:a){j=k.length();m=(j>m)?j:m;}for(String k:a)r[i++]=java.util.Arrays.copyOf(k.toCharArray(),m);int[][][]d=new int[n][m][2];for(j=m-1;j>=0;j--){for(i=0;i<n;i++){u=r[i][j];p=(u=='\0'||u==' '||u=='|'?0:u-'0');if(j==m-1)d[i][j][1]=p;else{if(u=='|')d[i][j][0]=-1;else{for(h=-1;h<2;h++){x=i+h;y=j+1;if(x>=0&&x<n){if(d[x][y][0]==-1){s=x-1;while(s>=0&&r[s][y]=='|')s--;t=x+1;while(t<n&&r[t][y]=='|')t++;if((s>=0&&t<n&&d[s][y][1]<d[t][y][1])||(s>=0&&t>=n)){t=d[s][y][1];s=4;}else{s=6;t=d[t][y][1];}d[x][y][0]=s;d[x][y][1]=t;}q=d[x][y][1]+p;if(d[i][j][0]==0||q<d[i][j][1]){d[i][j][0]=h+2;d[i][j][1]=q;}}}}}if(j==0&&(b<0||d[i][j][1]<c)){b=i;c=d[i][j][1];}}}String o="";i=b;j=0;while(j<m){u=r[i][j];if(u=='\0')j=m;else{o+=u+",";h=d[i][j][0]-2;if(h>1)i+=h-3;else{i+=h;j++;}}}System.out.println(o+"\b:"+c);}}

As per my habit, github with the ungolfed code.
Solution for "first" road:
$ java C "1356 | 1738" "3822 | 1424" "3527   3718" "9809 | 5926" "0261 | 1947" "7188   4717" "6624 | 9836" "4055 | 9164" "2636   4927" "5926 | 1964" "3144 | 8254"
0,2,0,1, , , ,1,4,1,4:13

Second example:
$ java C "9191 | 8282" "1919 | 2727" "5555   5555"
1,1,1,1, ,|,|, , ,2,2,2,2:12

Brian Tuck's sample:
$ java C "6417443208|153287613" "8540978161|726772300" "7294922506 263609552" "0341937695 498453099" "9417989188 370992778" "2952186385|750207767" "7049868670 756968872" "1961508589|379453595" "0670474005 070712970" "4817414691|670379248" "0297779413|980515509" "6637598208 090265179" "6872950638 767270459" "7375626432 439957105" "1387683792|544956696" "6974831376 545603884" "0949220671|632555651" "3952970630|379291361" "0456363431|275612955" "2973230054|830527885" "5328382365|989887310" "4034587060 614168216" "4487052014|969272974" "5015479667 744253705" "5756698090|621187161" "9444814561|169429694" "7697999461|477558331" "3822442188 206942845" "2787118311|141642208" "2669534759 308252645" "6121516963|554616321" "5509428225|681372307" "6619817314|310054531" "1759758306 453053985" "9356970729|868811209" "4208830142 806643228" "0898841529|102183632" "9692682718|103744380" "5839709581|790845206" "7264919369|982096148"
2,1,0,1,5,1,2,1,1,1, ,1,0,1,2,1,2,3,0,1:26

"Drunkified" Brian's example:

6417443208|153287613
8540978161|726772300
7294922506 263609552
0341937695 498453099
9417989188 370992778
2952186385|750207767
7049868670 756968872
1961508589|379453595
0670474005 070712970
4817414691|670379248
0297779413|980515509
6637598208 090265179
6872950638 767270459
7375626432 439957105
1387683792|544956
697483176 5456034
09492201|6325551
395297030|3792913
 456363431|275612
  73230054|830527885
    8382365|989887310
    4587060 614168216
  87052014|96927297
 50479667 7442537
57566980 | 621187161
944481456 | 169429694
7697999461|477558331
3822442188 206942845
2787118311|141642208
2669534759 308252645
6121516963|554616321
5509428225|681372307
6619817314|310054531
1759758306 453053985
9356970729|868811209
4208830142 806643228
0898841529|102183632
9692682718|103744380
5839709581|790845206
7264919369|982096148

$ java C "6417443208|153287613" "8540978161|726772300" "7294922506 263609552" "0341937695 498453099" "9417989188 370992778" "2952186385|750207767" "7049868670 756968872" "1961508589|379453595" "0670474005 070712970" "4817414691|670379248" "0297779413|980515509" "6637598208 090265179" "6872950638 767270459" "7375626432 439957105" "1387683792|544956" "697483176 5456034" "09492201|6325551" "395297030|3792913" " 456363431|275612" "  73230054|830527885" "    8382365|989887310" "    4587060 614168216" "  87052014|96927297" " 50479667 7442537" "57566980 | 621187161" "944481456 | 169429694" "7697999461|477558331" "3822442188 206942845" "2787118311|141642208" "2669534759 308252645" "6121516963|554616321" "5509428225|681372307" "6619817314|310054531" "1759758306 453053985" "9356970729|868811209" "4208830142 806643228" "0898841529|102183632" "9692682718|103744380" "5839709581|790845206" "7264919369|982096148"
 , , , ,0,5,2,0,1, , , ,1,1,1,3,2:16

Solution visualized:

09492201|6325551
395297030|3792913
\456363431|275612
 \73230054|830527885
  \ 8382365|989887310
   \4\87060 614168216
  87/5--\4|96927\97
 50479667\74425/7
57566980 |\62-/87161
944481456 |\/69429694
7697999461|477558331

Enjoy!
Edit: Now I'm just showing off (two roadways merge! Can he make it?)

948384 | 4288324   324324 | 121323
120390 | 1232133   598732 | 123844
 293009 | 2394023 432099 | 230943
 234882 | 2340909 843893 | 849728
  238984 | 328498984328 | 230949
  509093 | 904389823787 | 439898
   438989 | 3489889344 | 438984
   989789 | 7568945968 | 989455
    568956 | 56985869 | 568956
    988596 | 98569887 | 769865
     769879 | 769078 | 678977
     679856 | 568967 | 658957
      988798 | 8776 | 987979
      987878 | 9899 | 989899
       999889 |    | 989899
       989999 |    | 989999
        989898 |  | 998999
        989999 |  | 999999
         989998 || 899999
         989998 || 998999

Solution:
$ java C "948384 | 4288324   324324 | 121323" "120390 | 1232133   598732 | 123844" " 293009 | 2394023 432099 | 230943" " 234882 | 2340909 843893 | 849728" "  238984 | 328498984328 | 230949" "  509093 | 904389823787 | 439898" "   438989 | 3489889344 | 438984" "   989789 | 7568945968 | 989455" "    568956 | 56985869 | 568956" "    988596 | 98569887 | 769865" "     769879 | 769078 | 678977" "     679856 | 568967 | 658957" "      988798 | 8776 | 987979" "      987878 | 9899 | 989899" "       999889 |    | 989899" "       989999 |    | 989999" "        989898 |  | 998999" "        989999 |  | 999999" "         989998 || 899999" "         989998 || 998999"
 ,2,0,3,0,0, ,|,|, ,|,|, ,|,|, ,|,|, ,|,|, ,|,|, ,|,|, , , , , , , ,|, ,|, ,|, ,|, ,|, ,|, ,|,|, , ,1,0,7,2:15

(bonus: path from ungolfed):
$ java Chicken < test5.txt
best start: 3 cost: 15
  -> 2 -> 0 -> 3 -> 0 -> 0 ->   -> | -> | ->   -> | -> | ->   -> | -> | ->   -> | -> | ->   -> | -> | ->   -> | -> | ->
  -> | -> | ->   ->   ->   ->   ->   ->   ->   -> | ->   -> | ->   -> | ->   -> | ->   -> | ->   -> | ->   -> | -> | ->
  ->   -> 1 -> 0 -> 7 -> 2 -> 15
/ -> - -> - -> \ -> / -> / -> - -> , -> , -> - -> , -> , -> - -> , -> , -> - -> , -> , -> - -> , -> , -> - -> , -> , ->
- -> , -> , -> / -> \ -> - -> - -> - -> / -> / -> ^ -> / -> ^ -> / -> ^ -> / -> ^ -> / -> ^ -> / -> ^ -> / -> , -> , ->
/ -> - -> \ -> \ -> - -> \ -> across

Details on Algorithm
A more complete explanation of the Dynamic Programming technique I employed was requested, so here goes:
I'm using a mark-and-precompute method of solution. It has a proper name, but I've long since forgotten it; perhaps someone else can offer it?
Algorithm:

Starting at the right-most column and progressing to the left, compute the following about each cell in the column:

The summation of lowest cost movement, defined as current cell cost + lowest cost cell reachable in the next column
The movement action to take to achieve this lowest cost, as simply a valid move from this cell to another single cell.

Pipes are deferred. To resolve a pipe, you need to have the full column computed, so we don't compute pipes until the next column.

When determining the lowest cost of a cell to the left of a pipe, we first compute the best direction to travel along the pipe -- it will always resolve to either up, or down, so we compute it once.
We then store, as with all other cells, the best cost (defined as the cost of the cell we reach by travelling either up or down on the pipe) and the direction to travel to reach it.

Notes:
That's it. We scan from top to bottom, right to left, once; the only cells touched (potentially) more then once are pipes, however, each pipe is only "solved" once, keeping us within our O(m*n) window.
To handle "odd" map sizes, I chose to simply pre-scan and normalize lengths of rows by padding with null characters. Null characters count as "zero cost" moves same as pipes and spaces. Then, in printing the solution, I stop printing costs or moves when either the edge of the normalized road is reached, or a null character is reached.
The beauty of this algorithm is it's very simple, applies the same rules to every cell, producing a full solution by solving O(m*n) sub-problems, and in terms of speed is rather fast. It does trade off memory, creating effectively two copies in memory of the roadway map, the first to store "best cost" data and the second to store "best move" data per cell; this is typical for dynamic programming.


reach catch when everything in the try block is caught already This is limited to Java and C# by the syntax I guess.

In this programming puzzle, you are to produce Exceptions that can be caught but are thrown again at the end of the catch block.

try
{
    while(true)
        try
        {
            // you are only allowed to modify code between this try { } brackets
        }
        catch(Exception ex2) {  }
}
catch(Exception ex1)
{
    // your goal is to reach this catch block by modifying the code ...
    // in the inner try block above
    // You win if you reach this part and execute on of the following code lines
    Console.WriteLine("You won!"); // for C#
    // Or
    System.out.println("You won!"); // for Java
}

You can freely put code before and after this snippet.

The shortest code to reach the outer catch block wins.

C#, 46 (88 including boilerplate)

using System;class P{static void Main(){
        try
        {
            while(true)
                try
                {
                    System.Threading.Thread.CurrentThread.Abort();
                }
                catch(Exception ex2) {  }
        }
        catch(Exception ex1)
        {
            // your goal is to reach this catch block by modifying the code ...
            // in the inner try block above
            // You win if you reach this part and execute on of the following code lines
            Console.WriteLine("You won!"); // for C#
        }
}}

The Abort() method raises a ThreadAbortException, which is a special exception that is automatically rethrown at the end of each catch block (unless Thread.ResetAbort() is called).


Tips for golfing in TI-BASIC What general tips do you have for golfing in TI-BASIC for the TI-83/84+ series calculators? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to TI-BASIC (e.g. "remove comments" is not an answer).

Please post one tip per answer.

Your calculator is pretty smart at inferring the end of lines for you, and thus you can omit quite a few characters.

:Disp "HELLO WORLD    //is the same as...
:Disp "HELLO WORLD"

For( loops have a syntax like this - For(variable, start, end, increment), but you can omit the increment and it will use 1:

:For(A,1,5     //is the same as...
:For(A,1,5,1)

and you can omit ending parentheses (at the end of lines) across the board:

:Output(1,1,A
:int(A
:round(A
etc.

Tested on my TI-84 Silver Edition calculator

If you think this is more than one idea (inferring endings) then I'll split them up


St. Patrick's Day Challenge! Seeing as its St. Patrick's day, I thought I would have a little challenge

Your task is to write a program draws a clover in any way possible. Each leaf has to be symmetrical, and the user has to input the number of leaves that they want on the clover. It then must be drawn. This has to be generated. You cannot just load an image or have ASCII art saved as a variable. However using modules like turtle to generate (and draw is included under generate) are fine.

You can use any language. This is a code-golf so the shortest answer wins.

Begin! Happy St Patrick's Day!

Just for reference, here is an example of a 3 leaf clover

Just for DavidCarraher

Mathematica - 106 bytes

c=RegionPlot[x^2+y^2<Abs@Sin[#x~ArcTan~y/2]||x>0&&y^2<.001,{x,-1,1},{y,-1,1},Frame->0>1,PlotStyle->Green]&

Ungolfed version:

c[leaves_] := (
    angle = ArcTan[x,y];
    RegionPlot[
        x^2 + y^2 < Abs[Sin[leaves*angle/2]]
        || x > 0 && y^2 < .001
      , {x,-1,1}
      , {y,-1,1}
      , Frame -> False, PlotStyle -> Green
    ]);

Here are the outputs for c[3] through c[6].

At the cost of another 7 bytes you can improve the colour (using PlotStyle->Darker@Green or PlotStyle->Hue[.3,1,.7] instead), and for another 15 bytes you can remove some of the sampling artifacts (using an additional option ,PlotPoints->90), giving a total of 128 bytes for these beauties:

The braces and commes in those pictures are not produced by c, but just by how I output them to fit them all in one row.

Lastly, here is an attempt at somewhat neater shading. I didn't even bother golfing this down further, the option names are just too long. I'm not even sure I'm too pleased with the result, but I thought I'd post it anyway. This is 188 bytes as it stands:

c=RegionPlot[x^2+y^2<Abs@Sin[(l=#)x~(a=ArcTan)~y/2]||x>0&&y^2<.001,{x,-1,1},{y,-1,1},Frame->0>1,PlotPoints->90,ColorFunction->(Hue[.3,1,.5+.2Sin[.5l#~a~#2]^8]&),ColorFunctionScaling->0>1]&


printf-style string formatting Challenge

Write a function that implements C printf-style string formatting.

Rules

You must implement at least %%, %c, %s, %d and %f.
You must not use a built-in string formatting method.
You must not run external programs or connect to the Internet from your program.
It's up to you to decide how to handle invalid input, but your program must not terminate abnormally.
You should write a variadic function if possible.

  The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED",  "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.

APL (73)

{⊃,/,⌿↑(⊂2∘↓¨Z⊂G),⊂{'c'0≡⍵,∊⊃⍺:⎕UCS⍺⋄⍕⍺}/⍵,⍪⌷∘G¨1↓1+(Z←G='%')/⍳⍴G←'%!',⍺}

Some tests:

      'a:%c b:%s c:%d'{⊃,/,⌿↑(⊂2∘↓¨Z⊂G),⊂{'c'0≡⍵,∊⊃⍺:⎕UCS⍺⋄⍕⍺}/⍵,⍪⌷∘G¨1↓1+(Z←G='%')/⍳⍴G←'%!',⍺} 65 'foo' 67
a:A b:foo c:67

      printf←{⊃,/,⌿↑(⊂2∘↓¨Z⊂G),⊂{'c'0≡⍵,∊⊃⍺:⎕UCS⍺⋄⍕⍺}/⍵,⍪⌷∘G¨1↓1+(Z←G='%')/⍳⍴G←'%!',⍺}
      '1:%s 2:%s 3:%d 4:%c 5:%c' printf 'foo' 'bar' 100 110 'z'
1:foo 2:bar 3:100 4:n 5:z
      'The %s brown %c%c%c jumps over the %s dog.' printf 'quick' 102 111 'x' 'lazy'
The quick brown fox jumps over the lazy dog.

Explanation:

G←'%!',⍺: prefix a dummy specifier to the string (for easier processing)
(Z←G='%')/⍳⍴G: find the indices of all the % characters in the string; also store a bitmask in Z
⌷∘G¨1↓1+: select all the characters next to the %s, and drop the dummy.
⍵,⍪: match up each specifier with its value from the right argument.
{...}/: run the following function on each pair:

'c'0≡⍵,∊⊃⍺: if the argument is a number and the specifier is c:
:⎕UCS⍺: then return the unicode value of the argument,
⋄⍕⍺: otherwise, return the string representation of the argument.

⊂: enclose
⊂2∘↓¨Z⊂G: split the string on the %s and then remove the first two characters of each substring (this is where the dummy comes in), and enclose the result of that.
↑: make a matrix out of the two enclosed arrays, matching up each substring with the value that should follow it.
,⌿: join each substring with its value.
⊃,/: then join the resulting strings.


Shortest Hello World program with no semi colons I recently saw some questions on SO that asked if you could make a Hello World program without using any semi colons using C#. The challenge is to do this again, but in the shortest  amount of code possible!

C# 85 chars
class H{static void Main(){if(System.Console.Out.WriteAsync("Hello, world!")is H){}}}


Animate a Rotating Lissajous Figure Entries for this challenge will display an animated rotating Lissajous figure.  The appearance of 3d rotation occurs as the x parameter is successively phase-shifted in each frame.
Input:
The a and b parameters (as per the wikipedia article) will be specified at the command line, or read from stdin.
Output:
This is ascii-art, so output will be displayed in a terminal emulator window or equivalent.  Output size may be hardcoded, but the Lissajous figure must be at least big enough to fill a 80x24 window.
The animation frame rate will be approximately 50fps.  Sleeping for 20ms between each frame is fine, as long as the time to calculate each frame is small compared with the fixed sleep time.  If your choice of language cannot calculate quick enough on your chosen platform, then you'll have to calculate the time to sleep dynamically.
Each frame will not be displayed until all calculation for that frame is complete.  There is no need to clear the screen between each frame.
The figure will make a full 2*Pi rotation approximately every 4 seconds.
For each frame, a full closed curve must be generated.  At least 1000 points must be calculated along the curve.  Line-drawing in between points is not necessary.
Points of the curve will be plotted as # characters.  The rest of the display area will be blank/whitespace.
This is code-golf, so the shortest answer in bytes (deemed acceptable by me) will be the accepted winner one week after this posting.

Ungolfed reference answer.

Perl - 177

while($d+=.1){print"\e[H\e[2J";$a=0;while(($a+=.01)<4*atan2 1,0){$x=$==40+40*cos$d+$a*$ARGV[0];$y=$==13+13*sin$d+$a*$ARGV[1];print"\e[$y;$x"."H#";}print$/;select($v,$v,$v,.03);}

The coefficients are passed via arguments. The above gif is produced from perl % 2 3


Find self-locating strings in a number Based on this Numberphile video

A self-locating string is a number (or set of numbers) in a decimal expansion which corresponds to its location, from the start of the decimal.

For example, take the number:

.2734126393112

Here, we can identify certain items quickly, e.g:

.27 _3_ _4_ 1263 _9_ 3112

There are a few more complex cases in here though, too. For instance, the numbers 11 and 12 both appear starting in their respective positions:

.2734126393112
 123456789ABCD
           ^
           11

            ^
            12

So the list of self-locating strings in this case would be [3, 4, 9, 11, 12], as even though some of them overlap, they both start in the correct places. If we sum these up, we get 39, or the self-reference index (SRI) of this terminating decimal.

Input

A terminating decimal, either an array of digits (after the point) or a decimal type with 0. at the start/..

Output

The SRI of the input number.

Rules

In the case that there are no self-referential numbers, the SRI is 0. This must be returned/printed, as opposed to exiting or returning undefined.
The decimal expansion can be assumed to terminate, and will be no more than 128 digits in length.
The counting of the indexes should be 1-based, e.g the first decimal is at position 1, etc.
Standard I/O rules + standard loopholes apply.
This is code-golf, so shortest answer in bytes wins

Test cases

0.1207641728 -> 3
.12345678910 -> 55
0.1234567890112 -> 68
.0 -> 0
0.654321 -> 0
.54321 -> 3

APL (Dyalog Extended), 16 bytes

+/⍬∘⍋(⍸⊣⊃¨⍕⍛⍷¨)⊂

Try it online!

Takes a string of digits.

How it works

+/⍬∘⍋(⍸⊣⊃¨⍕⍛⍷¨)⊂  ⍝ Input: character vector of digits
  ⍬∘⍋             ⍝ X←Array of 1-based indices
     (    ⍕⍛ ¨)   ⍝ Stringify each of X
     (      ⍷¨)⊂  ⍝ And for each of above, build a boolean array where
                  ⍝   substring matches are marked as 1
                  ⍝ e.g. '10'⍷'10428104' is [1 0 0 0 0 1 0 0]
       ⊣⊃¨        ⍝ Extract X-th indices from each of above
      ⍸           ⍝ Convert ones to its 1-based locations
+/                ⍝ Sum


Convert a repeated decimal to a fraction This question doesn't need to apply to just terminating decimals - repeating decimals can also be converted to fractions via an algorithm.

Your task is to make a program that takes a repeated decimal as input, and output the corresponding numerator and denominator (in lowest terms) that produces that decimal expansion. Fractions greater than 1 should be represented as improper fractions like 9/5. You can assume that input will be positive.

The repeated decimal will be given in this format:

5.3.87

with everything after the second dot repeated, like this:

5.3878787878787...

Your program will output two integers representing the numerator and denominator, separated by a slash (or the equivalent form in your language if you do not output plain text):

889/165

Note that terminating decimals will have nothing after the second dot, and decimals with no non-repeating decimal portion will have nothing between the two dots.

Test cases

These test cases cover all of the required corner cases:

0..3 = 1/3
0.0.3 = 1/30
0.00.3 = 1/300
0.6875. = 11/16
1.8. = 9/5
2.. = 2/1
5..09 = 56/11
0.1.6 = 1/6
2..142857 = 15/7
0.01041.6 = 1/96
0.2.283950617 = 37/162
0.000000.1 = 1/9000000
0..9 = 1/1
0.0.9 = 1/10
0.24.9 = 1/4

If you wish, you can also assume that fractions without integer parts have nothing to the left of the first dot. You can test that with these optional test cases:

.25. = 1/4
.1.6 = 1/6
..09 = 1/11
.. = 0/1

Perl 6 (93 101 100 80 68 66 bytes)

$/=split ".",get;say ($0+($1+$2/(9 x$2.comb||1))/10**$1.comb).nude

The size was increased to handle nothing, instead of just failing. Mouq proposed to use $/, so it's now being used, and the code is 20 bytes shorter. Ayiko proposed replacing / with , so the code is even shorter (by 12 bytes). Then Mouq proposed replacing chars with comb (in numeric context, they are identical, because list of characters after conversion to number is number of characters).

Sample output:

$ perl6 script.p6
5.3.87
889 165
$ perl6 script.p6
2.0.0
2 1
$ perl6 script.p6
0..3
1 3
$ perl6 script.p6
0.0.3
1 30
$ perl6 script.p6
0.0.0
0 1
$ perl6 script.p6
0.1.6
1 6
$ perl6 script.p6
0.01041.6
1 96
$ perl6 script.p6
0.2.283950617
37 162
$ perl6 script.p6
123.456.789
41111111 333000


Where does the spaceship go? Based on an idea suggested by Zgarb.

A spaceship is moving around a regular 3D grid. The cells of the grid are indexed with integers in a right-handed coordinate system, xyz. The spaceship starts at the origin, pointing along the positive x axis, with the positive z axis pointing upwards.

The spaceship will fly along a trajectory defined by a non-empty sequence of movements. Each movement is either F(orward) which makes the spaceship move one cell in the direction its facing, or one of the six rotations UDLRlr. These corresponds to pitch, yaw and roll as follows:

Thanks to Zgarb for creating the diagram.

Up and Down change the pitch of the spaceship by 90 degrees (where the direction corresponds to the movement of the spaceship's nose).
Left and Right change the yaw of the spaceship by 90 degrees. They are just regular left and right turns.
left and right are 90 degree rolling movements, where the direction indicates which wing moves downwards.

Note that these should always be interpreted relative to the spaceship so the relevant axes rotate along with it.

In mathematical terms, the spaceship is initially at position (0, 0, 0), pointing along the (1, 0, 0) vector, with (0, 0, 1) pointing upwards. The rotations correspond to the following matrices applied to the coordinate system:

U = ( 0  0 -1     D = ( 0  0  1
      0  1  0           0  1  0
      1  0  0 )        -1  0  0 )

L = ( 0 -1  0     R = ( 0  1  0
      1  0  0          -1  0  0
      0  0  1 )         0  0  1 )

l = ( 1  0  0     r = ( 1  0  0
      0  0  1           0  0 -1
      0 -1  0 )         0  1  0 )

You should output the final position of the spaceship as three integers x, y, z. Output may be three separate integers or a list or string containing them. They may be in any consistent order as long as you specify it.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

Standard code-golf rules apply.

Test Cases

F                                                   => (1, 0, 0)
FDDF                                                => (0, 0, 0)
FDDDF                                               => (1, 0, 1)
LrDDlURRrr                                          => (0, 0, 0)
UFLrRFLRLR                                          => (1, 0, 1)
FFrlFULULF                                          => (3, 0, -1)
LLFRLFDFFD                                          => (-2, 0, -2)
FrrLFLFrDLRFrLLFrFrRRFFFLRlFFLFFRFFLFlFFFlUFDFDrFF  => (1, 5, 7)
FUrRLDDlUDDlFlFFFDFrDrLrlUUrFlFFllRLlLlFFLrUFlRlFF  => (8, 2, 2)
FFLrlFLRFFFRFrFFFRFFRrFFFDDLFFURlrRFFFlrRFFlDlFFFU  => (1, 2, -2)
FLULFLFDURDUFFFLUlFlUFLFRrlDRFFFLFUFrFllFULUFFDRFF  => (-3, -2, -3)

Worked example

Here are the intermediate steps of the UFLrRFLRLR test case. Here, all intermediate coordinates and direction vectors are given in the initial, global coordinate system (as opposed to one local to the spaceship):

Cmd.  Position    Forward     Up
      ( 0, 0, 0)  ( 1, 0, 0)  ( 0, 0, 1)
U     ( 0, 0, 0)  ( 0, 0, 1)  (-1, 0, 0)
F     ( 0, 0, 1)  ( 0, 0, 1)  (-1, 0, 0)
L     ( 0, 0, 1)  ( 0, 1, 0)  (-1, 0, 0)
r     ( 0, 0, 1)  ( 0, 1, 0)  ( 0, 0, 1)
R     ( 0, 0, 1)  ( 1, 0, 0)  ( 0, 0, 1)
F     ( 1, 0, 1)  ( 1, 0, 0)  ( 0, 0, 1)
L     ( 1, 0, 1)  ( 0, 1, 0)  ( 0, 0, 1)
R     ( 1, 0, 1)  ( 1, 0, 0)  ( 0, 0, 1)
L     ( 1, 0, 1)  ( 0, 1, 0)  ( 0, 0, 1)
R     ( 1, 0, 1)  ( 1, 0, 0)  ( 0, 0, 1)

MATL, 76 75 bytes
FFF!3Xyj"FFT_FTFv4BvtFT_YStTF_YS3:"3$y!]6$Xh@'ULlDRr'4#mt?X)Y*}xxt1Z)b+w]]x

This works in current version (12.1.1) of the language.
Edit (April 4, 2016): The behaviour of function v has changed in release 15.0.0 of the language. To make the above code run, remove the first v and replace the second 3$v. The following link includes this modification.
Try it online!
Explanation
The state of the ship can be described in terms of two variables:

position: 3x1 vector
orientation: 3x3 matrix with the accumulated rotation, where "accumulated" means repeated matrix product.

A third variable would be the direction in which the ship is facing, but that's not needed, because it can be obtained as the initial direction (column vector [1;0;0]) times the current orientation; that is, the first column of the orientation.
These two state variables are kept on the stack, and are updated with each letter. Each of the letters ULlDRr multiplies the orientation matrix by one of the six rotation matrices to update the orientation. Letter F adds the current position plus the first column of the orientation matrix.
The six rotation matrices are created as follows: first is introduced directly; second and third are circular shifts of the previous one; and the remaining three are transposed versions of the others.
FFF!             % 3x1 vector [0;0;0]: initial position
3Xy              % 3x3 identity matrix: initial orientation
j                % input string
"                % for-each character in that string
  FFT_FTFv4Bv    %   rotation matrix for U: defined directly
  tFT_YS         %   rotation matrix for L: U circularly shifted to the left
  tTF_YS         %   rotation matrix for l: L circularly shifted down
  3:"            %   repeat three times
    3$y!         %     copy third matrix from top and transpose
  ]              %   end loop. This creates rotation matrices for D, R, r
  6$Xh           %   pack the 6 matrices in a cell array
  @              %   push current character from the input string
  'ULlDRr'4#m    %   this gives an index 0 for F, 1 for U, 2 for L, ..., 6 for r
  t?             %   if non-zero: update orientation
    X)           %     pick corresponding rotation matrix
    Y*           %     matrix product
  }              %   else: update position
    xx           %     delete twice (index and rotation matrix are not used here)
    t1Z)         %     duplicate orientation matrix and take its first column
    b+           %     move position vector to top and add
    w            %     swap the two top-most elements in stack
  ]              %   end if
]                % end for-each
x                % delete orientation matrix
                 % implicitly display position vector


Sort digits by their first occurrence in pi Given a non-negative number n, sort the digits of n by their first occurrence in pi.

Input can be taken via function cli argument, or STDIN and as a string, char[] or integer. You may output via return value, exit status or STDOUT.

Python 3, 40 39 bytes

1 byte thanks to Jonathan Allan.

lambda s:sorted(s,key="145926870".find)

Try it online!


Print all odd numbers from 0 to 100000 My teacher gave me a simple problem which I should solve with a code tiny as possible. I should print all odd numbers from 0 to 100000 into a HTML document using javascript.

for(var y = 0; y < 100000; y++){
if(!(y % 2 == 0)){
document.write(y + " ");
}
};

Is it possible to do that shorter?

JavaScript, 38 bytes

Yet another way to do this, shortest of all.

This supposedly prints each number on a new line using \n. Now as the data is being written to an HTML document, \n is not of any use and the numbers appear to be separated by space only.

for(i=1;i<1e5;i+=2)document.writeln(i)


Cats go Meow, Cows go Moo Everyone knows that cats go meow, but what many don't realise is that caaaats go meeeeoooow. In fact, the length of the vowel sounds that the cat makes are dependant on the length of the vowel with which you address it.

In the same way, cows go moo, but coooows go moooooooo

Challenge

You are to write a program that takes as input, a word meaning cat, and a word meaning cow, determine the number of main vowels, and print one of the following strings, as appropriate:

C[]ts go M[]w
C[]ws go M[]

Where [] stands for the vowels, according to the following rules:

The number of e's and o's in "Meow" must both match the number of vowels found in the input word.
The number of o's in "Moo" must be double the number of vowels found in the input word.

The program must recognise the input words cat and cow. Input may use any capitalisation that is most convenient, but the output must be capitalised exactly as shown above.

Retina, 57 49 44 43 41 bytes

So close... :) Pyth...

.(.+).
$0s go M$1$1
+`aa(\w*$)
e$1ow
wo
o

Try it online.

Expects input to be capitalised like Caaat or Coooow.

Explanation

.(.+).
$0s go M$1$1

The regex matches the entire input, and captures the vowels in group 1 (we don't need anchors, because the match cannot fail and will greedily match the entire input). The substitution writes back that input, and appends s go M, followed by twice the vowels. For inputs Caaat and Coooow, we get:

Caaats go Maaaaaa
Coooows go Moooooooo

The output for cows is already correct. We just need to do something about those cats.

+`aa(\w*$)
e$1ow

The + tells Retina to repeat this stage as often as possible. The regex matches two as in the last part of the string (we ensure this with the $ anchor, so that we don't replace things inside Caaats). This will essentially match everything after M, as long as that part still has as. The two as are removed and the entire suffix after it is wrapped in e...ow:

Caaats go Meaaaaow
Caaats go Meeaaowow
Caaats go Meeeowowow

Finally, there are two many ws in the result, so we remove those that precede an o (to make sure we're not messing up the w in Coooows):

wo
o

And we're left with:

Caaats go Meeeooow


Build a MU puzzle solver The MU puzzle is a puzzle in which you find out whether you can turn MI into MU given the following operations:

If your string ends in I, you may add a U to the end. (e.g. MI -> MIU)
If your string begins with M, you may append a copy of the part after M to the string.
(e.g. MII -> MIIII)
If your string contains three consecutive I's, you may change them into a U.
(e.g. MIII -> MU)
If your string contains two consecutive U's, you may delete them. (e.g. MUUU -> MU).

Your task is to build a program that determines whether this is doable for any start and finish strings.

Your program will take two strings as input. Each string will consist of the following:

one M.
a string of up to twenty-nine I's and U's.

Your program will then return true (or your programming language's representation thereof/YPLRT) if the second string is reachable from the first string, and false (or YPLRT) if it is not.

Example inputs and outputs:

MI  MII
true

MI  MU
false

MIIIIU  MI
true

The shortest code in any language to do this wins.

SWI Prolog, 183 characters

m(A,A).
m([i],[i,u]).
m([i,i,i|T],B):-m([u|T],B).
m([u,u|T],B):-m(T,B).
n([m|A],[m|B]):-(m(A,B);append(A,A,X),m(X,B)).
n(A,B):-m(A,B).
s(A,B):-atom_chars(A,X),atom_chars(B,Y),n(X,Y).

How about some Prolog, (since nobody has answered in 6 months).
To run, just use "s(mi,mu)."  The code breaks up atoms into chars, then searches for the solution.


Diamondize Some Text Given an input string of length 2 or longer consisting solely of alphabetical characters [A-Z] or [a-z] (your choice if they're all uppercase or all lowercase), output a continuous string of characters forming a double diamond pattern.

The input string starts on the center line and extends down-and-right at a diagonal until the end of the input string is reached. Then, the pattern continues up-and-right at a diagonal until you're as far above the center line as the length of the input string minus 1. Continue down-and-right back to the center line, then down-and-left, then up-and-left (going "behind" the center character), and finally down-and-left back to the starting character.

That's a little wordy, and it's better demonstrated by some examples:

"YOU"
  U   Y
 Y O U O
Y   O   U
 O Y U Y
  U   O

  ^   ^
 ↙ ↖ ↗ ↘
↘   ↗   >
 ↘ ↗ ↖ ↙
  V   V

See how the YOU starts at the center line and follows down-and-right, then up-and-right, etc., until it loops back to the beginning. Note especially how the Y on the up-and-left portion is "behind" the O and therefore not shown.

Some further examples:

"HI"
 I I
H H H
 I I

"TEST"
   E     E
  S T   T S
 T   T T   T
T     S     T
 E   E E   E
  S T   T S
   T     T

"HELLO"
    L       L
   O L     E L
  H   E   H   O
 E     H O     H
H       L       E
 E     L L     L
  L   E   L   L
   L H     E O
    O       H

Input and output can be given by any convenient method.
The input is guaranteed to be at least two letters long (i.e., you'll never receive "" as input).
You can print it to STDOUT or return it as a function result.
Either a full program or a function are acceptable.
Any amount of extraneous whitespace is acceptable, so long as the characters line up appropriately (e.g., feel free to pad as a rectangle).
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Charcoal, 17 bytes

ＧＨ<↗↘>↖↙ＬθθＧＨ<Ｌθθ

Try it online! Link is to verbose version of code. Explanation:

ＧＨ

Draw along a path.

<↗↘>↖↙

Draw in the directions ↘↗↗↘↙↖↖↙ (the < and > are shorthands for those two pairs, but the other pairs don't have shorthands.)

Ｌθ

Each path segment has the same length, including the ends, of the length of the input.

θ

Use the input as the text to be written along the path.

ＧＨ<Ｌθθ

Print the first two parts of the path again so that the middle character is correct.


Like a path-segment; touched for the very first time Given an ordered list of 2 or more 2D cartesian points, output a truthy value if either the path touches itself or self-intersects; otherwise output a falsy value if it does not touch itself or self-intersect.
You may assume that consecutive points in the list are distinct.
Examples:
(0,0), (1,0) -> falsey
(0,0), (1,0), (0,0) -> truthy
(0,0), (1,0), (1,1), (0,0) -> truthy
(0,0), (2,0), (1,1), (1,-1) -> truthy
(0,0), (10,0), (0,1), (10,1), (0,2), (10,2) -> falsey

Note all the co-ordinates I gave here are integers.  You may support co-ordinate inputs of whatever you like out of {integer, decimal, rational, floating-point, ...}.  But your implementations calculations must give the correct answers for any inputs given.

Python 2, 315 309 298 382 380 372 bytes

s=sorted
w=lambda(x,y),(X,Y),(z,w):(X-x)*(w-y)-(z-x)*(Y-y)
def I(a,b):p,q=s(a);P,Q=s(b);n,N,m,M=w(p,q,P),w(p,q,Q),w(P,Q,p),w(P,Q,q);return(q>=P)*(Q>=p)if{n,N,m,M}=={0}else(b[1]!=a[0])*(n*N<=0>=m*M)
def f(l):
 i=0
 while i<len(l)-2:
	x=l[i:i+3];i+=1
	if w(*x)==0and s(x)==x:l.pop(i);i-=1
 L=zip(l,l[1:]);return any(I(*l)for l in[(k,x)for i,k in enumerate(L)for x in L[:i]])

Try it online!

Uses the algorithm from here, combined with this SO answer for collinear segments.

Edit: Fixed for line segments continuing in the same direction (eg (0,0),(1,0),(2,0)) by removing the middle point, (resulting in (0,0),(2,0)).


Compute the Eulerian number The Eulerian number A(n, m) is the number of permutations of [1, 2, ..., n] in which exactly m elements are greater than the previous element. These are also called rises. For example, if n = 3, there are 3! = 6 permutations of [1, 2, 3]

1 2 3
 < <  2 elements are greater than the previous

1 3 2
 < >  1 ...

2 1 3
 > <  1 ...

2 3 1
 < >  1 ...

3 1 2
 > <  1 ...

3 2 1
 > >  0 ...

So the outputs for A(3, m) for m in [0, 1, 2, 3] will be

A(3, 0) = 1
A(3, 1) = 4
A(3, 2) = 1
A(3, 3) = 0

Also, this is the OEIS sequence A173018.

Rules

This is code-golf so the shortest code wins.
The input n will be a nonnegative integer and m will be a integer in the range [0, 1, ..., n].

Test Cases

n   m   A(n, m)
0   0   1
1   0   1
1   1   0
2   0   1
2   1   1
2   2   0
3   0   1
3   1   4
3   2   1
3   3   0
4   0   1
4   1   11
4   2   11
4   3   1
4   4   0
5   1   26
7   4   1191
9   5   88234
10  5   1310354
10  7   47840
10  10  0
12  2   478271
15  6   311387598411
17  1   131054
20  16  1026509354985
42  42  0

Jelly, 8 bytes

Œ!Z>2\Sċ

Try it online! (takes a while) or verify the smaller test cases.

How it works

Œ!Z>2\Sċ  Main link. Arguments: n, m

Œ!        Generate the matrix of all permutations of [1, ..., n].
  Z       Zip/transpose, placing the permutations in the columns.
   >2\    Compare columns pairwise with vectorizing greater-than.
          This generates a 1 in the column for each rise in that permutation.
      S   Compute the vectorizing sum of the columns, counting the number of rises.
       ċ  Count how many times m appears in the computed counts.


Generate unique non-sequential string of length n without memory of previously generated strings Scenario:

Imagine a situation where you wish to share a unique alphanumeric code. Perhaps it is a one-time-use coupon code you hand write on business cards, or some other scenario where it is desirable to have a code where mis-keying the entry is unlikely to produce valid result and the another valid code is not readily guessed.

However, when you are issuing these codes you do not have access to the list of codes that have already been issued. Rather, you know only how many have been issued before.

Challenge:

Write a function that generates a unique string of length n, subject to the following constraints:

Available Characters: Each character in resultant string shall be from a configurable list of allowed values, which may be "hard-coded" into the algorithm.

Sample List: A, B, C, D, E, F, G, H, J, K, L, M, N, P, Q, R, S, T, U, V, W, X, Z, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 (A-Z and 0-9, omitting "I" and "J")

Configurable Length Output: The length n of the generated string shall be configurable within the algorithm, for n<=8.
Input: A seed is available (unique sequential positive integer >=1 and up to 10 digits)
Stateless: The algorithm has no memory of previously generated strings (no database calls)
Repeatable: The same seed shall yield the same result
Unordered Output: Sequential seed values shall not generate strings in any obvious order (that is to say, results should superficially "appear" random)

For example, 1:"AAAA", 2:"AAAB", 3:"AAAC", ... would NOT qualify, while 1:"RR8L", 2:"1D9R", 3:"TXP3", ... is on the right track.
Note: While this criterion is admittedly subjective, "degree of randomness" is not intended to be the core aspect of this function. Given the Popularity Contest format, I'll leave it up to the community to decide whether a pattern is too obvious.

Unique Output: String shall be unique, at least within limitations of available characters and requested string length. Therefore, each possible permutation is to be used exactly once before any combination may be reused.

For example, if configured to generate a string of length n=5 and the available characters include A-Z and 0-9 except for "O", "I" (34 possible characters), then the string may not repeat between seed>=1 and seed<=45,435,424.
However, if length n=4 with 34 available characters, then the same string need only be unique on seed>=1 and seed<=1,336,336

Winning Criteria:

Popularity Contest - Submission with the most upvotes will be selected as the winner no sooner than two weeks after the first valid solution. Please upvote any and all submissions you feel adequately meet the above criteria.

C(++) - we don't need no friggin' primes

The problem is to generate a different permutation of n characters taken from an a size alphabet for each seed value.

There are an such permutations, and they can be represented as values of a n digits number in base a.

The number of bits necessary to represent all these values is log2(an), rounded up.

We have at most 8 characters per code, and the alphabet contains at most 256 characters, so a 64 bits word is just what we need to cover all possible codes with all possible alphabets.

Now we just need something that maps all possible 232 seed values to the possible range of code values (and looks random enough).

I settled for a basic 32 bits reversal, which gives highest variability for low seed values.

If the possible codes range is smaller than the seed's, there will be duplicates anyway, and the codes will be like the n first digits of a greater number.

If the 232 seed values are not enough to cover all code values, the scrambled seed is extended to the smallest power of two inferior to code max value, by injecting 0s in the lower bits.

This should spread the range of code values while guaranteeing no duplicates.
However, the last digit will have a slightly lower frequency due to the rounding to a power of 2.
If alphabet size is much greater than 2, the difference will be hardly noticeable.

The scrambled seed is then converted as a number in base a, the digits being the symbols of the alphabet.

A few (pseudo) random thoughts

The big weakness of this method is that it won't work well with alphabets whose size is a power of two. The apparent randomness is due to the non-integer number of bits needed to encode a digit.

On second thought maybe we do need some friggin primes after all...

At any rate, even the most magnificent pseudo-random repartition is useless as far as data protection is concerned, since the encryption method is stateless and could be easily cracked by brute-force.

The code

I used the excellent bit shuffling generator of Mr. Jasper Neumann to produce the bit reverser, though other solutions are possible.

I compiled with g++4.8 under MinGW/Win7, but the code is nothing but glorified C and should work with any C++ compiler.

#include <cstdlib> // atoi
#include <cstdio>  // printf
#include <cmath>   // pow

#define Alphabet "ABCDEFGHKLMNOPQRSTUVWXYZ0123456789"
#define Length 8

unsigned bit_permute_step_simple(unsigned x, unsigned m, unsigned shift)
{
  return ((x & m) << shift) | ((x >> shift) & m);
}

unsigned shuffle (unsigned x)
{
    x = bit_permute_step_simple(x, 0x55555555, 1);  // Bit index complement 0
    x = bit_permute_step_simple(x, 0x33333333, 2);  // Bit index complement 1
    x = bit_permute_step_simple(x, 0x0f0f0f0f, 4);  // Bit index complement 2
    x = bit_permute_step_simple(x, 0x00ff00ff, 8);  // Bit index complement 3
    x = bit_permute_step_simple(x, 0x0000ffff, 16);  // Bit index complement 4
    return x;
}

#define Base (sizeof(Alphabet)-1)
typedef char Code[Length+1];

void gen_code (unsigned seed, Code code)
{
    // shuffle seed bits (the inversion is to avoid zero value for seed = 0)
    unsigned long long scrambled = shuffle(~seed);

    // if maximal code size is less than seed max value, there will be duplicates anyway
    int extra_bits = floor(Length * log(Base)/log(2)) - 32;
    if (extra_bits > 0) scrambled <<= extra_bits;

    // basic base conversion.
    // The last code digit might have a slightly lower frequency than others
    int i;
    for (i = 0 ; i != Length ; i++)
    {
        int digit = scrambled % Base;
        code[i] = Alphabet[digit];
        scrambled /= Base;
    }
    code[i] = '\0';
}

int main (int argc, char * argv[])
{
    if (argc != 2) exit(-1);
    unsigned seedm = atoi(argv[1]);
    Code code;

    for (unsigned seed = 0 ; seed != seedm ; seed++)
    {
        gen_code (seed, code);
        printf ("code (%u) = %s\n", seed, code);
    }

    return 0;
}

The main() prints a specified number of codes for consecutive seeds.

Sample output:

n=8, alphabet = ABCDEFGHKLMNOPQRSTUVWXYZ0123456789

code (0) = 215GVK7B
code (1) = MPPT46CX
code (2) = 4AF2E28Y
code (3) = GLGGAS6W
code (4) = U3MSPN2Y
code (5) = CR42Y97H
code (6) = WCWB943L
code (7) = CZW2XAAB
code (8) = UBHMSV6C
code (9) = CZ0W1HCY
code (10) = WMS5BD8Z
code (11) = 8UTL725X
code (12) = MDYVMY1Z
code (13) = 40F6VM7K
code (14) = OO7E6F3M
code (15) = U5L28BA5
code (16) = 08GMUH56
code (17) = KW0W35AS
code (18) = 2HS5D16T
code (19) = ESTL9Q4R

n=4, alphabet = ABCDE

code (0) = AEBD
code (1) = CEAE
code (2) = BEDD
code (3) = DECE
code (4) = DBAB
code (5) = ACEB
code (6) = EBCB
code (7) = BCBC
code (8) = ECDE
code (9) = BDCA
code (10) = ADAA
code (11) = CDEA
code (12) = CACC
code (13) = EABD
code (14) = DAEC
code (15) = ABDD
code (16) = CDCB
code (17) = EDBC
code (18) = DDEB
code (19) = AEDC


Parallel resistance in electric circuits Introduction:

Two resistors, R1 and R2,  in parallel (denoted R1 || R2) have a combined resistance Rp given as:

$$R_{P_2} = \frac{R_1\cdot R_2}{R_1+R_2}$$
or as suggested in comments:

$$R_{P_2} = \frac{1}{\frac{1}{R_1} + \frac{1}{R_2}}$$

Three resistors, R1, R2 and R3 in parallel (R1 || R2 || R3) have a combined resistance (R1 || R2) || R3 = Rp || R3 :

$$R_{P_3} = \frac{\frac{R_1\cdot R_2}{R_1+R_2}\cdot R_3}{\frac{R_1\cdot R_2}{R_1+R_2}+R_3}$$

or, again as suggested in comments:

$$R_{P_3} = \frac{1}{\frac{1}{R_1} + \frac{1}{R_2}+ \frac{1}{R_3}}$$

These formulas can of course be extended to an indefinite number of resistors.

Challenge:

Take a list of positive resistor values as input, and output the combined resistance if they were placed in parallel in an electric circuit. You may not assume a maximum number of resistors (except that your computer can handle it of course).

Test cases:

1, 1
0.5

1, 1, 1
0.3333333

4, 6, 3
1.3333333

20, 14, 18, 8, 2, 12
1.1295

10, 10, 20, 30, 40, 50, 60, 70, 80, 90
2.6117

Shortest code in each language wins. Explanations are highly encouraged.

05AB1E, 5 3 bytes
zOz

Try it online!

Explanation
z                     # compute 1/x for each x in input
 O                    # sum input
  z                   # compute 1/sum


Normal and inverted exclamation and question mark pairs Challenge

¡We're going to give exclamation and question marks inverted buddies!

Given a body of text containing sentences ending in ., ?, or !, prepend inverted question marks, ¿, to interrogative sentences (sentences ending in ?) and inverted exclamation marks, ¡, to exclamatory (sentences ending in !). Sentences ending in . are to be ignored.

Sentences will be separated by whitespace (spaces, tabs, and/or newlines) and will only contain alphanumerics, commas, apostrophes, and spaces. Every sentence will have at least one word. The first word of every sentence is guaranteed to be capitalized. Input can start and end with any whitespace.

Example

Input:

  Hello there!      What is your name?
My name is Ron. What's your name?
My name is Alex.  Nice to meet you!
Nice to meet you to!  How was your break?
It was great, I spent all my time code golfing!
What's that?
        Wow, you're such a n00b! Here, let me show you.

Output:

  ¡Hello there!      ¿What is your name?
My name is Ron. ¿What's your name?
My name is Alex.  ¡Nice to meet you!
¡Nice to meet you to!  ¿How was your break?
¡It was great, I spent all my time code golfing!
¿What's that?
        ¡Wow, you're such a n00b! Here, let me show you.

Rules

All default Code Golf rules apply.
The program with the shortest amount of bytes wins.

Bonus (17% off) - Parse multiple marks

A sentence can also end in multiple exclamation/question marks. Give each of these marks a paired inverse exclamation/question mark for an extra 17% off your byte count.

Example

Input:

I am a man in a can doing a dance?? Maybe...
              Doing it for the views??!???!

Output:

¿¿I am a man in a can doing a dance?? Maybe...
              ¡¿¿¿¡¿¿Doing it for the views??!???!

Incorrect output:

¿¿I am a man in a can doing a dance?? Maybe...
              ¿¿¡¿¿¿¡Doing it for the views??!???!

Retina, 39 37 34 bytes

\w[^.]*?([!?])
$1$0
T`?!`¿¡`\S\b

Try it online.

Explanation

\w[^.]*?([!?])
$1$0

This matches a sentence ending in an exclamation or question mark, and prepends that punctuation character to the sentence. Now we know that all the ! or ? which are immediately followed by a non-space character must be those we inserted, because the original ones should be separated from the next character by a space.

T`!?`¡¿`\S\b

This transliteration stage turns all ! and ? into ¡ and ¿, respectively, provided they're found in a match of \S\b, which applies only to the ones we just inserted. Replacing both in two separate substitutions in the same byte count, but I prefer the semantics of a transliteration stage here.


The shortest code to invert bit-wise a binary string Me thinks there aren't enough easy questions on here that beginners can attempt!

The challenge: Given a random input string of 1's and 0's such as:

10101110101010010100010001010110101001010

Write the shortest code that outputs the bit-wise inverse like so:

01010001010101101011101110101001010110101

J, 5 bytes
Assumes the input string is in variable b.
b='0'

This does not do what it would do in most languages...

 The J comparison operator is just = (=: and =. are global and local assignment, respectively). However, = doesn't work like the normal == operator: it compares item-by-item. Keep in mind that an array is formed like this: 0 2 3 2 3 1 2 3 4. 2 = 0 2 3 2 3 1 2 3 4 gives 0 1 0 1 0 0 1 0 0 for example. This is similar for a string: 'a'='abcadcadda' doesn't just return 0, it returns 1 0 0 1 0 0 1 0 0 1 (This can be extrapolated to mean 0 with */, which basically means all.) In this case however, this behavior is excelent, since we want a string of ones and zeros, or true's and false's. Since J's bools are 1 and 0, this results in an array of 1's and 0's (They aren't strings, and every other character other than 1 would also result in 0 in this array.) This doesn't need printing: J automatically prints the result of an expression. I hope this was adequate explanation, if not, please ask for something that isn't yet clear in the comments. This answer also could've been '0'&= (or =&'0'), but I felt that b='0' was clearer.


Tips for golfing in Kotlin Given Google's recent announcement of official Kotlin support for Android development, I thought it might be timely to poll the community for some awesome golfing tips for this relatively new JVM language.

Kotlin includes a unique combination of features among it's JVM siblings which makes it potentially attractive for golfing:

operator overloading
local, infix, and static extension functions
smart casts
Groovy-style type-safe builders
type aliases
ranges
an extensive functional collections package
scripting support

So, how do I squeeze the last few bytes out of my Kotlin program? One tip per answer, please.

Use + instead of toString

As one might expect, String overloads the + operator for string concatenation, like so.

print("Hel" + "lo")

However, checking the docs tells us that it accepts Any?, not just String. As stated:

  Returns a string obtained by concatenating this string with the string representation of the given other object.

In other words, String + anything makes sure to call .toString() on the right hand side before concatenating. This allows us to shorten it.toString() to ""+it, a massive 8 byte savings at best and 6 bytes at worst.

Use fold instead of joinToString

Related to the above, if you're calling map and then joinToString, you can shorten that by using fold instead.

list.map{it.repeat(3)}.joinToString("")
list.fold(""){a,v->a+v.repeat(3)}


Output a string's cumulative slope Challenge

Given a string such as Hello World!, break it down into its character values: 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33.

Then calculate the difference between each consecutive pair of characters: 29, 7, 0, 3, -79, 55, 24, 3, -6, -8, -67.

Finally, sum them and print the final result: -39.

Rules

Standard loopholes apply
No using pre-made functions that perform this exact task
Creative solutions encouraged
Have fun
This is marked as code-golf, the shortest answer in bytes wins but will not be selected.

Python, 29 bytes

lambda s:ord(s[-1])-ord(s[0])

The sum of the differences forms a telescopic series, so most summands cancel out and
(s1 - s0) + (s2 - s1) + … + (sn-1 - sn-2) + (sn - sn-1) = sn - s0.

If taking a byte string as input is allowed

lambda s:s[-1]-s[0]

will work as well for 19 bytes.

Test both on Ideone.


Generate /* line number comments */ Your task is to write a program (or function) that will take a string as input and append text to the beginning of every line that satisfy the following rules:

The text appended must contain the line number. You may use 0- or 1-based indexing.
The text must be a comment in your language. A comment is defined as a syntacticly valid piece of code that makes no changes to the program's state. Removing the comment should make no change to the program.
The comment may
only contain newlines at the end of it.
You do not have to put line numbers for lines that contain just whitespace and comments.

Specifications

You may assume that the input will be a valid program in your language.
In indentation-sensitive languages like Python, you may place the line number comment after all indentation. You may choose either tabs or spaces to be your indentation character, but you must specify on your post.
You may assume that every statement in the code will take up at most the entirety of 1 line; i.e. no multi-line strings or backslash-continuation.

Test Cases

Python:

#0
a = int(input())
#1
while a:
    #2
    print(a)

C: (Honestly, I'm surprised this compiles)

/*0 */#include <stdio.h>
/*1 */int main()
/*2 */{
/*3 */    char c;
/*4 */    c = getchar();
/*5 */    do
/*6 */    {
/*7 */        putchar(c);
/*8 */    }
/*9 */    while (c);
/*10*/}

This is code-golf, so the shortest answer (in bytes) wins.

Perl, 8+1 = 9 bytes

say"#$."

Run with -p (1 byte penalty). (Note to people unfamiliar with PPCG rules; you also need to specify a modern version of Perl syntax using -M5.010, but we decided that options to select language versions are free and don't incur a byte penalty, so I didn't mention it in the original version of this post.)

-p places the program into an implicit loop; it basically causes the program to become a filter that processes each line separately (i.e. the entire program is run on the first line, then the second, then the third, and so on). Perl also keeps track of a line number, called $., that records how many lines of input have been read. So all the program's doing is letting -p read a line of input; output a #, the current line number ($.), and a newline (say adds a newline by default, which is helpful in this case, and is also shorter than the more commonly seen print); and then letting -p output the original line of code that it read (typically a program using -p would do some sort of processing on the input, but because we didn't, it's just output unchanged). Comments in Perl run from # to a newline (the # in the program itself doesn't start a comment because it's inside a string literal), so what we're basically doing is taking the opportunity to write comment lines into the file as we process it, without disturbing the "natural" read and write cycle of -p.


Generate a Padovan Spiral Introduction
Similar to the Fibonacci Sequence, the Padovan Sequence (OEIS A000931) is a sequence of numbers that is produced by adding previous terms in the sequence. The initial values are defined as:
P(0) = P(1) = P(2) = 1

The 0th, 1st, and 2nd terms are all 1. The recurrence relation is stated below:
P(n) = P(n - 2) + P(n - 3)

Thus, it yields the following sequence:
1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, 351, ...

Using these numbers as side lengths of equilateral triangles yields a nice spiral when you place them all together, much like the Fibonacci Spiral:

Image courtesy of Wikipedia

Task
Your task is to write a program that recreates this spiral by graphical output, with input corresponding to which term.
Rules

Your submission must be able to handle at least up to the 10th term (9)
Your submission must be a full program or function that takes input and displays a graphical result (either outputs an image or graphs, etc)
You must show proof of your graphical output in your submission
Rotations of the output are allowed, in 60 degree multiples, with the same representation
Going counter-clockwise is also allowed
Standard loopholes are forbidden

You may assume that input will be >0 and that correct format of input will be given.
Scoring
This is code-golf, so the shortest code in bytes wins. Happy New Years everyone!

Mathematica, 119 108 bytes

Thanks to Martin Ender for saving 11 bytes!

±n_:=If[n<4,1,±(n-2)+±(n-3)];Graphics@Line@ReIm@Accumulate@Flatten@{0,z=I^(2/3),±# z^(#+{2,4,1})&~Array~#}&@

Unnamed function taking a positive integer argument (1-indexed) and returning graphics output. Example output for the input 16:

Developed simulataneously with flawr's Matlab answer but with many similarities in design—even including the definition I^(2/3) for the sixth root of unity! Easier-to-read version:

1  (±n_:=If[n<4,1,±(n-2)+±(n-3)];
2   Graphics@Line@ReIm@
3   Accumulate@Flatten@
4   {0,z=I^(2/3),±# z^(#+{2,4,1})&~Array~#}
5  ])&

Line 1 defines the Padovan sequence ±n = P(n). Line 4 creates a nested array of complex numbers, defining z along the way; the last part ±# z^(#+{2,4,1})&~Array~# generates many triples, each of which corresponds to the vectors we need to draw to complete the corresponding triangle (the ±# controls the length while the z^(#+{2,4,1}) controls the directions). Line 3 gets rid of the list nesting and then calculates running totals of the complex numbers, to convert from vectors to pure coordinates; line 2 then converts complex numbers to ordered pairs of real numbers, and outputs the corresponding polygonal line.


Compute the Mertens function Given a positive integer n, compute the value of the Mertens function M(n) where

and μ(k) is the Möbius function where μ(k) = 1 if k has an even number of distinct prime factors, -1 if k has an odd number of distinct prime factors, and 0 if the prime factors are not distinct.

This is code-golf so create the shortest code for a function or program that computes the Mertens function for an input integer n > 0.
This is the OEIS sequence A002321.

Test Cases

n M(n)
1 1
2 0
3 -1
4 -1
5 -2
6 -1
7 -2
8 -2
9 -2
10 -1
117 -5
5525 5
7044 -25
8888 4
10000 -23

Mathematica, 22 20 bytes

Thanks to @miles for saving 2 bytes.

Tr@*MoebiusMu@*Range

Explanation

Range

Generate a list from 1 to input.

MoebiusMu

Find MoebiusMu of each number

Tr

Sum the result.


"Monitorize" an Image The Problem:

This challenge comes from a real problem I was having. I have a dual monitor setup at work, and I wanted to use the following image as my wallpaper:

However, my monitors have quite significant bezels, and when I set my background, it looks something like this, where the pier appears (appiers?) to be broken:

I was able to solve this by making an image with the center cut out of it, and then stretching it back to the original size, as in the image below:

The Challenge:

Write a program that takes in an image and "monitorizes" it  for use with a dual monitor setup (i.e. deletes the center section of the image, where the bezels are). The rules are as follows:

It must be a full program that accepts the image, either as a path (string argument, etc), or in the form of a file chooser dialog.
The program must take as an input the number of vertical lines (one pixel in width) to crop out from the center of the image
The cropping must come from the center (width-wise) of the original image
The resultant image must be re-scaled back to the original size of the input image. (Either the halves can be scaled individually, and then concatenated, or concatenated and then scaled. Scaling individually produces a better image/effect, but is hardly noticeable in the real world)
Background images are generally even, so to make this challenge easier, input images will only have an even number of pixels, and number of lines to remove will only be even as well.
This challenge is code golf - shortest code in bytes wins

Good Luck!

Matlab 2013, 150 bytes

Here is my attempt in Matlab. Definitely won't be the shortest code, but it's a start.

Warning, this overwrites the original image, so make a copy first.

Golfed Version

function  mi(f,n)
o=imread(f);
s=size(o);
imwrite([imresize(o(:,1:((s(2)-n)/2),:),[s(1),s(2)/2]) imresize(o(:,((s(2)+n)/2):end,:),[s(1),s(2)/2])], f);
end

Ungolfed Code, with improvements for odd image sizes and odd number of columns

function  monitorizeImage( filename, num_columns )

orig = imread(filename);
orig_size = size(orig);

f = factor(orig_size(2));
origsize_iseven = f(1)==2;

f = factor(num_columns);
num_columns_iseven = f(1)==2;

odd_even_size_mismatch = xor(origsize_iseven,num_columns_iseven);

img_resized = imresize(orig,[orig_size(1) orig_size(2)+odd_even_size_mismatch]);

leftimg = img_resized(:,1:((orig_size(2)+odd_even_size_mismatch-num_columns)/2),:);
leftimg = imresize(leftimg,[orig_size(1),floor(orig_size(2)/2)]);
rightimg = img_resized(:,((orig_size(2)-odd_even_size_mismatch+num_columns)/2):end,:);
rightimg = imresize(rightimg,[orig_size(1),floor(orig_size(2)/2)]);

monitorized_image = [leftimg rightimg];
monitorized_image = imresize(monitorized_image,[orig_size(1),orig_size(2)+ ~origsize_iseven]);

[~, ~, ext] = fileparts(filename);

imwrite(monitorized_image,strcat(filename(1:end-length(ext)),'_',num2str(num_columns),ext));

end


Optimizing my spell casts! I'm a young wizard, and I try very hard to not waste mana during my magical encounters.
I have X spells available at any given time and each one of them have its own mana cost Y.
X,Y being positive integers strictly lower than 11.
As a beginner, my mana pool fluctuates a lot (it is always lower than 11), and I need help to cast as few spells as possibles (scrolls are expensive, ya know) while emptying my mana pool. If you can't find any spell combination which matches exactly my mana pool's size, you shall then offer me closest (and cheaper) one.

I came to you and your infinite wisdom to help me become the greatest dark wizard. I shall not be disappointed.

INPUT style (because style is everything):
Y;a b c d e f
Y is the size of the mana pool. (a,b,c,d,e,f) are the spells. There are 6 spells, first one costs 'a' mana, second spell costs 'b' mana, etc.

INPUT :  4;1 2 3 3 7 6
I have 4 manas available, and 6 spells available. Two spells cost 1 mana, 1 spell costs 2 mana, two spells cost 3 mana, etc.

OUTPUT : (3,1)

INPUT : 3;1 3 5 2 10
OUTPUT : (3)

INPUT : 8 ; 4 1 9
OUTPUT : (4,1)

INPUT :  4;1 2 2 3
OUTPUT : (2,2),(1,3)
You shall output every combination of spells, but there is no need to distinct spells which are the same cost.

The shortest incantation to whatever machine you desire will be granted a profusion of thanks, and a whip of destiny.

Ruby, 114 113 characters

x,y=eval gets
(d=0..10).find{|r|d.find{|c|s=y.sort.combination(c).select{|s|s.reduce(:+)==x-r}.uniq
p s if s[0]}}

Input: a two-element array of the wizard mana and the spell list, formatted a one-line JSON.

Output: a 2D array of the spell lists, formatted as a one-line JSON, or nil if the wizard can cast no spell.

I especially love x,y = eval gets. So dangerous and evil, yet so powerful and simple. Perfect for golfing.

Both sort and uniq are neccessary. Otherwise, this will produce duplicates for input like [4, [1, 3, 1]]. I'm not happy about this.

find is a useful method for control flow. Its return value is not as useful here, though. Length-wise, it comes on par with any?, which return value is even less useful.

Examples:

> [4, [1, 2, 3, 3, 7, 6]]
# [[1, 3]]
> [3, [1, 3, 5, 2, 10]]
# [[3]]
> [8, [4, 1, 9]]
# [[1, 4]]
> [4, [1, 2, 2, 3]]
# [[1, 3], [2, 2]]
> [4, [5, 6, 7]]
# nil


Tips for golfing in 05AB1E Do you have any tips for code-golfing in 05AB1E, a golfing language created by Adnan?

Your tips should be at least somewhat specific to 05AB1E.

Please post one tip per answer.

Since it wasn't part of the Wiki on 05AB1E's GitHub pages (I think it should), I'm just gonna add it here now that I better understand it myself.

How to use the dictionary?

05AB1E has the following words.ex dictionary file containing all the words it knows. But how do we access the words in this dictionary? Let's take the word "testing" as example:

"testing" can be found on row 1453 of the dictionary file. Since the first two lines aren't words, and we need the 0-indexed word, we subtract 3.
So, now we have the index (1450), but how to use it?

We open and start a compressed string with “†. We then look at the second column of the info.txt file. (So € is 00; ‚ is 01; etc.)
In the case of "testing" this means î (14) and » (50).

The compressed String for "testing" is therefore: “î»“ Try it online. As with almost all 05AB1E pieces of code, the trailing “ is optional if you don't access the string, so without works as well in this case.

Some things to note:

All characters that doesn't have any index in the info.txt file can be used as is. This can be useful for adding an s to output a plural instead of singular word or use punctuation like ,.?! for example.
ÿ (string-interpolation) can also be used when you want to insert values from the stack within the string.
NOTE: Every loose character that doesn't have any index in the info.txt file counts as a word for the compression types below.

† There are different types of compressed strings you can use:

': Take a single compressed word as is (no trailing ' required) - 'î»: "testing"
„: Takes two compressed words with space delimiter (no trailing „ required) - „î»î»: "testing testing"
…: Takes three compressed words with space delimiter (no trailing … required) - …î»î»î»: "testing testing testing"
“: Take the compressed string with space delimiter - “î»î»“: "testing testing"
’: Take the compressed string as is without implicit spaces - ’î»î»’: "testingtesting"
”: Take the compressed string in title-case with space delimiter - ”î»î»”: "Testing Testing"
‘: Take the compressed string in full uppercase with space delimiter - ‘î»î»‘: "TESTING TESTING"

Here a useful program to get the compressed string based on a space-delimited input of words:

'“? lAð«Ã#¸˜ vyU "€‚ƒ„…†‡ˆ‰Š‹ŒŽ•–—™š›œžŸ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîï" Dâ vy"“ÿ“".V XlQi y?1#] '“,

Try it online.

This program will:

Take the input as lowercase, removes any non-alphabetic characters (except for spaces), and then splits the words by spaces (lAð«Ã#), or wraps the words in a list if only a single word was inputted (¸˜)
Loops over each word (vyU)
Then has an inner loop over each compressed word from the dictionary ("€...ï"Dâvy), which it will try to run as 05AB1E program ("“ÿ“".V)
And if it's equal to the current word it will print it and break the inner loop XlQiy?1#

With an input good bye world the output would therefore be “‚¿Þ¡‚ï“. Try it online.

NOTE: You'd still have to see if the word exist in the dictionary in order for this generator to work, and it will ignore any special characters or plural words. Only the words that are exactly the same in the dictionary will be found.

Here an example where I use …Ÿ™‚ï! for the string "hello world!" and ’‚¿Þ¡ ÿ ‚ï!’ for the string "goodbye ÿ world!". Note how the spaces and exclamation mark are used as is, because they don't have indices in the info.txt file. In addition, it uses ÿ to insert the "cruel" that was at the top of the stack, which unfortunately wasn't part of the dictionary (but was still compressed using the method at the section below).

How to compress strings not part of the dictionary?

Although the words.ex dictionary file is pretty big (10,000 words to be exact), it can happen that you need a word which isn't part of it, or a string which is just plain gibberish. So is there a way to compress those as well?
There certainly is, by using .•, which is a compressed base-255 alphabet based string. NOTE: This method can only be used for characters in the lowercase alphabet and spaces.

Here is a useful program to convert a word/string to the compressed base-255 alphabet based string:

vAyk})> 27β 255B ".•ÿ•"

Try it online..

What this program above does is:

vAyk})>: Take the 1-indexed alphabet indices of the individual letters of the input, with spaces becoming index 0
27β: Convert these indices from base 27 to a single number
255B: Convert this number to Base-255 using 05AB1E's own code page
".•ÿ•": Places a leading .• and trailing • before this compressed string

Here an example answer where @Kaldo uses .•zíΘ• to compress the word "goose".

How to compress large integers?

Let's say we want to use a very big number for something, but it can't really be retrieved by pow-calculations. For example, let's say we want to access the large integer 18238098189071058293 for whatever reason.

In this case we can use both a leading and trailing • to compress a number in the format [1-9][0-9]+.
The example number above will become •15Y₁Ò'Θpc•. Try it online. Again, just like with the compressed dictionary string, the trailing • can optionally be removed.

Optionally, when the integer is small enough so only 2 compressed characters have to be used, we can use Ž instead, in which case we won't need a trailing byte to close it and the integer is compressed in 3 bytes instead of 4. For example, the integer 13562 would result in •rl•, but because it only uses two characters, it can be Žrl instead.

Also, numbers in the range [101, 355] can be compressed in 2 bytes using Ƶ plus an additional character from 05AB1E's codepage. So for example, Ƶ– can be used for the integer 250. Here an overview of all available numbers. These characters are converted from Base-255 to Base-10, and then 101 is added (since the numbers in the range [0,100] are already 1 or 2 bytes).

How are these 15Y₁Ò'Θpc and rl created? Very simple, the number is converted to Base-255 using 05AB1E's own codepage. So you can use the following program to get a compressed number, for which it will then use Ƶ., Ž.., or •...• depending on the size of the compressed integer:

101 355Ÿså i 101-255B"Ƶÿ" ë 255B Dg2Qi "Žÿ" ë "•ÿ•"

Try it online.

Here an example answer where @Emigna uses •3Èñ• for the integer 246060.

How to compress integer lists?

Sometimes you want to compress an entire list of integers instead of a single number. For example, let's say we want the list [5,94,17,83,4,44,32,19,4,45,83,90,0,14,3,17,17,81] for whatever reason. In this case, we can use the following instead: •5O›YJ&p‘ÑÎ!6¯8,•₃в Try it online.

Here a useful program to generate both this compressed number and the Base we want to convert to:

Z>© β 255B ®s"•ÿ•ÿв"

Try it online.

What this program above does is:

Z>: Get the max number + 1 of the input-list (©: and store it in the register)
β: Convert the input list from base max+1 to a single number
255B: Compress this single number (as we did at the section above)
®s"•ÿ•ÿв": Returns the result in the format: leading •, compressed number, •, max+1, trailing в

Here an example answer where I use •4Œ”dóŒfÝŸĀTUÕáOyÖOÀÁàu¼6¹₆Žr‡_›y³eß₂©ǝ²ƶ"SAÎAñ'¡û†Ø(•91в to compress the list [85,30,29,39,28,37,33,88,31,40,34,89,35,41,32,90,36,38,42,43,44,60,45,61,46,62,47,63,48,64,49,65,81,50,66,51,67,52,68,53,69,86,54,70,87,55,71,56,72,82,57,73,79,80,58,74,59,75,76,77,78,83,84].
PS: In this answer •6j|eDEJÞó(ÍêΓλùÄÞKüzHÇ-ø`JδŠ₂+Öηôî®À8†6/ðÎ6ùøΓ°ÓĆ;ˆ©Ā•2ô is an equal-bytes (57) alternative, since all numbers have exactly two digits. In some cases (especially small lists) this can be a shorter alternative.

One thing to note is that it's usually shorter to use a slightly larger single-byte integer constant (i.e. T₂₆₃т₅₁₄ for 10,26,36,95,100,255,256,1000 respectively) instead of the maximum+1 found by the program above. Let's say our example [5,94,17,83,4,44,32,19,4,45,83,90,0,14,3,17,17,81] was [5,95,17,83,4,44,32,19,4,45,83,90,0,14,3,17,17,81] instead, it would find •6MÖ∊]ć;?,ćiåÑ6Š•96в (20 bytes) as shortest, but •CRā»ïζyˆöÍ†y“a±•тв (19 bytes) with the single-byte constant 100 would be 1 byte shorter.
You can still get the compressing program above by replacing the Z> with the single-byte constant (or its value): Try it online.

Integer compression vs Integer list compression:

With these two it can go either way. Sometimes a compressed list is shorter, sometimes a compressed integer, sometimes a completely different alternative is shorter. So always use your own judgment and golfing skills to possibly golf things further, instead of relying on the above generators completely. Here some examples:

[44, 59] (used in this answer of @Emigna):

•A–•60в is 7 bytes (generated by the compressed integer list generator)
•H|•2ô or •H|•2ä or hardcoded 44 59‚ are all 6 bytes
ŽH|2ô or ŽH|2ä are both 5 bytes
But in this case, „,;Ç with 4 bytes would be the best option (codepoints of characters ',' and ';')

[2,4,6,0] (used in this answer of @Emigna):

•3ā•7в is 6 bytes (generated by the compressed integer list generator)
Ž3ā7в is 5 bytes
But in this case, Ž9¦S with 4 bytes would be the best option (compressed integer 2460 to a list of digits)

10101001100101001 (initially used in this answer of mine):

•a½₄Ƶ6®í• is 9 bytes (generated by compressed large integer generator)
•1∊}•2вJ is 8 bytes (generated by compressed integer list generator with added join)
•1∊}•b with 6 bytes would be even shorter (compressed integer list, with a to binary instead of 2в, which implicitly joins)
But Ž«ǝbĆ with 5 bytes would be the shortest option here (compressed integer, to binary, and enclose - appending its own head)

[85,30,29,39,28,37,33,88,31,40,34,89,35,41,32,90,36,38,42,43,44,60,45,61,46,62,47,63,48,64,49,65,81,50,66,51,67,52,68,53,69,86,54,70,87,55,71,56,72,82,57,73,79,80,58,74,59,75,76,77,78,83,84] (used in this answer of mine):

•4Œ”dóŒfÝŸĀTUÕáOyÖOÀÁàu¼6¹₆Žr‡_›y³eß₂©ǝ²ƶ"SAÎAñ'¡û†Ø(•91в is 57 bytes (generated by compressed integer list generator)
•6j|eDEJÞó(ÍêΓλùÄÞKüzHÇ-øJδŠ₂+Öηôî®À8†6/ðÎ6ùøΓ°ÓĆ;ˆ©Ā•2ô` is also 57 bytes (compressed integer, split into parts of size 2)
•Bšā¿ÑáζΔÕæ₅"®GÙ₂®°ƶío"§óÏ4¸bćÔ!₃ùZFúÐìŸ
,λ₂Ï¦P(Ì•65в₂+ is however 2 bytes shorter, by compression the list with each value 26 lower, and then add that afterwards with ₂+. This trick of adding a single-byte value later on can be used pretty often to save bytes in compressed lists.


Find the closest Fibonacci Number We are all familiar with the famous Fibonacci sequence, that starts with 0 and 1, and each element is the sum of the previous two. Here are the first few terms (OEIS A000045):
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584

Given a positive integer, return the closest number of the Fibonacci sequence, under these rules:

The closest Fibonacci number is defined as the Fibonacci number with the smallest absolute difference with the given integer. For example, 34 is the closest Fibonacci number to 30, because |34 - 30| = 4, which is smaller than the second closest one, 21, for which |21 - 30| = 9.

If the given integer belongs to the Fibonacci sequence, the closest Fibonacci number is exactly itself. For example, the closest Fibonacci number to 13 is exactly 13.

In case of a tie, you may choose to output either one of the Fibonacci numbers that are both closest to the input or just output them both. For instance, if the input is 17, all of the following are valid: 21, 13 or 21, 13. In case you return them both, please mention the format.

Default Loopholes apply. You can take input and provide output through any standard method. Your program / function must only handle values up to 108.

Test Cases

Input -> Output

1    -> 1
3    -> 3
4    -> 3 or 5 or 3, 5
6    -> 5
7    -> 8
11   -> 13
17   -> 13 or 21 or 13, 21
63   -> 55
101  -> 89
377  -> 377
467  -> 377
500  -> 610
1399 -> 1597

Scoring
This is code-golf, so the shortest code in bytes in every language wins!

Python 2, 43 bytes

f=lambda n,a=0,b=1:a*(2*n<a+b)or f(n,b,a+b)

Try it online!

Iterates through pairs of consecutive Fibonacci numbers (a,b) until it reaches one where the input n is less than their midpoint (a+b)/2, then returns a.

Written as a program (47 bytes):

n=input()
a=b=1
while 2*n>a+b:a,b=b,a+b
print a

Same length:

f=lambda n,a=0,b=1:b/2/n*(b-a)or f(n,b,a+b)


Find longest consecutive characters in 2D array Challenge

Given a 2D array, find the length and direction of all the longest consecutive characters.

If there are ties, output every possible winning combination in any order, (winners can overlap with other winners)
Zero "0" is a special padding character which cannot be a winner.
Code golf rules apply, shortest code wins.

Output: n,m,d

(Where n is the identified character of length m in d direction)

Valid characters for d: /|\-. See below examples to interpret meaning.

Input: The 2D array input should be in either of the following format, (your preference):

Option 1:

123
456
789

Option 2*:

[["123"],["456"],["789"]]

*or any combination of "{[()]}" characters can be used, with whitespace characters ignored outside of quotes. Quotes can be single or double. The array must read left-to-right, top-to-bottom.

Assumptions

The shape of the array will always be rectangular or square
There will always be at least one non-zero character
Array characters will only be alphanumeric

Examples

1.

0000000
0111100
0000000

  1,4,-

2.

00000000
aaaa0000
00bbbbb0

  b,5,-

3.

0y00x000
aayxaaaz
00xy000z
0x00y00z
x0000y0z

  x,5,/

  y,5,\

*(in any order)

4.

1111
1111
1111

  1,4,-

  1,4,-

  1,4,-

5.

ccc
cwc
ccc

  c,3,-

  c,3,-

  c,3,|

  c,3,|

*(in any order)

6.

9

  9,1,.

7.

ab
cd

  a,1,.

  b,1,.

  c,1,.

  d,1,.

*(in any order)

Charcoal, 110 bytes

≔⪫Ａ⸿θＰθＦθ«≔⟦⟧ηＦ∧¬№0⸿ι⟦→↘↓↙⟧«≔ＫＤＬθ✳κζＷ›Ｌζ№ζι≔⊟ζε⊞η⟦κιＬζ⟧»¿⁼¹⌈Ｅη§κ²⊞υ⊟ηＦη⊞υκι»⎚≔⌈Ｅυ§ι²εＦΦυ⁼⊟ιε«⊟ι,Ｉε,Ｐ✳⊟ι⎇⊖ε¹.¦⸿

Try it online! Link is to verbose version of code. Takes an array of strings as input. Explanation:

≔⪫Ａ⸿θＰθ

Join the strings with carriage returns (not newlines) and output them without moving the cursor.

Ｆθ«

Loop over each character in the string.

≔⟦⟧η

Collect all of the consecutive characters starting at this position in an array.

Ｆ∧¬№0⸿ι⟦→↘↓↙⟧«

If the current character is not a 0 or a carriage return, then check all four directions.

≔ＫＤＬθ✳κζ

Peek as much as possible in that direction.

Ｗ›Ｌζ№ζι≔⊟ζε

Shorten the string until all of the characters are the same.

⊞η⟦κιＬζ⟧»

Save the results in the array.

¿⁼¹⌈Ｅη§κ²⊞υ⊟ηＦη⊞υκ

If the maximum consecutive character was 1, then only push one of the results to the final array, otherwise push all of them.

ι»

Reprint the current character, this time allowing the cursor to move.

⎚

Clear the input from the canvas.

≔⌈Ｅυ§ι²ε

Find the longest consecutive length.

ＦΦυ⁼⊟ιε«

Loop over the entries with that length.

⊟ι,Ｉε,

Output the character and length.

Ｐ✳⊟ι⎇⊖ε¹.¦⸿

If the length is 1 then output a . otherwise output a direction character. Then move to the start of the next line for the next result.


Transformers in Disguise (Robbers' Thread) The cop's thread is here

The robber's task is to find a program of size equal to or less than the cop's program, which, when given an itself as input, produces the same output as the cop's program.

Additionally, even if a cop's answer is provisionally marked Safe and has been revealed, you can still crack it by finding an input that is not the same as the given source code, but still produces the same output.

Rules:

Submissions consist of

Language name + flags
Username of the cop with a link to the original post
The cracked program

An explanation would be appreciated
Your goal is to crack the most Cop's programs

Some Examples:

brainfuck, xxx's submission

[,[>,]<[.<]]

Try It Online!

This program simply reverses the input

Good luck!

Node.js v10.9.0, Arnauld

o=>[...o].sort(n=>16&(j+=13),j=9).join``

Try it online!

This outputs this particular permutation of itself when using Node's current sorting algorithm:

&`nij.9=j.,)r31n=+(=ooj`[o.o.)1.s](>=6>t

An insightful comment by l4m2 gave me a headstart, but I had to write a brute-forcer to figure out which permutation of digits gives the correct output...


Calculate the Riemann Zeta Function Calculate the Riemann zeta function to the maximum primitive precision in your language (for C-family, that would be double or long double, var in JS, etc.) No need for BigDecimal or the like unless you need it to use a double-equivalent precision.

Efficiency (be sane) doesn't matter.
If it's not in a common language, I can't test it, but I hope somebody does.
No libraries or built-in math functions.
Recursion is cool!

See my JS entry for a sample program.

JavaScript (Chrome): 78
function zeta(r){for(var t=0,a=1,n=1;t!=a;a=t,t+=1/Math.pow(n++,r));return t}


Number of characters in an integer's name The goal of this challenge is to show how many characters are in the name of a given integer. This is code golf, so the smallest code wins.

RULES

The input will be between 0 and 100 (inclusive). If it is not the program won't return anything.
The result has to be printed as input : answer
Result for 100 is hundred

For example, if the input is 23 you have to count the numbers of letters twenty-three : here the answer is 12, and you should print 23 : 12

C : 117 bytes

(From kind suggestion of @edc65 and @ColeCameron)

f(a){char *d="0446554665366887798803665557667";printf("%d : %d",a,(a?a<20?d[a]-(a<10):d[a%10]+d[20+a/10]-48:52)-48);}

Live example

C++ : 159 bytes 178 bytes

int f(int a){char *d[3]={"0446554665","0366555766","3668877988"};printf("%d : %d",a,(a?a<20?a>9?d[2][a-10]:d[0][a]-1:a>99?55:d[0][a%10]+d[1][a/10]-48:52)-48);}

Live example

Explanation

Explanation from previous code, with all suggestions from comments incorporated.

int f(int a) {  // Return int to save a byte, a is the argument

    int d[3][10]={
             {0,4,4,6,5,5,4,6,6,5},  // Length of "", "-one", "-two", "-three" etc.
             {0,3,6,6,5,5,5,7,6,6},  // Length of "", "ten", "twenty", etc.
             {3,6,6,8,8,7,7,9,8,8}   // Length of "ten", "eleven", etc.
           };
    printf ("%d : %d", a,
               a
                 // If a is not zero
                 ? a < 20
                     // If a is less than 20
                     ? a > 9
                         // a is in range 10-19
                         ? d[2][a-10]
                         // a is in range 0-9
                         : d[0][a]-1  // Subtract one as '-' is not required
                     // If a is >= 20
                     : a > 99
                         // If a is 100
                         ? 7  // Length of hundred
                         // a is between 20-99
                         : d[0][a%10] + d[1][a/10]  // unit digit length + tens digit length
                 // If a is zero
                 : 4
            );
}


Given a string find the substring which appears most often Write a complete program (not just a function) which using stdin takes in a string of arbitrary length (assume string-length at least one) composed only of digits 0-9 and outputs using stdout the substring which appears most often in the input string. The input string can be any length and the substring can be maximum half the length of the input string because it must appear at least twice non-overlapped to be printed.

We following the following hierarchy selecting the substring to be printed.

First priority, the longest substring
Second priority, if we have multiple substrings of the same length, we pick the one appearing the most often.
Third priority, if multiple substrings of the same size appear the same number of times, pick the one which appears first scanning from the left.

Here are some test cases followed by the rules and some explanation.

./myprogram 123456
No substrings repeat.

The substring must appear more than once. If no substrings repeat the the output must exactly be the string "No substrings repeat." complete with the capitalization and the period.

./myprogram 12121
12

The sub-strings must not overlap. So in this case the largest repeating substring is 12 instead of 121.

./myprogram 99999999
9999

We want the largest substring which appears at least twice. Here 9, 99, 999, and 9999 all appears at least twice. But we want the largest substring which appears at least twice.

./myprogram 321321788788788
788

321, 788, 887, and 878 each appear multiple times so we pick 788 which appears the most often.

./myprogram 12121
12

12 and 21 both appear twice so we pick 12 which appears first from the left.

./myprogram 12012112299999999
9999

The string 12 occurs first and appears thrice but 9999 is longer and appears only twice so we pick 9999 because it has the highest priority.

./myprogram 56698853211564788954126162561664412355899990001212345
412

No substrings of length more than three repeat. 412, 616, and 123 each appear twice. 412 occurs first and is thus printed.

I think I have taken care of all the cases. True code-golf. The shortest code in any language wins. In the case of ties, I pick the one with the highest upvotes after waiting at least for two weeks and probably longer. So the community please feel free to upvote any solutions you like. The cleverness/beauty of the code matters much more than who posts first.

Happy coding!

Perl, 99 (+1) bytes

$_=$;{(sort%;)[m{(.+).*\1(?{$;{$;x$+=~y///c.1x@{[/$+/g]}.2x$+[1]}=$+})^}]}
||"No substrings repeat."

Requires a -p command line switch.

For each repeated substring a hash entry is created, such that the largest substring, repeated the most times, with the earliest position is guaranteed to be the smallest key in the hash. The hash is then sorted, and the corresponding value for the smallest key is output.

Sample Usage:

$ echo 123456 | perl -p repeated-substring.pl
No substrings repeat.

$ echo 12121 | perl -p repeated-substring.pl
12

$ echo 99999999 | perl -p repeated-substring.pl
9999

$ echo 321321788788788 | perl -p repeated-substring.pl
788

$ echo 12012112299999999 | perl -p repeated-substring.pl
9999

$ echo 56698853211564788954126162561664412355899990001212345 | perl -p repeated-substring.pl
412


Circumvent this credentials validator This is a program I wrote in JavaScript to validate some inputted credentials, with an intentional vulnerability. The credentials_validator function takes an object as input, with usernames and passwords. It returns a function, which takes a username and password and returns true if the credentials are valid.
Your challenge is to find a username and password which, when passed to the function returned by credentials_validator, cause it to return true without knowledge of the credentials ahead of time.
This is a programming-puzzle, so the first valid answer wins.
Program:
var credentials_validator = (credentials) => {
    if (typeof credentials !== "object")
        throw new TypeError("'credentials' must be an object");

    for (var username in credentials)
        if (typeof credentials[username] === "object")
            throw new TypeError("Passwords may not be objects or 'null'");

    return (username, password) => {
        if (typeof password === "object")
            throw new TypeError("Passwords may not be objects or 'null'");

        if (!(username in credentials))
            return false;

        if (credentials[username] === password)
            return true;

        return false;
    };
};

/*

Run with:

    var validator = credentials_validator({
        "J. Doe": "P4ssword",
        "R. Wolf": "1234",
        "X. Ample": "wxyz#1"
    });

    validator("J. Doe", "P4ssword"); // true
    validator("R. Wolf", "123"); // false

*/

username = 'toString', password = {}.toString

Try it online!
Note: Due to a certain username pointed out by Wezl in the comments, this answer is not valid for the current challenge.
Why this works:

 Among other properties, Object.prototype.toString is inherited from Object.prototype, even if it wasn't a part of the object literal given to the validator. Since any object inherits the same function {}.toString is the same as the toString of the credentials object.


Inter-language 2-cycle quine Challenge
Create 2 programs A and B

The output of program A is exactly program B

The output of program B is exactly program A

Neither program should depend on inputs to yield the correct output

A and B are not identical programs

A and B are of different programming languages

Neither program may be equivalent to itself in the other language.
For example, if the chosen languages are C and C++, the C++ program
must not be a valid and equivalent C program, else the
"inter-language" requirement is redundant

A solution should include:

The program source, as well as a Try it online (tio.run) link for both programs

Scoring
The score for a solution is:

The length of the shortest program +

The combined length of the names of both programming languages, as they appear on tio.run

The reason for this unusual scoring is because this constitutes the combined length of the minimum information necessary to communicate your solution.

This is my first post to Code Golf.
Any edits to this post to increase clarity or appropriate vocabulary are welcome.

><> and Gol><>, 18 bytes + 3 + 6 = 27

'3d*:5-0@o~r{?H>o<

Try it online!

and

"3d*:5-0@o~r{?H>o<

Try it online!

Both output the same program, but with the first character flipped between ' and ". Neither program is equivalent to itself in the other language, since the behaviour of @ differs.


Standardise leading zeroes in an input string Write a program in the shortest number of bytes possible that will parse any string given to it by input, and output that string with any and all numbers padded with leading zeroes to match the largest number's length.

For example:

Input:

This 104 is an -8 example of 4.518 a string 50.

The generated output should become:

This 104 is an -008 example of 004.518 a string 050.

Note that any digits after the period are not considered part of the "length" of a number. Numbers are considered any sequence of digits with either 0 or 1 periods in the sequence. Numbers will be delimited with either the string boundary, spaces, commas, or newlines. They can also be followed by a period, but only if the period is then followed by a delimiting character. They can also be preceded with a '-' to indicated negatives.  So something like this:

The strings 20.d, 5.3ft and &450^ are not numbers, but 450.2 is.

Should output the following:

The strings 20.d, 5.3ft and &450^ are not numbers, but 450.2 is.

That is to say, no modifications.

String input will be no more than 200 characters, if your program has an upper bound for some reason.

The winning answer will be the answer in the shortest number of bytes in seven days from the posting of this question.

Test cases

Input:

2 40 2

Output:

02 40 02

Explanation: both substrings 2 are bounded on one side by a string boundary and on the other side by  .

Input:

E.g. 2,2.,2.2,.2,.2., 2 2. 2.2 .2 .2. 2d 2.d 2.2d .2d .2.d 40

Output:

E.g. 02,02.,02.2,00.2,00.2., 02 02. 02.2 00.2 00.2. 2d 2.d 2.2d .2d .2.d 40

Explanation: in the first two groups the first four numbers are followed by a delimiter (, or  ) and the final one is followed by a period then a delimiter; in the third group, each sequence is followed by the non-delimiter d.

Ruby, 111 bytes

I hope this catches all the details of the spec

puts $*[0].gsub(r=/(?<![^,\s])(-?)(\d+)(?=\.?\d*(?![^,\s]))/){$1+$2.rjust(i.scan(r).map{|m|m[1].size}.max,'0')}

It reads the input as the first command line argument and prints the result to STDOUT.