title: Plot a list of numbers

text:
# Question
Title: Plot a list of numbers
Are you feeling jealousy towards Mathematica, Matlab et al. for their intricate plotting capabilities? If you answered yes, this challenge is for you!

# Challenge

Given, via parameters or standard input, a list of numbers `list` and a positive integer `h` for the height of the plot, write a program/function/snippet that prints a character array of `length(list)` columns and `h` rows, where each column contains exactly one special non-whitespace character, e.g. `#` and `h-1` spaces. For the *nth* column the position of the special character corresponds to the value of the *nth* element in the list. Lower rows correspond to lower values, so if `list[a]≥list[b]`, then in column `a` the special character must be at least as high than in column `b`.

The scaling from the value to the y-position of the special character must *essentially* be an affine mapping (`x ↦ ax+b`) plus any necessary rounding so for example integer division is allowed but clipping is not. The scaling must be done so that the full extent of the plot is used, i.e. the first and last row contain at least one special character.

The numbers can be of any numeral type that is at least 8 bits wide. Labels or axes aren't needed. Built-in plotting functions are allowed if the output conforms to the required format. The standard loopholes are disallowed.

## Example

### Input:

```
list = [0.0,0.325,0.614,0.837,0.969,0.997,0.916,0.736,0.476,0.165,-0.165,-0.476,-0.736,-0.916,-0.997,-0.969,-0.837,-0.614,-0.325,0.0]
h = 8

```

### One possible output:

```
    ###
  ##   #
 #      #
#        #         #
          #
           #      #
            #   ##
             ###

```

This is , so the shortest code in bytes wins!

# Answer
# MATL, 26 bytes

```
tX<-tX>/iq*Yo"@Z"35h]Xhc!P

```

Try it online!

Explanation
```
tX<-    % Input array of values implicitly. Subtract minimum
tX>/    % Divide by maximum
iq      % Input height and subtract 1
*       % Multiply
Yo      % Round to nearest integer
"       % For each number in that array
  @     %   Push current number
  Z"    %   String with that number of spaces
  35h   %   Append a '#' character to that string
]       % End
Xh      % Collect all strings into a cell array
c       % Convert into 2D char array, right-padding with spaces
!P      % Transpose and flip vertically. Implicitly display

```
> 1 votes

# Answer
# Python 2, 118 bytes

Saving 2 bytes thanks to Shebang

```
def f(n,L):
 for i in range(n):print''.join(' #'[i==j]for j in[n-1-int(~-n*(x-min(L))/(max(L)-min(L))+0.5)for x in L])

```
> 2 votes

# Answer
# Mathematica, 91 bytes

```
StringRiffle[(Join[" "~Table~#,{"#"},Table[" ",a-#]]&/@⌊(a=#2-1)Rescale@#⌋),"
",""]&

```

Anonymous function. The Unicode characters are respectively U+230A LEFT FLOOR for `\[LeftFloor]`, U+230B RIGHT FLOOR for `\[RightFloor]`, and U+F3C7 (private use) for `\[Transpose]`. Output for the test case:

```
     #
   ## ##
  #     #
 #       #
#                  #
          #       #
           #     #
            #####

```
> 2 votes

# Answer
## JavaScript (ES6), 125 bytes

```
list=[0.0,0.325,0.614,0.837,0.969,0.997,0.916,0.736,0.476,0.165,-0.165,-0.476,-0.736,-0.916,-0.997,-0.969,-0.837,-0.614,-0.325,0.0];
h=8;
f=
(a,n,m=Math,u=m.max(...a),h=u-m.min(...a))=>[...Array(n--)].map((_,i)=>a.map(v=>m.round(i-(u-v)*n/h)?` `:`#`).join``).join`
`
;
console.log(f(list,h));
```
> 1 votes

---
Tags: code-golf, math, ascii-art
---


title: Polyglot Anagrams Cops' Thread

text:
# Question
Title: Polyglot Anagrams Cops' Thread
This challenge has two threads. This is the cops' thread. The robbers' thread is located here.

Your challenge is to choose an OEIS sequence and write two *full programs* in two different languages that produces that nth item in the sequence when given an n via STDIN, or an other forms of standard input, where n is any positive number. However your two programs must be anagrams, meaning each can be rearranged from the other's letters.

Programs must output the decimal of the number followed by optional whitespace to STDOUT. Programs may output to STDERR however it should be ignored and if the hidden case does so it must be clearly stated that this is the case.

If you wish you may also output by character code. However if you do so in your hidden solution you must state such in the body of your submission.

You will then present the OEIS number, the source code for and the name of *one* language it is in.

Robbers will crack your submission if they find an anagram of the original submission that runs in a language other than the one you already presented. To crack an answer they must only find ***any*** language and program which produces the sequence and is an anagram of the original, not necessarily the answer the you were thinking about.

Thus you are incentivized to make it as hard as possible to find any language that does the task using their list of symbols.

## Scoring

This is so the shortest un-cracked program is the winner.

## Languages

Languages will be considered different if the two proposed solutions do not complete the task in both languages. This will include different versions of *the same language* as long as neither the cop's solution or the robber's solution produce the correct output in the other's language.

i.e. If the there are two solutions 1 and 2 that are in language A and B respectively solution 2 must not produce the correct output in language A and solution 1 must not produce the correct output in language B.

# Safety

Once your submission has been uncracked for a week you may post your solution and declare your post safe. If after a week you choose not to post a solution your answer may still be cracked.

# Answer
# ~~Python 2, 118 bytes, A042545~~ Cracked

```
i=input();s=1/(801**.5-28);a=[0,1]
for p in range(i):a+=[a[-2]+a[-1]*int(s)];s=1/(s-int(s))
print a[i]#,,,.//000fhlmo|

```

I didn't feel like implementing a trivial sequence, so I decided to go with my PPCG user ID. I wrote this in the other language first, which should give you a clue about what that language is, though I'd bet 100 dollars that this will be cracked in a golfing language before it's cracked in the intended other language.

**Note:** Due to floating-point precision errors, this is only accurate up to an input of 14. The intended solution is the same way.

## Intended solution, JavaScript (ES7)

```
for(i=prompt(),s=1/(801**.5-28),a=[1,0];i--;s=1/(s-n))
  n=s|0,a.unshift(a[1]+a[0]*n);
alert(a[0])  //#+2:[]giiiiinnpt

```

Works in pretty much the same way as the Python solution, though the sequence is stored largest-first rather than smallest-first due to the fact that JS does not support negative indexing.
> 15 votes

# Answer
# Brain-Flak, 24 bytes, A000290, Safe

Yet another square solution. This time there is nothing but parentheses

```
({(({}[()])()){}[()]}{})

```

---

The intended solution was in Brain-Flueue, a version of brain-flak that uses queues instead of stacks. The program was:

```
({(({})[()]){}}{})[()()]

```

The languages are considered distinct because neither of the two programs halt when run in the other language.
> 10 votes

# Answer
# ~~Python 2, 38 bytes, A000290~~ Cracked by Emigna

```
def e(X):return X*X
print e(input())##

```

This will probably be very easy to crack. I'm mostly posting this as a starting point.

Orignial solution in CJam:

```
ri:XX*e#def ()return X
e#pnt (input())

```
> 7 votes

# Answer
# ~~CJam, 7 bytes, A005843~~ Cracked!

```
ri2*e#^

```

This is a basic `2*n` sequence.

Explanation:

```
r          e# read input
 i         e# convert to integer
  2*       e# multiply it by 2
    e#^    e# this is a comment that is ignored by the interpreter

```

Try it online!

---

# Original Solution, Carrot

```
#^i*2er

```

Carrot is an esolang created by me. I have stopped developing it a long time ago. The reason I chose this is because I hoped that it would be hard for other languages to comment out the unnecessary parts of the code.

Explanation:

```
#^            This pushes the input to the stack (anything before the ^ is the stack)
  i           Convert stack to integer
   *2         Multiply it by 2
     er       These are ignored because they are not Carrot commands
              Implicit output

```

Try it online!
> 7 votes

# Answer
# ~~Brain-Flak, 44 bytes, A000290~~ Cracked

```
<({({})({}[()])}{}))()()()turpentine/"*"*4splint>

```

Try it online!

---

## Original solution, Python 2

```
print(input()**(len(set("{}{}{}[]()<>"))/4))

```
> 6 votes

# Answer
# ~~2sable, 15 bytes, A000290~~, Cracked!

Hopping on the same **n2** train :p.

```
*?"!#$&<=@\^{|}

```

Try it online!
> 6 votes

# Answer
# ~~Excel, 12 bytes, A000012~~ Cracked

```
=IF(1=1,1,1)

```

Maybe not the toughest, but a fun one to crack.
> 5 votes

# Answer
# Python 2, 25 bytes, A000583, cracked

```
Y=input("");print`Y**4`,X

```

This program exits with an error after printing the output.

---

My hidden code (substantially different from the cracked solution!):

## Actually, 25 bytes

```
4,n`*`Y")ii(*nppruttY;="X

```

Try it online!

Explanation:

```
4,n`*`Y")ii(*nppruttY;="X
4,n                        input, repeat 4 times
   `*`Y                    do * until the stack stops changing (fixed-point combinator)
       ")ii(*nppruttY;="X  push this string and immediately pop and discard it

```
> 5 votes

# Answer
# Python 2, 124 bytes, A144945, \[Safe\]

Cracking this would have earned you a 500 rep bounty! Too late!

> Number of ways to place 2 queens on an n X n chessboard so that they attack each other.

I hope it's not too easy. I arranged my code so the whitespace is clearly visible. Those are spaces and newlines only.

*Note: intended solution outputs via character code*

```
n=input();print((3+2)*n*n+~0*6*n+1)*n/3;            +6;

+7+7+7+7+7+7+7+7+7;+++++++++++++++9+9*9*9

```

**Try it online**

### Intended Solution, Headsecks:

```
r2=ni***p**
(

p((0 ;3+++3;+;/

)

i+++nn
 +)7
n

n+++

17+~
 +)7;97++++7

69+9n+ ++7+n 69
 +7+ ++7

**7+++tut

```

This is equivalent to the following BF program:

```
>>,[->>>+>>>+>>>+++++<<<<<<<<<]>>>->>>>>>-<<<[[>+<-]>[>>[<<<+>>+>-]<[>+<-]<-]<<<<]>>+++>[-<-[<+<<]<[+[->+<]<+<<]>>>>>]<<<.,.

```
> 5 votes

# Answer
# Python, 118 bytes, A042545, Safe

```
i=int(input());s=pow(801.0,0.5);a=[0|0,1]
for Moshprtflmah in range(i):s=1./(s%1);a+=[a[-2]+a[-1]*int(s)];
print(a[i])

```

This time it works in both 2 and 3. And there's no comments! What will you do?

Note: As with the old solution, this loses precision after the first 15 terms due to floating-point arithmetic errors.

## Intended solution, JavaScript (ES6)

```
giiiiinnnnprt:
i=prompt([n=+2]);s=Math.pow(801,.5);for(a=[1,0];i--;a.unshift(a[1]+a[0]*(s|0)))s=1/(s%1)
alert(a[0])

```

Though I kept several old versions, I somehow managed to lose *this* copy, but fortunately piecing it together from the others wasn't too hard. I see now that I had an extraneous `prt` in both programs that could have been golfed out. Oh well.
> 5 votes

# Answer
# Fuzzy Octo Guacamole, 26 bytes, A070627 \[Safe\]

```
49++*5^pm#]%:"?:.=:#,|"1:@

```

Test cases:

```
1 -> 1
3 -> 23
5 -> 1

```

Solution:

```
^::::|*?1=#@]","%.#49++5pm

```

Works in Magistack.
> 4 votes

# Answer
# ~~Python 2, 37 bytes, A000290~~ Cracked

```
print(input()**(1+1))
"'10°3¢','m'"

```
> 3 votes

# Answer
# MATL, 7 bytes, A000217, cracked

```
:sp{1}x

```

The sequence is `n(n+1)/2` (triangular numbers), starting at input `n=1` as specified by the challenge: `1`, `3`, `6`, `10`, ... (Output for input `0` is not guaranteed to be the same in the two programs).

The program in the other language exits with an error (after producing the correct output in STDOUT).

Try it online!

```
:            % Push [1 2 ... n], where n is implicit input
 s           % Sum of that array. Gives the desired result
   p         % Product of that. Gives the same number
    {1}      % Push a cell array containing number 1
       x     % Delete it

```
> 3 votes

# Answer
# Fuzzy Octo Guacamole, 11 bytes, A001844 \[Safe!\]

```
hha02^d+**+

```

A crack that sort-of works is `dh*h++^2*0a`, in Pyth. It's not the right output format though.

My code is still out there! (and it's not in Pyth)

Test Cases:

```
0 -> 1
1 -> 5

```

Solution:

```
^++d0ah*2*h

```

In Jolf.
> 3 votes

# Answer
# ~~Pyth, 75 bytes, A004526~~ Cracked, milk

More of a playful test than anything, but:

```
/Q/////////////////****22222 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2;;;;;

```

Try it online!

Milk's solution (Convex):

```
2/Q2 2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2*2*2*; 2*;                 2; 2; 2;

```

Try it online

Intended solution (///):

```
/*///;2/;// ///22/Q//2;///;//;***2222222222222222222222

```

Try it online

Takes input in the form of 2's before the last semicolon and outputs the correct number of Q's.

The sequence is 0-indexed (i.e. 0 is 0, 1 is 0, 2 is 1, ...)

Found slight syntactical mistakes in the ///, so edited all solutions.
> 3 votes

# Answer
# ~~Python 3, 27 bytes, A000012~~, Cracked

No input this time!

```
if 1:
    if 1:
        print( '1' )

```

The indents are tabs, but not to save bytes - they are required for whitespace.

I don't think it needs a TIO link or explanation!

(Probably won't take long to crack in some way)

Intended answer (Whitespace):

```
-Start-

    if1:if1:print('1')
-End-

```

(Start and end not part of the program)

Sorry, I forgot to add that it prints to STDERR:

Try it online!
> 3 votes

# Answer
# ~~MATL, 13 bytes, A002275~~  Cracked!

```
i:"@ax'1']
v!

```

Try it online!

Explanation:

```
i           % Grab input
 :          % Push (range(1,input))
  "         % For each element in this range:
   @        %   Push it
    a       %   Is is truthy?
     x      %   Delete it
      '1'   %   Push '1'
         ]  %   End loop
v           % Join all of these '1's together
 !          % Transpose and display

```
> 2 votes

# Answer
# ~~WinDbg, 39 bytes, A000007~~ Cracked by jimmy23013

```
~e.block{j(0>=@$t0)?@$t0+(1<7);??0}t":"

```

The difficult sequence of `0**n`.

Input is done by passing a value in the pseudo-register `$t0`.

My original solution was C#:

```
@t=>(object)(0<@t?0:1)??"$$700~lk.{}+";

```
> 2 votes

# Answer
# JavaScript ES6, 38 bytes, A000290, Cracked

```
J=>eval(Array(J).fill(J).join`+`)|2-2;

```

This square train is pretty nifty, but isn't going anywhere fast. (Get it? *square* train? as in, wheels? no? okay, fine. *critics*.)

---

Intended answer: Reticular (Try it online!),

```
in2Jo;=>eval(Array(J).fill(J).j`+`)|-2
in      take input, convert to number
  2J    raise to the second power
    o;  output and terminate; ignores following chars

```
> 2 votes

# Answer
# ~~2sable, 13 bytes, A002378~~, Cracked!

Hoping I didn't miss something. Computes **a(n) = n × (n + 1)**:

```
>*?"!&)<=@\\}

```

---

My version:

```
?"\>@&*})<\=!

```

Or the unfolded version:

```
  ? " \
 > @ & *
} ) < \ =
 ! . . .
  . . .

```

Note that the `>` in the top-left corner is unused (except for the 2sable program). I did this to confuse the robbers (but that obviously didn't work haha).

Try it online!
> 2 votes

# Answer
# Python 2, 35 bytes, A048735, Safe

```
print(lambda u:u&u<<1)(input())>>1

```

---

The original solution was in my own programming language Wise.

```
:<<>&>print(lambda uuu1)(input())1

```

Most of the characters are irrelevant no-ops. The important characters are the first six. `:` creates two copies of the first item on the stack. `<<>` bit shifts twice to the left and once to the right which is equivalent to bit shifting once to the left. `&` takes the bitwise and of the top and second item (the original and the bit shifted copy). Lastly `>` bit shifts once to the right.
> 2 votes

# Answer
# 05AB1E, 5 bytes, A000012, Safe

```
$;$1?

```

Sequence of 1's. Try it online

### Intended Solution: Arcyou

```
1;$$?

```

Try it online. I couldn't find documentation for this language, so don't have an explanation of how it works exactly.
> 2 votes

# Answer
# Befunge 93, 14 bytes, A121377,  Cracked by milk!

```
&52* %68*+ .@Q

```

Fun fact: The intended solution to this is the first time I've ever used that language.

My solution in Pyth. &@ print an error, but that goes to STDERR which according to the OP is ignored.

```
+%Q*5 2*6 8.&@

```
> 2 votes

# Answer
# 2sable, 15 bytes, A087156

```
D1QiA0*<}.;2->>

```

Try it online

The sequence of non-negative numbers, except for 1.
> 2 votes

# Answer
# ~~Python 2, 70 Bytes, A000217~~ Cracked!

I have a feeling this won't be cracked in the language I used for the other version, we will see :)

```
o=input()
v=0
i=1
while o:
 v+=i
 i+=1
print v

#|  d00->1@@@++-^,,[

```

---

I realized afterwards I had incorrectly obfuscated the code (it doesn't change the posted answer's validity). Here's the code I started with in Haystack:

```
v
0
v
0
i
1
-
>      d0[v
^-1@+@d+1@?,,o|

```
> 1 votes

# Answer
# ~~05AB1E, 9 bytes, A000042~~ Cracked!

```
1×,1*-^$)

```

This is the *Unary representation of natural numbers* (OEIS). So if the input was `3`, for example, then output would be `111`.

Explanation:

```
                    # implicit input
1                   # pushes 1 to the stack
 ×                  # pushes "1" × (the input)
  ,                 # outputs the stack
   1*-^$)           # irrelevant

```

Try it online!

---

# Original Solution, Carrot

```
1^*$-1×^)

```

Explanation

```
1^             Push "1" to the stack
  *            Multiply the string by
   $-1         ...the input (as an integer) minus 1 times
      ×,)      Ignored by the interpreter

```

The `*` multiplies the string by `(n+1)` times, so that `a^*3` results in `aaaa` and not `aaa`. So that is why I subtracted `1` from the input.

Only now I realise that the `)` has been irrelevant in both the languages :D

Try it online!
> 1 votes

# Answer
# 05AB1E, 8 bytes, A000042, Cracked

```
F1}J,(1&

```

Test cases:

```
1 -> 1
2 -> 11
3 -> 111

```
> 1 votes

# Answer
# J, 2 bytes, A000290, Cracked

```
*~

```

Well, might as well start going for those two-byters. Yields **n** × **n**, or **n**2.

## ~~intended solution, Jolf, 2 bytes~~

~~```
*~

```~~

~~Well. Yeah. This is my own language and I think it works because `~` looks for an extended character, but doesn't find one, so it just ignores it. ¯\\\_(ツ)\_/¯~~ Oops.
> 1 votes

# Answer
# ~~ABCR, 24 bytes, A023443~~ Cracked!

```
70: Quit xi. Classy queue!

```

There's a bunch of no-ops. Calculates `n - 1`.
> 1 votes

# Answer
## ~~Ouroboros, 6 bytes, A000012~~ Cracked

```
)49.o(

```

Always outputs `1`.
> 1 votes

# Answer
# 05AB1E, 5 bytes, A005843

```
ApDF>

```

Calculates `n*2`.
> 1 votes

# Answer
# ~~05AB1E, 5 bytes, A000012~~ Cracked!

```
¸WW/`

```

The funny thing is that the cracked version is the intended answer.

Try it online!
> 0 votes

---
Tags: code-golf, sequence, polyglot, cops-and-robbers
---


title: Polyglot Anagrams Robbers' Thread

text:
# Question
Title: Polyglot Anagrams Robbers' Thread
This is the robbers' thread of this challenge

The cops will choose an OEIS sequence and write two *full programs* in two different languages that produces that nth item in the sequence when given an n via STDIN. The two programs must be anagrams of each other, meaning each can be rearranged from the other's letters.

They will present the OEIS number, the source code for and the name of *one* language it is in.

You must find an anagram of the original cop's submission that runs in a language other than the one used by the cop. To crack an answer you must only find ***any*** language and program which produces the sequence and is an anagram of the original, not necessarily the answer the cop was thinking about.

You may output by character code or include STDERR in your solution, but only if the cop has indicated their hidden solution does so. Decimal output to STDOUT is always a valid crack.

Thus cops are incentivized to make it as hard as possible to find any language that does the task using their list of symbols.

## Scoring

The person with the most cracks will be the winner of this section. Only the first crack for each solution will count towards one's score.

## Leader Board

Big thanks to every one that took place in this challenge.

Here is the leader board as it stands

```
Place  User             Score
-----------------------------
1      Adnan            3
1      Kritixi Lithos   3
1      Emigna           3
1      milk             3
5      Steven H.        2
5      Wheat Wizard     2
5      jimmy23013       2
8      ETH Productions  1
8      Dennis           1
8      alleks           1
8      Martin Ender     1
8      Oliver           1
8      Conor O'Brien    1

```

# Answer
# 05AB1E, 38 bytes, Loovjo, A000290

```
nXtdief e():return X*X
pr e(input())##

```

Try it online!

Very likely not the intended solution, but it works.

**Explanation**

```
n      # square input
 X     # push 1
  t    # push sqrt(1)
   d   # push is_number(1.0)
    i  # if true do the rest of the code (1.0 is not a number so it will never execute)

```
> 9 votes

# Answer
# Jolf, 15 bytes, Adnan, A000290

```
*&"?!#$|<=@\^{}

```

Try it here! Definitely not the intended solution, but hey, it works.

## Explanation

```
*&"?!#$|<=@\^{}
*                multiply
 &               the two inputs to this func, x, y: x && y
                 returns y if x and y, or the falsey argument.
  "?!#$|<=@\^{}  this string is always truthy, so the second arg is used.
                 two implicit inputs are taken, both equal to the first arg
                 so, this corresponds to *xx, which is x^2.

```
> 8 votes

# Answer
# 05AB1E, 49 bytes, Wheat Wizard, A000290

Actually the same approach as Emigna's crack :p.

```
n4i<({({)({[()]){))()()()turpetne/"*"*splint>}}}}

```

Explanation:

```
n          # Square the input
 4i        # If 4 == 1, do the following...
   <({...

```

Try it online!
> 7 votes

# Answer
# 05AB1E, 35 bytes, Oliver, A000290

Cops should stop posting `n^2` challenges in python...

```
n0iprt(input()**(1+1))
"'1°3¢','m'"

```

Try it online!

**Explanation**

```
n    # square input
 0i  # if 0 == 1 do the rest of the code

```
> 7 votes

# Answer
# 2sable, 7 bytes, Kritixi Lithos, A005843

Code:

```
r^#ei2*

```

Explanation:

```
r         # Reverse the stack, which is a no-op
 ^        # XOR the input with itself, always leading to 0
  #       # If 1, break (which stops the program)
   e      # Compute input nPr input, which always leads to 1
    i     # If equal to one, do the following..
     2*   #   Multiply the input by 2.

```

Try it online!
> 6 votes

# Answer
# Hexagony, 13 bytes, Adnan, A002378

```
?"&\>=})\*!@<

```

Try it online!

Unfolded:

```
  ? " &
 \ > = }
) \ * ! @
 < . . .
  . . .

```

Not 100% whether this is the original, because the top left `\` is unused.

The `<\>` are just mirrors, so the program is actually entirely linear:

```
?"&)}=*!@

?          Read input.
 "         Move back and left.
  &        Copy input.
   )       Increment copy.
    }=     Move forward and right and turn around (to face the n and n+1 edges).
      *    Multiply.
       !   Print.
        @  Terminate.

```
> 6 votes

# Answer
# , 13 bytes, DJMcMayhem, A002275

```
v!:x]''"
@ai1

```

Try it online!

This might be the first solution in the language the author intended.

---

## Explanation

```
v!:x]''"   Does nothing
@ai1       inserts 1 a times

```
> 5 votes

# Answer
# 2sable, Conor O'Brien, A000290

```
~*

```

Try it online!

I don't know how it works, there's really only one program that meets the requirements and I just brute-forced to find the language it worked in.

After looking through the docs, I am able to come up with an explanation:

```
~         Push Input OR Input (always pushes the input)
 *        Multiply that by Input

```
> 5 votes

# Answer
# Pyth, 26 bytes, Steven H., A023443

Code:

```
tQ.qly 7:esau0euii s uxC !

```

Try online.

Fairly simple:

```
 Q                            Reads input
t                             Substracts 1 from it
  .q                          Quits program (implicit print)
    ly 7:esau0euii s uxC !    None of this ever plays a part...
                                I just thought it'd be fun to scramble it.

```
> 5 votes

# Answer
# Python 3, 118 bytes, ETHproductions, A042545

```
s,a=801**.5-28,[0,0==0]
for i in range(int(input())):a+=[a[i]+a[-1]*int(1/s)];s=1/s-1//s
(print(a[-2]),) #.0fhlmop|

```

Test it on Ideone.

### Cop submission

```
i=input();s=1/(801**.5-28);a=[0,1]
for p in range(i):a+=[a[-2]+a[-1]*int(s)];s=1/(s-int(s))
print a[i]#,,,.//000fhlmo|

```

### What's different

The cop submission doesn't work in Python 3 for two reasons.

* Python 2's *input* function automatically evals one line of input, while Python 3's counterpart just returns the line as a string. We can simply call *int* to fix this.
* `print` was a statement in Python 2, but it is a function in Python 3. In particular, that means that we have to surround its argument with parentheses.

That means we need `int()` and `()`, but those characters aren't all part of the comment. That means we must make some changes.

Instead of the fraction **s**, we keep track of **1/s**.

The initialization of **s**`s=1/(801**.5-28)` – becomes `s=801**.5-28`, saving the characters `1/()`.

The factor of **a\[-1\]** in the update of **a**`int(s)` – becomes `int(1/s)`, costing the characters `1/`.

The update of **s**`s=1/(s-int(s))` – becomes `s=1/s-1//s`, costing the characters `1//`, but saving the characters `(int())`.

The saved characters in `()(int())` cover those we needed to port the code to Python 3, but obtaining them cost us `1//`. We can take `//` from the comment, but we'll have to save `1` elsewhere.

One way (the only one?) of saving the needed `1` is to replace the `1` in the initialization of **a** with `0==0`. This costs those four characters, but we can take `00` from the comment.

So far, we have the following code.

```
i=int(input());s=801**.5-28;a=[0,0==0]
for p in range(i):a+=[a[-2]+a[-1]*int(1/s)];s=1/s-1//s
print(a[i]) #,,,.()0fhlmo|

```

To recover one of the `=` we now "owe", we can rewrite the initialization of **s** and **a** with a single assignment: `s,a=801**.5-28,[0,0==0]` Additionally, this saves a `;` and costs a `,`, which can be be added to and removed from the comment.

The second `=` can be saved by not storing the input in a variable, i.e., writing `range(int(input()))` instead, saving the characters in `i=`. We use **i** after the loop as well, but the **i**th element of **a** is just the second one from the right, so we can replace `i` with `-2`. For the same reason, `a[-2]` in the loop body can be replaced with `i`.

We now have a permutation into working Python 3 code:

```
s,a=801**.5-28,[0,0==0]
for i in range(int(input())):a+=[a[i]+a[-1]*int(1/s)];s=1/s-1//s
print(a[-2]) #,.()0fhlmop|

```

However, this code also works in Python 2! One way of fixing this is to replace `print(a[-2])` with `(print(a[-2]),)`; we have the characters we need in the comment. As mentioned before, *print* is a function in Python 3, so this constructs the tuple **(*None*,)**. However, Python 2's *print **statement*** is a *SyntaxError* inside a tuple literal.
> 5 votes

# Answer
# CJam, 39 bytes, milk, A000007

```
l~0{"e.bockj(>=@$t0)@$t0+(<7)??0t:"};1?

```

Try it here.
> 4 votes

# Answer
# Pyth, 7 bytes, Luis Mendo, A000217

```
x:{ps}1

```

As requested, the program exits with error after `p`rinting the correct answer.

Try it online here!
> 4 votes

# Answer
# 05AB1E, 12 bytes, tuskiomi, A000012

```
1,(FI1=1=1,)

```

Try it online!

**Explanation**

```
1,            # print 1
  (           # negate input
   F          # that many times do (i.e. no times)
    I1=1=1,)  # the rest of the code

```
> 3 votes

# Answer
# 05AB1E, 38 bytes, Conor O'Brien, A000290

```
n2iJ=>eval(Array(J).fill(J).jo`+`)|-2;

```

Try it Online!

---

## Explanation

This is based on Emigna's crack here.

```
n   #Squares the number
 2i #Runs the rest of the code if 2==1

```
> 3 votes

# Answer
# 05AB1E, 27 bytes, boboquack, A000012

```
1 1pif:
    if :
        rint( '1' )

```

Try it online

How it works:

```
1                     # push 1
  1                   # push 1
   p                  # pop (1), push is_prime(1)
    i                 # pop (is_prime(1), false), if is false so don't execute rest

```
> 3 votes

# Answer
# CJam, 70 bytes, Shebang, A000217

```
ri),:+

e#|  d00->1@@@++-^,[o=input(v=0i=1whil o v=i i+=1pnt v

```

Try it here.
> 2 votes

# Answer
# Convex, 75 bytes, boboquack, A004526

```
2/Q2 2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2*2*2*; 2*;                 2; 2; 2;

```

Try it online

How it works:

```
2  e# push 2
 / e# pop first 2, divide, push result
   e# push a bunch of garbage but discard it all with semi-colons (;)
  Q2 2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2/2*2*2*; 2*;                 2; 2; 2;

```
> 2 votes

# Answer
# Dip, 9 bytes, Kritixi Lithos

Definitely not the intended answer.

```
1^,-$)×1*

```

Explanation:

```
1$^,-)×   # Basically does nothing
       1* # Repeat "1" n times

```
> 2 votes

# Answer
# Pip, 6 bytes, DLosc, A000012

```
.()49o

```

I figured I'd try the OP's esolang first ;-)

Try it online.
> 2 votes

# Answer
# 05AB1E, 25 bytes, Mego, A000583

Code:

```
nnYi=put("");prit`Y**4`,X

```

Explanation:

```
n       # Square the input
 n      # Square the squared input
  Y     # Constant that pushes 2
   i    # If equal to 1, do the following:
    =put...

```

Try it online!
> 1 votes

# Answer
# Dip, 8 bytes, Oliver, A000042

```
(1J&F},1

```

### Explanation

```
              #Implicit Input
(             #Start range loop
 1            #Push 1 to the stack
  J           #Join all the elements in the stack
   &          #End program
    F},1      #These are ignored

```

The funny thing is that this was the intended language! Dip is an esolang created by Oliver.

### Test Cases and Running Dip from Command-Line

```
$python3 dip.py
Dip v1.0.0 by Oliver Ni.
>>> (1J&F},1
> 4
1111
>>> (1J&F},1
> 7
1111111

```
> 1 votes

# Answer
# 05AB1E, 4 bytes, Oliver, A000012

```
p¥_1

```

Try it online!

This is a sequence of `1`s.

```
              # Implicit input
p¥_           # Does nothing
   1          # Pushes 1 to the stack
              # Implicit output

```

This outputs `1` no matter what the input is.
> 1 votes

# Answer
# 2sable, 14 bytes, Dopapp, A121377

```
Q@5 2*%6 8*+.&

```

Try it online.

How it works (more or less):

```
Q@
  5              # Push 5
    2            # Push 2
     *           # Pop (2), pop (5), push 5*2=10
      %          # Pop (10), pop (input), push input%10
       6         # Push 6
         8       # Push 8
          *      # Pop (8), pop (6), push 8*6=48
           +     # Pop (48), pop (input), push input+48
            .&

```
> 1 votes

# Answer
# Dip, 5 bytes, Oliver, A000012

```
`¸WW/

```

The sequence just prints a `1` no matter what the input is. Oliver's answer prints a `1.0`. This program also prints a `1.0`. This apparently is the intended solution.

### Explanation

```
`¸                  # push character `¸`
  W                 # pushes 1000000
   W                # pushes 1000000 also
    /               # divides the last two items in stack resulting in 1.0
                    # implicit output (1.0)

```

### Alternative solution (courtesy of @milk)

# Convex, 5 bytes

```
WW¸`/

```

Try it online!

### Explanation

```
                  // implicit input
W                 // pushes -1
 W                // pushes -1 also
  ¸               // calculates the LCM of the two numbers (which evaluates to 1)
   `              // finds its string representation
    /             // slices the string (so that it would evaluate to "1")
                  // implicit output

```
> 1 votes

---
Tags: code-golf, sequence, polyglot, cops-and-robbers
---


title: Lead Your Turtle by a String

text:
# Question
Title: Lead Your Turtle by a String
Write a program or function that takes in a nonempty single-line string of printable ascii characters excluding space:

```
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

```

You may assume the input is valid.

Based on the input, draw a new string arranged on a textual grid of spaces and newlines following turtle graphics-esque rules where the turtle always occupies one grid space and can only face the cardinal directions.

Print the first character in the input string to the text grid. The turtle starts here facing right. Iterate over the rest of the characters in the input string (only stopping if the turtle gets stuck), repeating this process:

1. If the 4 grid spaces directly neighboring the turtle are all filled (i.e. none of them is a space), stop iterating. The turtle is stuck and the grid is as complete as it can be.
2. Look at the current character in the input compared to the previous character:

* If the current character is lexically before the previous, rotate the turtle a quarter turn left.
    * If the current character is lexically after the previous, rotate the turtle a quarter turn right.
    * If the current character equals the previous, don't rotate the turtle.
3. If the grid space the turtle is now facing is not empty (i.e. not a space), repeatedly rotate the turtle a quarter turn left until she is facing an empty grid space.
4. Move the turtle one grid step forward in the direction she's facing and print the current character on the grid in the turtle's new location.

Print or return the resulting text grid string with no extraneous rows or columns of whitespace. Lines may have trailing spaces up to the rightmost column with a non-space, but not beyond. A single trailing newline is optionally allowed.

**The shortest code in bytes wins.**

# Example

Here are all the steps of the input `spattuuxze`. The `^V<>` characters show the direction the turtle is facing, they are **not** part of the input or output.

```
s>
```

```
^
p
s
```

```
<ap
  s
```

```
^
t
ap
 s
```

```
^
t
t
ap
 s
```

```
tu>
t
ap
 s
```

```
tuu>
t
ap
 s
```

```
tuu
t x
apV
 s
```

```
tuu
<zx
ap
 s
```

At this point the turtle is stuck so the `e` never gets printed and the final output is:

```
tuu
tzx
ap
 s

```

Following is a similar but invalid output since it has an unnecessary leading column of whitespace:

```
 tuu
 tzx
 ap
  s

```

# Test Cases

```
spattuuxze

tuu
tzx
ap
 s

spattuuxxze

tuu
t x
apx
 sze

1111111

1111111

ABCDEFGHIJKLMNOP

PEFG
ODAH
NCBI
MLKJ

`_^]\[ZYXWVUTSR

 ^_RS
\]`UT
[ZWV
 YX

Woo!

W
o
o!

woo!

!o
 o
 w

Wheeee

W
heeee

banana

  a
 an
an
b

Turtle

T
ure
 tl

turTle

  e
tTl
ur

```

<sup>(Do tell me right away if any of these seem wrong.)</sup>

# Answer
> 1 votes
# Groovy (357 Bytes)

No external turtle libs were used and no turtles were harmed.

```
R={s->s[0]?[0,-1*s[0]]:[s[1],0]}
L={s->s[0]?[0,s[0]]:[-1*s[1],0]}
def y(s){l=s.length()*2;z(new String[l][l],[l/4,l/4],s,null,[0,1])}
def z(g,l,w,p,h){if(w.length() && !g[(int)(l[0]+h[0])][(int)(l[1]+h[1])]){c=w.getAt(0);w=w.substring(1);if(p && p<c){h=R(h)}else if(p>c){h=L(h)};g[(int)l[0]+h[0]][(int)l[1]+h[1]]=c;z(g,[l[0]+h[0],l[1]+h[1]],w,c,h)}else{g}}

```

Try it here: https://groovyconsole.appspot.com/edit/5115774872059904

---

# Previous Attempts

## Groovy (397 Bytes)

```
rotR={s->s[0]!=0?[0,-1*s[0]]:[s[1],0]}
rotL={s->s[0]!=0?[0,s[0]]:[-1*s[1],0]}
def y(s){z(new String[s.length()][s.length()],[s.length()/2,s.length()/2],s,null,[0,1])}
def z(g,l,w,p,h){if(w.length() && !g[(int)(l[0]+h[0])][(int)(l[1]+h[1])]){c=w.getAt(0);w=w.substring(1);if(p && p<c){h=rotR(h)}else if(p > c){h=rotL(h)};g[(int)l[0]+h[0]][(int)l[1]+h[1]]=c;z(g,[l[0]+h[0],l[1]+h[1]],w,c,h)}else{g}}

```

https://groovyconsole.appspot.com/script/5179465747398656

# Answer
> 0 votes
# Java, ~~408~~ 406 bytes

```
String f(String I){int l=I.length(),x=l,y=x,z=x,t=y,Z=x,T=y,d=1,i=1,a;char[][]g=new char[l*2][l*2];int[]D={-1,0,1,0};for(char c,p=g[x][y]=I.charAt(0);i<l;p=c){c=I.charAt(i++);d=((c<p?d-1:c>p?d+1:d)+4)%4;for(a=0;g[x+D[d]][y+D[3-d]]>0&&a++<4;)d=(d+3)%4;if(a>3)break;g[x+=D[d]][y+=D[3-d]]=c;z=z<x?z:x;Z=Z>x?Z:x;t=t<y?t:y;T=T>y?T:y;}for(I="";z<=Z;z++,I+="\n")for(a=t;a<=T;a++)I+=g[z][a]<1?32:g[z][a];return I;}

```

The function gets the the input as String and returns the outcome as a String.

Internally it uses a 2D char array to store the letters and keeps the min and max columns and rows used in order to return the sub-array that was used.

So, in the outcome String there are no leading columns of white-spaces but there are trailing white-spaces up to the rightmost column with a non-space character. A newline is added at the end.

Any suggestions to golf it more are welcome :-)

# Answer
> 0 votes
# Python3, ~~419~~ 414 bytes

```
Z=input();l=r=c=M=R=C=N=len(Z);t=(r*2)+1;A=[0]*t;J=range
for i in J(t):A[i]=[" "]*t
A[r][c]=Z[0];i=1;Q=[1,0,-1,0];d=q=0
while i<l:
 if Z[i]<Z[i-1]:d+=3
 elif Z[i]>Z[i-1]:d+=1
 while A[r+Q[(d-1)%4]][c+Q[d%4]]!=" "and q<4:d+=3;q+=1
 if q>3:break
 r+=Q[(d-1)%4];c+=Q[d%4];R=min(R,r);C=min(C,c);M=max(M,r);N=max(N,c);A[r][c]=Z[i];i+=1;q=0
for i in J(R,M+1):
 for j in J(C,N+1):print(A[i][j],end="")
 print()

```

---
Tags: code-golf, string, grid
---


title: Convert to camelCase

text:
# Question
Title: Convert to camelCase
# The Challenge

I was reading Google's Java Style Guide the other day and stumbled over their algorithm to convert any arbitrary string into camelCase notation. In this challenge you have to implement this algorithm since you don't want to do all this stuff in your head when you are writing your super competitive Java submissions to code-golf challenges.

*Note: I made some small adjustments to the algorithm. You need to use the one specified below.*

# The algorithm

You start with an arbitrary input string and apply the following operations to it:

1. Remove all apostrophes ``'`
2. Split the result into words by splitting at

* characters that are not alphanumerical and not a digit `[^a-zA-Z0-9]`
* Uppercase letters which are surrounded by lowercase letters on both sides. `abcDefGhI jk` for example yields `abc Def Ghi jk`

3. Lowercase every word.
4. Uppercase the first character of every but the first word.
5. Join all words back together.

### Additional notes

* The input will only contain printable ASCII.
* If a digit is the first letter in a word, leave it as it is and don't capitalize something else in this word.
* The input will always have at least one character.

# Rules

# Test cases

```
"Programming Puzzles & Code Golf" -> "programmingPuzzlesCodeGolf"
"XML HTTP request" -> "xmlHttpRequest"
"supports IPv6 on iOS?" -> "supportsIpv6OnIos"
"SomeThing w1th, apo'strophe's and' punc]tuation" -> "someThingW1thApostrophesAndPuncTuation"
"nothing special" -> "nothingSpecial"
"5pecial ca5e" -> "5pecialCa5e"
"1337" -> "1337"
"1337-spEAk" -> "1337Speak"
"whatA mess" -> "whataMess"
"abcD" -> "abcd"
"a" -> "a"
"B" -> "b"

```

**Happy Coding!**

# Answer
## Retina, 56 bytes

Byte count assumes ISO 8859-1 encoding.

```
T`'\`
S_`\W|_|(?<=[a-z])(?=[A-Z][a-z])
T`L`l
T`l`L`¶.
¶

```

Try it online!

### Explanation

This implements the specification quite literally:

```
T`'\`

```

Remove apostrophes and backticks.

```
S_`\W|_|(?<=[a-z])(?=[A-Z][a-z])

```

Split the string around non-word characters (in regex this also excludes digits and underscores), or underscores or positions that have a lower case letter on the left and and upper case, lower case on the right. This would create some empty segments when there are two non-letter, non-digit characters in a row, or more important at the beginning of the string. We get rid of those with the `_` option. Here, "splitting" means put each remaining part on its own line.

```
T`L`l

```

Convert everything to lower case.

```
T`l`L`¶.

```

Convert each character that occurs after the linefeed to upper case. This will conveniently skip the first word because there's no linefeed in front of it.

Get rid of the linefeeds to join everything back together.
> 13 votes

# Answer
## Java, ~~198~~ 190 bytes

*+3 bytes because I forgot that `\W+` == `[^a-zA-Z0-9_]+` and I need to match `[^a-zA-Z0-9]+`*

*-11 bytes thanks to user20093 \- `?:` instead of `if`/`else`*

Because, Java.

```
s->{String[]a=s.replaceAll("`|'","").split("[\\W_]+|(?<=[a-z])(?=[A-Z][a-z])");s="";for(String w:a){String t=w.toLowerCase();s+=a[0]==w?t:t.toUpperCase().charAt(0)+t.substring(1);}return s;}

```

This is a lambda. Call like so:

```
UnaryOperator<String> op = s->{String[]a=s.replaceAll("`|'","").split("[\\W_]+|(?<=[a-z])(?=[A-Z][a-z])");s="";for(String w:a){String t=w.toLowerCase();s+=a[0]==w?t:t.toUpperCase().charAt(0)+t.substring(1);}return s;};
System.out.println(op.apply("Programming Puzzles & Code Golf"));

```

Readable version:

```
public static String toCamelCase(String s) {
    String[] tokens = s
            .replaceAll("`|'", "") // 1. Remove all apostrophes
            .split("[\\W_]+|(?<=[a-z])(?=[A-Z][a-z])"); // 2. Split on [\W_]+ or between [a-z] and [A-Z][a-z]
    s = ""; // Reusing s for building output is cheap
    for (String token : tokens) {
        String lowercaseToken = token.toLowerCase(); // 3. Lowercase every word
        s += tokens[0].equals(token)?lowercaseToken:lowercaseToken.toUpperCase().charAt(0) + lowercaseToken.substring(1); // 4. Uppercase first char of all but first word
        // ^ 5. Join all words back together
    }
    return s;
}

```
> 10 votes

# Answer
# JavaScript (ES6), ~~156~~ ~~154~~ ~~152~~ ~~148~~ ~~145~~ ~~141~~ 140 bytes

*Thanks @Neil (6 bytes), @ETHproductions (3 bytes), and @edc65 (7 bytes)*

```
a=>a[r='replace'](/`|'/g,a='')[r](/[a-z](?=[A-Z][a-z])/g,'$& ')[r](/[^\W_]+/g,b=>a+=(a?b[0].toUpperCase():'')+b.slice(!!a).toLowerCase())&&a

```

Removes apostrophes, then does a replace to split on special characters/before surrounded capitals, then combines with proper casing. Unfortunately, `toLowerCase()` and `toUpperCase()` are annoyingly long and hard to avoid here...
> 9 votes

# Answer
## vim, ~~69~~ ~~68~~ 66

```
:s/[`']//g<cr>:s/[a-z]\zs\ze[A-Z][a-z]\|\W\|_/\r/g<cr>o<esc>guggj<C-v>GgU:%s/\n<cr>

```

vim shorter than Perl?! What is this madness?

```
:s/[`']//g<cr>           remove ` and '
:s/                      match...
 [a-z]\zs\ze[A-Z][a-z]   right before a lowercase-surrounded uppercase letter
 \|\W\|_                 or a non-word char or underscore
 /\r/g<cr>               insert newlines between parts
o<esc>                   add an extra line at the end, necessary later...
gugg                     lowercasify everything
j                        go to line 2 (this is why we added the extra line)
<C-v>G                   visual select the first char of all-but-first line
gU                       uppercase
:%s/\n<cr>               join all lines into one

```

Thanks to Neil for spotting a useless keystroke!
> 6 votes

# Answer
## Mathematica 10.1, 101 bytes

```
""<>(ToCamelCase@{##2}~Prepend~ToLowerCase@#&@@StringCases[StringDelete[#,"`"|"'"],WordCharacter..])&

```

Uses the undocumented `ToCamelCase`, which works similarly to `Capitalize` but sets other characters to lowercase.
> 5 votes

# Answer
# Julia, ~~98~~ 89 bytes

```
s->lcfirst(join(map(ucfirst,split(replace(s,r"['`]",""),r"[a-z]\K(?=[A-Z][a-z])|\W|_"))))

```

This is an anonymous function that accepts a string and returns a string. To call it, assign it to a variable.

The approach here is the same as in Doorknob's Perl answer: `replace` apostrophes and backticks with the empty string, `split` into an array on a regular expression that matches the necessary cases, `map` the `ucfirst` function over the array to uppercase the first letter of each element, `join` the array back into a string, and `lcfirst` the result to convert the first character to lowercase.
> 4 votes

# Answer
# Perl 67 + 1 = 68 bytes

```
y/'`//d;s/([a-z](?=[A-Z][a-z]))|\W|_/$1 /g;$_=lc;s/^ +| +(.)/\u$1/g

```

Requires the `-p` flag, and `-l` for multi line:

```
$ perl -pl camelCase.pl input.txt
programmingPuzzlesCodeGolf
xmlHttpRequest
supportsIpv6OnIos:
someThingW1thApostrophesAndPuncTuation
nothingSpecial
5pecialCa5e
1337
1337Speak
abcd

```

How it works:

```
y/'`//d;                            # Remove ' and `
s/([a-z](?=[A-Z][a-z]))|\W|_/$1 /g; # Replace according to '2. Split...' this will create
                                    #   a space separated string.
$_=lc;                              # lower case string
s/^ +| +(.)/\u$1/g                  # CamelCase the space separated string and remove any
                                    #   potential leading spaces.

```
> 3 votes

# Answer
# Lua, 127 Bytes

```
t=''l=t.lower z=io.read()for x in z:gmatch('%w+')do t=t..(t==''and l(x:sub(1,1))or x:sub(1,1):upper())..l(x:sub(2))end return t

```

Accepts a string from stdin and returns camelized results.

Probably still gonna look for a better solution as storing everything in a variable feels inefficient.

But anyhow, pretty simple in general:

```
 z:gmatch('%w+')

```

This is the beauty that saved me a bit of bytes. gmatch will split the string based on the pattern: `%w+` which grabs only alphanumerics.

After that it's simple string operations. string.upper, string.lower and done.
> 2 votes

# Answer
# PHP, ~~145~~ ~~122~~ 133 bytes

```
<?=join(split(" ",lcfirst(ucwords(strtolower(preg_replace(["#`|'#","#\W|_#","#([a-z])([A-Z][a-z])#"],[""," ","$1 $2"],$argv[1]))))));

```

Save to file, call from CLI.
Takes input from a single command line argument; escape quotes and whitespace where necessary.

**breakdown**

```
<?=                 // 9. print result
join(split(" ",     // 8. remove spaces
    lcfirst(        // 7. lowercase first character
    ucwords(        // 6. uppercase first character in every word
    strtolower(     // 5. lowercase everything
    preg_replace(
        ["#`|'#",   "#\W|_#",   "#([a-z])([A-Z][a-z])#"],
        ["",        " ",        "$1 $2"],
        // 2. replace apostrophes with empty string (remove them)
                    // 3. replace non-word characters with space
                                // 4. insert space before solitude uppercase
        $argv[1]    // 1. take input from command line
    ))))
));

```

`lcfirst` allowed to reduce this to a single command, saving 23 bytes.
Fixing the apostrophes cost 11 bytes for the additional replace case.
> 2 votes

# Answer
## Perl, ~~87~~ ~~80~~ 78 bytes

```
y/'`//d;$_=join'',map{ucfirst lc}split/[a-z]\K(?=[A-Z][a-z])|\W|_/,$_;lcfirst

```

Byte added for the `-p` flag.

First, we use the `y///` transliteration operator to `d`elete all `'`` characters in the input:

```
y/'`//d;

```

Then comes the meat of the code:

```
                         split/[a-z]\K(?=[A-Z][a-z])|\W|_/,$_;

```

(split the input string `$_` in the appropriate locations, using the fancy `\K` in the match string to exclude the portion preceding it from the actual match)

```
          map{ucfirst lc}

```

(map over each split portion of the string and make the entire string lowercase, then make the first character of the modified string uppercase)

```
$_=join'',

```

(join on empty string and re-assign to magic underscore `$_`, which gets printed at the end)

Finally, we lowercase the first letter ~~by regex-matching it and using `\l` in the replacement string~~ with a builtin, saving 2 bytes over the previous method:

```
lcfirst

```

Thanks to @MartinBüttner for 7 bytes (`[^a-zA-Z\d]` -\> `\W|_`)!
> 1 votes

# Answer
# Scala, ~~181~~ ~~170~~ 144

```
def f(s:String)={val l=s.replaceAll("'|`","")split("[\\W_]+|(?<=[a-z])(?=[A-Z][a-z])")map(_.toLowerCase);l(0)+l.tail.map(_.capitalize).mkString}

```

Tester:

```
val testCases = List(
  "Programming Puzzles & Code Golf" -> "programmingPuzzlesCodeGolf",
  "XML HTTP request" -> "xmlHttpRequest"
  // etc
)
println(testCases.map(t=>if(t._2!=f(t._1))s"FAIL:${f(t._1)}"else"PASS").mkString("\n"))

```

Props to CAD97 and apologies to Nathan Merrill :)
> 1 votes

# Answer
# Kotlin, 160 Bytes

```
fun a(s: String)=s.replace(Regex("['`]"),"").split(Regex("[\\W_]+|(?<=[a-z])(?=[A-Z][a-z])")).map{it.toLowerCase().capitalize()}.joinToString("").decapitalize()

```

My goal was to be Scala, the other "alternative Java", so I'm somewhat happy with my results. I stole the regex from the Java answer.

Test it with:

```
fun main(args: Array<String>) {
    val testCases = arrayOf(
            "Programming Puzzles & Code Golf",
            "XML HTTP request",
            "supports IPv6 on iOS?",
            "SomeThing w1th, apo'strophe's and' punc]tuation",
            "nothing special",
            "5pecial ca5e",
            "1337",
            "1337-spEAk",
            "abcD",
            "a",
            "B")
    testCases.forEach { println(a(it)) }

}

```
> 1 votes

# Answer
# C 272 characters

C program pass string to camelCase in quotes as argument 1. There are lot's of gotchas in this problem statement...

```
#define S strlen(t)
#define A isalnum(t[i])
j=0;main(i,v)char**v;{char*p=v[1],*t;char o[99]={0};while(t=strtok(p," [{(~!@#$%^*-+=)}]")){i=0;p+=S+1;while((!A)&&i<S)i++;if(i!=S){o[j]=((j++==0)?tolower(t[i++]):toupper(t[i++]));while(i<S){if(A)o[j++]=t[i];i++;}}}puts(o);}

```
> 0 votes

# Answer
# JavaScript, 123 bytes

```
v=>v[r="replace"](/[`']/g,"")[r](/^.|.$|[A-Z][^a-z]+/g,x=>x.toLowerCase())[r](/[^a-z0-9]+./ig,x=>x.slice(-1).toUpperCase())

```

Readable version

```
v=>
  v.replace(/[`']/g,"")
  .replace(/^.|.$|[A-Z][^a-z]+/g,x=>x.toLowerCase())
  .replace(/[^a-z0-9]+./ig,x=>x.slice(-1).toUpperCase())

```

Remove the apostrophes, make the first character lower case, the last character lowercase, and any grouping of multiple uppercase characters, match any group of 1 or more non-alphanumeric chars + 1 other character, replace with that last character capitalized.

\[r="replace"\] trick from Mrw247's solution.
> 0 votes

---
Tags: code-golf, string
---


title: Alternating Fibonacci

text:
# Question
Title: Alternating Fibonacci
In the alternating Fibonacci sequence, you first start with `1` and `1` as usual.

However, instead of always adding the last two values to get the next number, you alternate starting with adding, and every other time you subtract instead.

The sequence starts like this:

```
1
1
2    # 1 + 1
-1   # 1 - 2
1    # 2 + -1
-2   # -1 - 1
-1   # 1 + -2
-1   # -2 - -1
-2   # -1 + -1
1    # -1 - -2
-1   # -2 + 1
2    # 1 - -1
1    # -1 + 2
1    # 2 - 1

```

etc.

Notice that after it starts over once it gets to `1` and `1` again.

Given a number *N*, print the *N*th term of the alternating fibonacci sequence.

Remember, this is , so the code with the smallest number of bytes wins.

# Answer
> 17 votes
# JavaScript (ES6), 25 bytes

```
n=>"334130110314"[n%12]-2

```

0-indexed. You can shorten the string with a slightly recursive version, though it adds 6 bytes:

```
f=n=>"3341301"[n]-2||f(13-n%12)

```

This is still shorter than the definitive recursive formula:

```
f=n=>n<2||f(n-2)+f(n-1)*(-n%2|1)

```

# Answer
> 8 votes
## Python, 31 bytes

```
lambda n:2-33107256/5**(n%12)%5

```

Doesn't bother trying to compute the value. Just looks in up in the peroidic length-12 list `[1, 1, 2, -1, 1, -2, -1, -1, -2, 1, -1, 2]`, which is compressed in base 5.

Compare to a recursive solution (37 bytes) with `True`'s for 1:

```
f=lambda n:n<2or(-1)**n*f(n-1)+f(n-2)

```

or to string storage

```
lambda n:int('334130110314'[n%12])-2

```

or an attempt at an arithmetical expression.

```
lambda n:4**n%7%3*(-1)**((n+n%2*4)/6)

```

# Answer
> 7 votes
# Oasis, 10 bytes

Reminds me to implement some more built-ins :p. The input is **0-indexed**.

Code:

```
n>2%x<*c+V

```

Translated version:

```
a(n) = (2*((n+1)%2)-1) * a(n-1) + a(n-2)
a(1) = 1
a(0) = 1

```

And calculates the *n*th term.

Try it online!

# Answer
> 5 votes
# 05AB1E, 10 bytes

```
•É&Â†º•sèÍ

```

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

# Answer
> 4 votes
# Jelly, 12 bytes

```
“½Ġ⁻S’b5_2⁸ị

```

**TryItOnline!**

1-based, given the first and second values are `1`.

Not sure if this is shorter yet, but for this I noted that the series has a period of 12:
`[1, 1, 2, -1, 1, -2, -1, -1, -2, 1, -1, 2]`

So, I took that and added `2` to give
`[3, 3, 4, 1, 3, 0, 1, 1, 0, 3, 1, 4]`
then converted that as a base `5` number to base `250`, to give:
`[11, 197, 140, 84]`
(which is `184222584`).

```
“½Ġ⁻S’b5_2⁸ị - Main link: n
“½Ġ⁻S’       - base 250 number      184222584
      b5     - convert to base 5   [3, 3, 4, 1, 3, 0, 1, 1, 0, 3, 1, 4]
        _2   - subtract 2          [1, 1, 2, -1, 1, -2, -1, -1, -2, 1, -1, 2]
          ⁸  - left argument, n
           ị - index into (1-based and modular)

```

# Answer
> 4 votes
# Pyth - 13 bytes

Base encoded once cycle series, modular indexed.

```
@-R2jC"
ûx"5

```

Try it online here.

# Answer
> 4 votes
# Haskell, ~~33~~ 26 bytes

```
a!b=a:b:(a+b)!(-a)
(1!1!!)

```

Recursive approach. 0-indexed. Try it on Ideone.
Saved 7 bytes thanks to xnor.

Usage:

```
Prelude> (1!1!!)11
2

```

# Answer
> 3 votes
# MATL, ~~17~~ ~~16~~ 15 bytes

```
'"Bl)e'F5Za2-i)

```

Input is 1-based.

Try it online!

### Explanation

The sequence has period `[1 1 2 -1 1 -2 -1 -1 -2 1 -1 2]`.

```
'"Bl)e     % Compressed array [1 1 2 -1 1 -2 -1 -1 -2 1 -1 2] with source
           % alphabet [-2 -1 0 1 2]
F5Za       % Decompress with target alphabet [0 1 2 3 4]
2-         % Subtract 2 to transform alphabet into [-2 -1 0 1 2]
i)         % Input N and use as (modular, 1-based) index into the sequence

```

# Answer
> 3 votes
# Mathematica, 40 bytes

Just creates a lookup table and accesses it cyclically, as in ETHproductions's answer. Unnamed function, 1-indexed.

```
Join[s={2,1,1,2,-1,1},-s][[#~Mod~12+1]]&

```

# Answer
> 3 votes
# WinDbg, 26 bytes

```
?(85824331b>>@$t0%c*3&7)-2

```

Input is passed in through the pseudo-register `$t0`. 0-indexed. +2 of each term in the sequence is stored in 3 bits making `85824331b`.

How it works:

```
? (85824331b >> @$t0 % c * 3 & 7) - 2 ;*? Evalutes the expression. Shifts 85824331b to get
                                       *the 3 bits for the @$t0'th term (mod c (12) when
                                       *the sequence repeats). Bitwise AND by 7 to get the
                                       *desired 3 bits, finally subtract 2 since the terms
                                       *where stored as +2.

```

Sample output, a loop printing the first 14 values of the sequence:

```
0:000> .for(r$t0=0;@$t0<e;r$t0=@$t0+1){?(85824331b>>@$t0%c*3&7)-2}
Evaluate expression: 1 = 00000001
Evaluate expression: 1 = 00000001
Evaluate expression: 2 = 00000002
Evaluate expression: -1 = ffffffff
Evaluate expression: 1 = 00000001
Evaluate expression: -2 = fffffffe
Evaluate expression: -1 = ffffffff
Evaluate expression: -1 = ffffffff
Evaluate expression: -2 = fffffffe
Evaluate expression: 1 = 00000001
Evaluate expression: -1 = ffffffff
Evaluate expression: 2 = 00000002
Evaluate expression: 1 = 00000001
Evaluate expression: 1 = 00000001

```

# Answer
> 3 votes
# Java, 32 bytes

```
n->"334130110314".charAt(n%12)-50

```

Since this is Java, the answer is 0-indexed.

## Testing and ungolfed:

```
class Ideone {
  public static void main (String[] args) throws Exception {
    java.util.function.IntFunction f = n->"334130110314".charAt(n%12)-50;
    for (int i = 0; i < 12; i++) {
      System.out.printf("%d -> %d%n", i, f.apply(i));
    }
  }
}

```

Test on Ideone

# Answer
> 2 votes
# Mathematica, ~~45~~ ~~41~~ 38 bytes

Thanks to @MartinEnder for 3 bytes.

```
±0=±1=1;±n_:=±(n-2)+±(n-1)(1-2n~Mod~2)

```

0-indexed.

**Usage**

```
±5

```

> `-2`

# Answer
> 1 votes
# Perl 6,  ~~39 35~~  32 bytes

```
{(1,1,{|(($/=$^a+$^b),$b-$/)}...*)[$_]}

```

```
{(|(334130110314.comb X-2)xx*)[$_]}

```

```
{(|334130110314.comb xx*)[$_]-2}

```

```
{334130110314.substr($_%12,1)-2}

```

# Answer
> 1 votes
# R, 38 bytes

Uses the lookup table solution inspired by @ETHproductions JS answer.

```
c(s<-c(2,1,1,2,-1,1),-s)[scan()%%12+1]

```

Edit: Forgot to mention that this is 1-indexed.

# Answer
> 1 votes
# C#, 117 Bytes

Golfed:

```
int A(int n){var f=new List<int>{0,1,1};for(int i=3;i<=n;i++){f.Add(i%2>0?f[i-1]+f[i-2]:f[i-2]-f[i-1]);}return f[n];}

```

Ungolfed:

```
public int A(int n)
{
  var f = new List<int> { 0, 1, 1 };

  for (int i = 3; i <= n; i++)
  {
    f.Add(i % 2 > 0 ? f[i - 1] + f[i - 2] : f[i - 2] - f[i - 1]);
  }

  return f[n];
}

```

Testing:

```
var alternatingFibonacci = new AlternatingFibonacci();
Console.WriteLine(alternatingFibonacci.B(10));
1

```

# Answer
> 1 votes
# Actually, 22 bytes

```
34*@%"334130110314"E≈¬

```

Try it online!

Explanation:

```
34*@%"334130110314"E≈¬
34*@%                   input % 12
     "334130110314"E    get that character in the string
                    ≈¬  convert to int, subtract 2

```

# Answer
> 1 votes
# Java 7, ~~88~~ ~~82~~ 79 bytes

golfed:

```
int f(int n){int c,i=0,a=1,b=1;for(;i<n;){c=i++%2>0?a-b:a+b;a=b;b=c;}return b;}

```

ungolfed:

```
int f(int n)
{
    int c, i = 0, a = 1, b = 1;
    for (; i < n;)
    {
        c = i++ % 2 > 0 ? a - b : a + b;
        a = b;
        b = c;
    }
    return b;
}

```

Try it online

# Answer
> 1 votes
## DC, 55 bytes

```
?sd[ln1+snly[[+2Q]sEln2%1=E-]xlyrsylnld>r]sr1sy0sn1lrxp

```

0-indexed.

```
?sd                                                     takes input and stores
                                                        it in register d

                                            1sy0sn1     stores 1 in register y
                                                        and 0 in register n and
                                                        appends 1 to the stack

   [ln1+snly                                            adds 1 to register n and
                                                        appends the value of
                                                        register y to the stack

            [[+2Q]sEln2%1=E-]                           adds or subtracts the
                                                        the two values on the
                                                        stack depending on
                                                        parity of n

                             xlyrsylnld>r]              does the rest of the
                                                        stuff required to store
                                                        the new values properly
                                                        and quits if it has
                                                        done enough iterations

                                          sr            stores the main macro
                                                        in register r

                                                   lrxp executes the macro and
                                                        prints the stack

```

Register d stores the index of the value. Register n counts the number of iterations completed. Register r stores the main macro. Register y stores the later value in the sequence, while the stack contains the earlier value in the sequence.

Visual explanation of whats going on in the big loop (assuming addition):

```
register: y=1     y=1   y=1    y=1   y=1    y=2
stack:     1      1 1    2     2 1   1 2     1
               ly     +     ly     r     sy

```

The check to determine whether to add or subtract takes the counter modulo two and uses this trick to make an if then else construction.

At the end the stack contains a single number, the desired value, which is printed with `p`.

(I'm new to `dc`, so I'd expect there are some obvious improvements to be made here.)

# Answer
> 0 votes
# ForceLang, 153 bytes

```
def s set
s a 1
s b 1
s p 1
s k io.readnum()
if k=0
goto b
label a
s c b.mult p
s c a+c
s a b
s b c
s p p.mult -1
s k k+-1
if k
goto a
label b
io.write a

```

# Answer
> 0 votes
# Turtlèd, 35 bytes

```
#112-1_--_1-2#?:[*l+].(-r'1)(_"-2")

```

0 indexed

## Explanation:

```
#112-1_--_1-2#                      the 12 values of sequence. - is -1, _ is -2
              ?:                    input a number and move right that many
                [*l+]               move back to the asterisk on start cell,
                                    increment sting pointer by amount moved
                     .              write pointed char
                      (-r'1)        if it was -, move right, write 1
                            (_"-2") if it was _, write "-2"
      [print grid]

```

### Try it online!

# Answer
> 0 votes
# ABCR, 43 bytes

```
)AAB)ABB..A))A..A)AA(ABB.)A+A)))AiB5aAb(Bxo

```

Explanation: the first part (`)AAB)ABB..A))A..A)AA(ABB.)A+A)))A`) sets up queue A to contain \[1, 1, 2, -1, 1, -2, -1, -1, -2, 1, -1, 2\], keeping all other queues empty. `iB` stores our desired term, and the loop `5aAb(Bx` cycles through the the queue that many times. `o` prints the front of the queue as a number, which will then be our desired answer.

# Answer
> 0 votes
## Batch, 49 bytes

```
@cmd/cset/a"n=%1%%12,~!(n%%3)*(1|-!(n%%5*(n/4)))"

```

Takes input as a command-line parameter. Explanation: Closed form uses the following observations:

* Sequence is cyclic with period 12
* Every third term is ±2 while other terms are ±1
* Terms after the third are negative except multiples of 5 (after reducing modulo 12)

We therefore start by reducing modulo 12 (to save 2 bytes). We then reduce modulo three and invert the result, which is 1 for multiples of 3 or 0 otherwise. We then bitwise not that value, giving us -2 for multiples of 3 or -1 otherwise. We then reduce modulo 5 and separately divide by 4, giving zero for terms 1, 2, 3, 5, 10 and 12 (0). Inverting and negating gives us -1 for those values and zero for other values. We then bitwise or that with 1 and multiply with the earlier calculation.

# Answer
> 0 votes
# TI-Basic, 26 bytes

Unfortunately, very uninteresting approach. I could not find anything shorter. The list is 1-indexed.

```
Input :{1,1,2,-1,1,-2:augment(Ans,-Ans:Ans(X

```

# Answer
> 0 votes
## C#, ~~73~~ 71 bytes

This uses 0-indexed values of n.

```
n=>{int a=1,b=1,i=0,r;for(;++i<n;){r=i%2>0?a+b:a-b;a=b;b=r;}return b;};

```

Formatted version:

```
Func<int, int> f = n =>
{
    int a = 1, b = 1, i = 0, r;

    for(; ++i < n;)
    {
        r = i % 2 > 0 ? a + b : a - b;
        a = b;
        b = r;
    }

    return b;
};

```

---
Tags: code-golf, number, fibonacci
---


title: Wait... what was I going to say again?

text:
# Question
Title: Wait... what was I going to say again?
I often forget what I wanted to say when the teacher calls on me to speak. Can you make me a tool to solve this?

Requirements:

* The program must loop as follows:
    + First, take in input
    + If the input is empty, print the last stored question.
    + Otherwise, store the input as a question.

Notes:

* The input will never be empty if there are no questions stored.

Clarification: **The program does not need to store multiple questions.** I originally wanted it to store multiple, but I changed it after many people misunderstood the question.

Remember, this is , so the code with the smallest number of bytes wins.

# Answer
# Perl, ~~13~~ ~~17~~ 14 +1 = 15 bytes

```
/./?$;=$_:say$

```

+1 for the `-n` flag (saved 4 bytes thanks to @Dada)

As long as the input is not equal to the carriage return, it stores the input in `$;`. If it is equal to the carriage return, it prints what's already in `$;`.

This assumes that all input can be characterized as questions, even if grammatically, they are not such.
> 10 votes

# Answer
# 05AB1E, ~~12~~ ~~11~~ 10 bytes

Thanks @daHugLenny and @Adnan for 1 byte!
Thanks @Emigna for 1 byte!

```
[IDõQiX,ëU

```
> 8 votes

# Answer
## Haskell, 49 bytes

```
g s=getLine>>=(#s)
""#s=putStr s>>g s
l#s=g l
g""

```

How it works: start with `g ""`. The parameter `s` of function `g` is the question in store. `g` reads the next line from stdin and passes it (and also s) to `#`. If the line is empty, `#` prints the store and calls `g` again. If the line is not empty, `g` is called with the line as the new store.
> 4 votes

# Answer
# JavaScript, ~~36~~ ~~34~~ 31 bytes

```
for(;;b?a=b:alert(a))b=prompt()
```

An infinite loop keeps asking for input and stores it in `b`. It the input is not empty it's then stored in `a`, otherwise the value of `a` is printed.

Saved 2 bytes thanks to @ETHproductions
> 3 votes

# Answer
# Mathematica, 44 bytes

```
If[(b=InputString[])=="",Print@a,a=b]~Do~∞

```

Full program. The Unicode character is U+221E INFINITY for `\[Infinity]`.
> 2 votes

# Answer
## Python 3, 31 bytes

```
while 1: I=input()or I;print(I)

```

Try it out!

-1 byte thanks to Flp.Tkc
> 2 votes

# Answer
# reticular, 12 bytes

```
id""E[$dp]~*

```

Try it online!

## Explanation

```
id""E[$dp]~*
i             take a line of input     [input]
 d""E         push equality with ""    [input, input == ""]
     [$dp]    push that func           [input, input == "", [$p]]
         ~*   execute it iff equal
              on equal:
      $       drop empty input
       dp     duplicate then print the TOS
              this wraps around to the beginning, taking another line of input

```
> 1 votes

# Answer
# Python3 - 49 bytes

```
s=""
while 1:
 b=input()
 if b:s=b
 else:print(s)

```
> 1 votes

# Answer
## Pyke, 6 bytes

```
z=z~zr

```

Try it here!

```
     r - while 1:
z      -   input() or z.contents
 =z    -  z.contents = ^
   ~z  -  z.contents

```
> 1 votes

# Answer
## Python 3, 34 bytes

```
s=""
while[print(s)]:s=input()or s

```
> 1 votes

# Answer
# Python 3, 60 bytes

```
q=[]
while 1:
 s=input()
 if''<s:q+=[s]
 else:print(q.pop())

```
> 1 votes

# Answer
# CMD, 37 bytes

Sadly `set` does not take empty input:(

```
set/p a=
if %a%.=. echo b
set b=%a%
c

```

in a file names `c.cmd` or

```
set/p a=
if %a%.=. echo b
set b=%a%
%0

```

in any file. Working(Use `-` as empty):

```
set/p a=
if %a%.=-. echo b
set b=%a%
c

```
> 0 votes

# Answer
# C, ~~73~~ 63 bytes

```
g(){char a[99],x;for(;;){gets(a);if(*a)x=*a;else*a=x,puts(a);}}

```

Only uses 1 buffer and a single char for handling the logic. If user inputs nothing, only the first char in the buffer gets overwritten by `'\0'`, in that case it gets restored from `x` and printed, otherwise copy the first letter into `x` for later use.

Previous code:

```
main(){char a[99],b[99];for(;;){gets(a);if(*a)strcpy(b,a);else puts(b);}}

```
> 0 votes

# Answer
# APLX, 19 bytes

```
a←⍞⋄→(0=⍴a)/1⋄a⋄→1

```

### Explanation:

```
⍝ Note: the ⋄ symbols are statement separators, so I've replaced them here with newlines

a←⍞           ⍝ get an input string (⍞) and store it in variable a
→(0=⍴a)/1     ⍝ if the length of a (⍴a) is 0, goto (→) the start of this program (1)
a             ⍝ else, print a
→1            ⍝ goto the start of the program (1)

```
> 0 votes

# Answer
# Java 7, ~~189~~ ~~187~~ 178 bytes..

```
class M{public static void main(String[]a){String s="",x;do{x=new java.util.Scanner(System.in).nextLine();if(x.isEmpty())System.out.println(s);else s=x;}while(1>0);}}

```

-9 bytes by using `new java.util.Scanner` directly, thanks to *@cliffroot*.

Probably the first time I used a `do-while` in a codegolf challenge..

When functions are allowed instead of programs, it's **135 bytes** (still many times more than most other answers..)
> 0 votes

# Answer
# sed, 10 bytes

```
/./{x;d};g

```

Explanation:

```
      (implicit at start of program) read input, overwriting old input
/./{  If the input is nonempty
  x;  swap the input with the hold space
  d   then restart, without any implicit printing of input
};    end if statement
g     Append the hold space to the [empty] input
      (implicit at end of program) print the input, then restart

```

Nice to see an exoteric (i.e. "not esoteric") language tying with some of the golfing languages!
> 0 votes

---
Tags: code-golf, string
---


title: Identify the IP address

text:
# Question
Title: Identify the IP address
Identify whether an IP address is internal, global, link-local, or reserved.

Input should be an IPv4 address in decimal octets separated by periods.

Output should be `0` for link-local (RFC 3927), `1` for internal (RFC 1918), `2` for global IPs (Internet), and `3` for otherwise reserved addresses.

All these address types are described in RFC 5735:

> 3. Global and Other Specialized Address Blocks
>
> 0.0.0.0/8 - Addresses in this block refer to source hosts on "this" network. Address 0.0.0.0/32 may be used as a source address for this host on this network; other addresses within 0.0.0.0/8 may be used to refer to specified hosts on this network (\[RFC1122\], Section 3.2.1.3).
>
> 10.0.0.0/8 - This block is set aside for use in private networks. Its intended use is documented in \[RFC1918\]. As described in that
> RFC, addresses within this block do not legitimately appear on the
> public Internet. These addresses can be used without any
> coordination with IANA or an Internet registry.
>
> 127.0.0.0/8 - This block is assigned for use as the Internet host loopback address. A datagram sent by a higher-level protocol to an
> address anywhere within this block loops back inside the host. This
> is ordinarily implemented using only 127.0.0.1/32 for loopback. As
> described in \[RFC1122\], Section 3.2.1.3, addresses within the entire 127.0.0.0/8 block do not legitimately appear on any network anywhere.
>
> 169.254.0.0/16 - This is the "link local" block. As described in \[RFC3927\], it is allocated for communication between hosts on a
> single link. Hosts obtain these addresses by auto-configuration,
> such as when a DHCP server cannot be found.
>
> 172.16.0.0/12 - This block is set aside for use in private networks. Its intended use is documented in \[RFC1918\]. As described in that RFC, addresses within this block do not legitimately appear on the public Internet. These addresses can be used without any coordination with IANA or an Internet registry.
>
> 192.0.0.0/24 - This block is reserved for IETF protocol assignments. At the time of writing this document, there are no current assignments. Allocation policy for future assignments is given in \[RFC5736\].
>
> 192.0.2.0/24 - This block is assigned as "TEST-NET-1" for use in documentation and example code. It is often used in conjunction with domain names example.com or example.net in vendor and protocol
> documentation. As described in \[RFC5737\], addresses within this
> block do not legitimately appear on the public Internet and can be
> used without any coordination with IANA or an Internet registry. See \[RFC1166\].
>
> 192.88.99.0/24 - This block is allocated for use as 6to4 relay anycast addresses, in \[RFC3068\]. In contrast with previously
> described blocks, packets destined to addresses from this block do
> appear in the public Internet. \[RFC3068\], Section 7, describes
> operational practices to prevent the malicious use of this block in
> routing protocols.
>
> 192.168.0.0/16 - This block is set aside for use in private networks. Its intended use is documented in \[RFC1918\]. As described in that RFC, addresses within this block do not legitimately appear on the public Internet. These addresses can be used without any coordination with IANA or an Internet registry.
>
> 198.18.0.0/15 - This block has been allocated for use in benchmark tests of network interconnect devices. \[RFC2544\] explains that this
> range was assigned to minimize the chance of conflict in case a
> testing device were to be accidentally connected to part of the
> Internet. Packets with source addresses from this range are not
> meant to be forwarded across the Internet.
>
> 198.51.100.0/24 - This block is assigned as "TEST-NET-2" for use in documentation and example code. It is often used in conjunction with domain names example.com or example.net in vendor and protocol
> documentation. As described in \[RFC5737\], addresses within this
> block do not legitimately appear on the public Internet and can be
> used without any coordination with IANA or an Internet registry.
>
> 203.0.113.0/24 - This block is assigned as "TEST-NET-3" for use in documentation and example code. It is often used in conjunction with domain names example.com or example.net in vendor and protocol
> documentation. As described in \[RFC5737\], addresses within this
> block do not legitimately appear on the public Internet and can be
> used without any coordination with IANA or an Internet registry.
>
> 224.0.0.0/4 - This block, formerly known as the Class D address space, is allocated for use in IPv4 multicast address assignments.
> The IANA guidelines for assignments from this space are described in
> \[RFC3171\].
>
> 240.0.0.0/4 - This block, formerly known as the Class E address space, is reserved for future use; see \[RFC1112\], Section 4.
>
> The one exception to this is the "limited broadcast" destination
> address 255.255.255.255. As described in \[RFC0919\] and \[RFC0922\],
> packets with this destination address are not forwarded at the IP
> layer.
>
> 4. Summary Table
>
> ```
> Address Block       Present Use                Reference
> 0.0.0.0/8           "This" Network             RFC 1122, Section 3.2.1.3
> 10.0.0.0/8          Private-Use Networks       RFC 1918
> 127.0.0.0/8         Loopback                   RFC 1122, Section 3.2.1.3
> 169.254.0.0/16      Link Local                 RFC 3927
> 172.16.0.0/12       Private-Use Networks       RFC 1918
> 192.0.0.0/24        IETF Protocol Assignments  RFC 5736
> 192.0.2.0/24        TEST-NET-1                 RFC 5737
> 192.88.99.0/24      6to4 Relay Anycast         RFC 3068
> 192.168.0.0/16      Private-Use Networks       RFC 1918
> 198.18.0.0/15       Network Interconnect
>                     Device Benchmark Testing   RFC 2544
> 198.51.100.0/24     TEST-NET-2                 RFC 5737
> 203.0.113.0/24      TEST-NET-3                 RFC 5737
> 224.0.0.0/4         Multicast                  RFC 3171
> 240.0.0.0/4         Reserved for Future Use    RFC 1112, Section 4
> 255.255.255.255/32  Limited Broadcast          RFC 919, Section 7
>                                                RFC 922, Section 7
>
> ```

## Rules

* Standard loopholes apply.
* This is , shortest answer wins.

# Answer
# JavaScript, ~~261~~ 207 bytes

```
v=>["169.254","10.|172.1[6789].|172.2\\d.|172.3[01]|192.168","x","0.|127|192.0.[02].|192.88.99|198.1[89].|198.51.100|203.0.113|2[345]\\d|22[^0123]"].reduce((a,x,i)=>v.search(x.replace(/\./g,"\\."))==0?i:a,2)

```

Readable version

```
v=>[
    "169.254",
    "10.|172.1[6789].|172.2\\d.|172.3[01]|192.168",
    "x",
    "0.|127|192.0.[02].|192.88.99|198.1[89].|198.51.100|203.0.113|2[345]\\d|22[^0123]"]
    .reduce((a,x,i)=>v.search(x.replace(/\./g,"\\."))==0?i:a,2)

```

Create an array with matching patterns, loop through the patterns and compare to input. Return 0,1,2,3 as appropriate.

Edit: Fix bugs and streamline
> 3 votes

# Answer
# ES6 (Javascript), ~~204~~, ~~200~~, ~~182~~, 178 bytes

*EDIT*: Rewritten hex padding code, removed extra parenthesis, -4 bytes

*EDIT*: RegExp cleanup, streamline the result extraction, shorten the hex conversion code

*EDIT*: Refactored result extraction to bring it down to 200 bytes

Note, this should be pretty easy to shorten even further, by compressing the *RegExp* (as I never really bothered to do this)

**Golfed**

```
a=>/(^(?:00|7f|c0(?:5863|0{3}[02])|c6(?:1[23]|3364)|cb0071|e|f))|(^a9fe)|(^0a|^ac1|^c0a8)|./.exec(a.replace(/\d+./g,o=>(o|256).toString(16).slice(1))).reverse().findIndex(a=>a)^1

```

**Explanation**

*IP addresses* are shorter to write and easier to match, when converted to hexadecimal form, as CIDR masks tend to end on the 4 bit boundaries (with an exception of 198.18.0.0/15).

E.g.

```
0A000000-0AFFFFFF //10.0.0.0/8
AC100000-AC1FFFFF //172.16.0.0/12
C0A80000-C0A8FFFF //192.168.0.0/16

```

can be matched as

```
/^0a|^ac1|^c0a8/

```

**Test**

```
I=a=>/(^(?:00|7f|c0(?:5863|0{3}[02])|c6(?:1[23]|3364)|cb0071|e|f))|(^a9fe)|(^0a|^ac1|^c0a8)|./.exec(a.replace(/\d+./g,o=>(o|256).toString(16).slice(1))).reverse().findIndex(a=>a)^1;

T=(i,o)=>{
  block=I(i);
  console.log(i,(block==o)?"OK":"NOT OK");
}

T("0.0.0.0",3)
T("10.0.0.0",1)
T("11.0.0.0",2)
T("127.0.0.0",3)
T("169.254.0.0",0)
T("169.253.0.0",2)
T("172.16.0.0",1)
T("172.31.0.0",1)
T("172.32.0.0",2)
T("192.0.0.0",3)
T("192.0.2.0",3)
T("192.88.99.0",3)
T("192.168.0.0",1)
T("192.167.0.0",2)
T("198.18.0.0",3)
T("198.51.100.0",3)
T("203.0.113.0",3)
T("224.0.0.0",3)
T("239.255.255.255",3)
T("240.0.0.0",3)
T("255.255.255.255",3)
T("241.0.0.1",3)
T("151.101.192.71",2)

```
> 1 votes

# Answer
## Batch, 356 bytes

```
@echo off
set s=%1
if not %s==%s:.=% %0 %s:.= %
if %1.%2==169.254 exit/b0
if %1==10 exit/b1
if %1.%2==172.16 if %3 lss 32 exit/b1
if %1.%2==192.168 exit/b1
if %1==0 exit/b3
if %1==127 exit/b3
if %1 geq 224 exit/b3
for %%a in (18 19)do if %1.%2==192.%a exit/b3
for %%a in (192.0.0 192.0.2 198.51.100 203.0.113)do if %1.%2.%3==%%a exit/b3
exit/b2

```

Takes input as a command-line parameter and returns the result by setting the errorlevel.
> 0 votes

---
Tags: code-golf, string, number, internet
---


title: Solve the Laplace equation

text:
# Question
Title: Solve the Laplace equation
# Introduction to Numerical Mathematics

This is the "Hello, World!" of PDEs (Partial Differential Equations). The Laplace or Diffusion Equation appears often in Physics, for example Heat Equation, Deforming, Fluid Dynamics, etc... As real life is 3D but we want to say "Hello, World!" and not sing "99 bottles of beer,..." this task is given in 1D. You may interpret this as a rubber robe tied to a wall on both ends with some force applied to it.

On a \\$\[0,1\]\\$ domain, find a function \\$u\\$ for given source function \\$f\\$ and boundary values \\$u\_L\\$ and \\$u\_R\\$ such that:

* \\$-u'' = f\\$
* \\$u(0) = u\_L\\$
* \\$u(1) = u\_R\\$

\\$u''\\$ denotes the second derivative of \\$u\\$

This can be solved purely theoretically but your task is it to solve it numerically on a discretized domain \\$x\\$ for \\$N\\$ points:

* \\$x = \\{\frac i {N-1} : 0 \le i \le N-1\\}\\$ or 1-based: \\$\\{\frac {i-1} {N-1} : 0 \le i \le N-1\\}\\$
* \\$h = \frac 1 {N-1}\\$ is the spacing

### Input

* \\$f\\$ as a function, expression or string
* \\$u\_L\\$, \\$u\_R\\$ as floating point values
* \\$N \ge 2\\$ as an integer

### Output

* Array, List, some sort of separated string of \\$u\\$ such that \\$u\_i = u(x\_i)\\$

### Examples

#### Example 1

Input: \\$f = -2\\$, \\$u\_L = u\_R = 0\\$, \\$N = 10\\$ (Don't take \\$f=-2\\$ wrong, it is not a value but a constant function that returns \\$-2\\$ for all \\$x\\$. It is like a constant gravity force on our rope.)

Output: `[-0.0, -0.09876543209876543, -0.1728395061728395, -0.22222222222222224, -0.24691358024691357, -0.24691358024691357, -0.22222222222222224, -0.1728395061728395, -0.09876543209876547, -0.0]`

There exists an easy exact solution: \\$u = -x(1-x)\\$

#### Example 2

Input: \\$f = 10x\\$, \\$u\_L = 0\\$, \\$u\_R = 1\\$, \\$N = 15\\$ (Here there is a lot of upwind on the right side)

Output: `[ 0., 0.1898688, 0.37609329, 0.55502915, 0.72303207, 0.87645773, 1.01166181, 1.125, 1.21282799, 1.27150146, 1.29737609, 1.28680758, 1.2361516, 1.14176385, 1.]`

The exact solution for this states: \\$u = \frac 1 3(8x-5x^3)\\$

**Example 3**

Input: \\$f = \sin(2\pi x)\\$, \\$u\_L = u\_R = 1\\$, \\$N = 20\\$ (Someone broke gravity or there is a sort of up- and downwind)

Output: `[ 1., 1.0083001, 1.01570075, 1.02139999, 1.0247802, 1.0254751, 1.02340937, 1.01880687, 1.01216636, 1.00420743, 0.99579257, 0.98783364, 0.98119313, 0.97659063, 0.9745249, 0.9752198, 0.97860001, 0.98429925, 0.9916999, 1.]`

Here the exact solution is \\$u = \frac {\sin(2πx)} {4π^2}+1\\$

**Example 4**

Input: \\$f = \exp(x^2)\\$, \\$u\_L = u\_R = 0\\$, \\$N=30\\$

Output: `[ 0. 0.02021032 0.03923016 0.05705528 0.07367854 0.0890899 0.10327633 0.11622169 0.12790665 0.13830853 0.14740113 0.15515453 0.16153488 0.1665041 0.17001962 0.172034 0.17249459 0.17134303 0.16851482 0.1639387 0.15753606 0.1492202 0.13889553 0.12645668 0.11178744 0.09475961 0.07523169 0.05304738 0.02803389 0. ]`

*Note the slight asymmetry*

### FDM

One possible method to solve this is the **Finite Difference Method**:

* Rewrite \\$-u\_i'' = f\_i\\$ as \\$\frac {-u\_{i-1} + 2u\_i - u\_{i+1}} {h^2} = f\_i\\$, which equals \\$-u\_{i-1} + 2u\_i - u\_{i+1} = h^2 f\_i\\$
* Setup the equations:

$$ u\_0 = u\_L \\ \frac {-u\_0 + 2u\_1 - u\_2} {h^2} = f\_1 \\ \frac {-u\_1 + 2u\_2 - u\_3} {h^2} = f\_2 \\ \dots = \dots \\ \frac {-u\_{n-3} + 2u\_{n-2} - u\_{n-1}} {h^2} = f\_{n-2} \\ u\_{n-1} = u\_R $$

* Which are equal to a matrix-vector equation:

$$ \begin{pmatrix} 1 & & & & & & \\ -1 & 2 & -1 & & & & \\ & -1 & 2& -1& & & \\ & & \ddots & \ddots & \ddots & & \\ & & & -1 & 2 & -1 & \\ & & & & -1 & 2 & -1 \\ & & & & & & 1 \end{pmatrix} \begin{pmatrix} u\_0 \\ u\_1 \\ u\_2 \\ \vdots \\ u\_{n-3} \\ u\_{n-2} \\ u\_{n-1} \end{pmatrix} = \begin{pmatrix} u\_L \\ h^2 f\_1 \\ h^2 f\_2 \\ \vdots \\ h^2 f\_{n-3} \\ h^2 f\_{n-2} \\ u\_R \end{pmatrix} $$

* Solve this equation and output the \\$u\_i\\$

One implementation of this for demonstration in Python:

```
import matplotlib.pyplot as plt
import numpy as np
def laplace(f, uL, uR, N):
 h = 1./(N-1)
 x = [i*h for i in range(N)]

 A = np.zeros((N,N))
 b = np.zeros((N,))

 A[0,0] = 1
 b[0] = uL

 for i in range(1,N-1):
  A[i,i-1] = -1
  A[i,i]   =  2
  A[i,i+1] = -1
  b[i]     = h**2*f(x[i])

 A[N-1,N-1] = 1
 b[N-1]     = uR

 u = np.linalg.solve(A,b)

 plt.plot(x,u,'*-')
 plt.show()

 return u

print laplace(lambda x:-2, 0, 0, 10)
print laplace(lambda x:10*x, 0, 1, 15)
print laplace(lambda x:np.sin(2*np.pi*x), 1, 1, 20)

```

Alternative implementation without Matrix Algebra (using the Jacobi method)

```
def laplace(f, uL, uR, N):
 h=1./(N-1)
 b=[f(i*h)*h*h for i in range(N)]
 b[0],b[-1]=uL,uR
 u = [0]*N

 def residual():
  return np.sqrt(sum(r*r for r in[b[i] + u[i-1] - 2*u[i] + u[i+1] for i in range(1,N-1)]))

 def jacobi():
  return [uL] + [0.5*(b[i] + u[i-1] + u[i+1]) for i in range(1,N-1)] + [uR]

 while residual() > 1e-6:
  u = jacobi()

 return u

```

**You may however use any other method to solve the Laplace equation.** If you use an iterative method, you should iterate until the residual \\$|b-Au| \< 10^{-6}\\$, with \\$b\\$ being the right hand side vector \\$u\_L,f\_1 h^2,f\_2 h^2, \dots\\$

### Notes

Depending on your solution method you may not solve the examples exactly to the given solutions. At least for \\$N \to \infty\\$ the error should approach zero.

Standard loopholes are disallowed, built-ins for PDEs are allowed.

### Bonus

A bonus of -30% for displaying the solution, either graphical or ASCII-art.

### Winning

This is codegolf, so shortest code in bytes wins!

# Answer
> 4 votes
# Mathematica, 52.5 bytes (= 75 * (1 - 30%))

+0.7 bytes per @flawr 's comment.

```
ListPlot[{#,u@#}&/@Subdivide@#4/.NDSolve[-u''@x==#&&u@0==#2&&u@1==#3,u,x]]&

```

This plots the output.

e.g.

```
ListPlot[ ... ]&[10 x, 0, 1, 15]

```

# Explanation

```
NDSolve[-u''@x==#&&u@0==#2&&u@1==#3,u,x]

```

Solve for the function `u`.

```
Subdivide@#4

```

`Subdivide` the interval \[0,1\] into N (4th input) parts.

```
{#,u@#}&/@ ...

```

Map `u` to the output of `Subdivide`.

```
ListPlot[ ... ]

```

Plot the final result.

# Non-graphing solution: 58 bytes

```
u/@Subdivide@#4/.NDSolve[-u''@x==#&&u@0==#2&&u@1==#3,u,x]&

```

# Answer
> 6 votes
# Matlab, ~~84, 81.2~~ 79.1 bytes = 113 - 30%

```
function u=l(f,N,a,b);A=toeplitz([2,-1,(3:N)*0]);A([1,2,end-[1,0]])=eye(2);u=[a,f((1:N-2)/N)*(N-1)^2,b]/A;plot(u)

```

Note that in this example the I use row vectors, this means that the matrix `A` is transposed. `f` is taken as a function handle, `a,b` are the left/right side Dirichlet contraints.

```
function u=l(f,N,a,b);
A=toeplitz([2,-1,(3:N)*0]);       % use the "toeplitz" builtin to generate the matrix
A([1,2,end-[1,0]])=eye(2);        % adjust first and last column of matrix
u=[a,f((1:N-2)/N)*(N-1)^2,b]/A;   % build right hand side (as row vector) and right mu
plot(u)                           % plot the solution

```

For the example `f = 10*x, u_L = 0 u_R = 1, N = 15` this results in:

# Answer
> 3 votes
## R, 123.2 102.9 98.7 bytes (141-30%)

Edit: Saved a handful of bytes thanks to @Angs!

If someone wants to edit the pictures feel free to do so. This is basically an R adaptation of both the matlab and python versions posted.

```
function(f,a,b,N){n=N-1;x=1:N/n;A=toeplitz(c(2,-1,rep(0,N-2)));A[1,1:2]=1:0;A[N,n:N]=0:1;y=n^-2*sapply(x,f);y[1]=a;y[N]=b;plot(x,solve(A,y))}

```

**Ungolfed & explained:**

```
u=function(f,a,b,N){
    n=N-1;                                              # Alias for N-1
    x=0:n/n;                                            # Generate the x-axis
    A=toeplitz(c(2,-1,rep(0,N-2)));                     # Generate the A-matrix
    A[1,1:2]=1:0;                                       # Replace first row--
    A[N,n:N]=0:1;                                       # Replace last row
    y=n^-2*sapply(x,f)                                  # Generate h^2*f(x)
    y[1]=a;y[N]=b;                                      # Replace first and last elements with uL(a) and uR(b)
    plot(x,solve(A,y))                                  # Solve the matrix system A*x=y for x and plot against x
}

```

**Example & test cases:**

The named and ungolfed function can be called using:

```
u(function(x)-2,0,0,10)
u(function(x)x*10,0,1,15)
u(function(x)sin(2*pi*x),1,1,20)
u(function(x)x^2,0,0,30)

```

Note that the `f` argument is an R-function.

To run the golfed version simply use `(function(...){...})(args)`

##

# Answer
> 2 votes
# Haskell, ~~195~~ 168 bytes

```
import Numeric.LinearAlgebra
p f s e n|m<-[0..]!!n=((n><n)(([1,0]:([3..n]>>[[-1,2,-1]])++[[0,1]])>>=(++(0<$[3..n]))))<\>(col$s:map((/(m-1)^2).f.(/(m-1)))[1..m-2]++[e])

```

The readability took quite a hit. Ungolfed:

```
laplace f start end _N = linearSolveLS _M y
  where
  n = fromIntegral _N
  _M = (_N><_N) --construct n×n matrix from list
        ( ( [1,0]           --make a list of [1,0]
          : ([3.._N]>>[[-1,2,-1]]) --         (n-2)×[-1,2,-1]
          ++ [[0,1]])       --               [0,1]
        >>= (++(0<$[3.._N])) --append (n-2) zeroes and concat
        )                   --(m><n) discards the extra zeroes at the end
  h  = 1/(n-1) :: Double
  y  = asColumn . fromList $ start : map ((*h^2).f.(*h)) [1..n-2] ++ [end]

```

TODO: Printing in ~~83~~ 71 bytes.

Lemme see:

```
import Graphics.Rendering.Chart.Easy
import Graphics.Rendering.Chart.Backend.Cairo

```

D'oh!

# Answer
> 1 votes
# Axiom, ~~579~~ 460 bytes

```
l(w,y)==(r:=0;for i in 1..y|index?(i,w)repeat r:=i;r)
g(z:EQ EXPR INT,y:BasicOperator,a0:Float,a1:Float,a2:Float):Float==(r:=digits();digits(r+30);q:=seriesSolve(z,y,x=0,[a,b])::UTS(EXPR INT,x,0);w:=eval(q,0);s:=l(w,r+30);o:=solve([w.s=a0,eval(q,1).s=a1]::List(EQ POLY Float),[a,b]);v:=eval(eval(eval(q,a2).s,o.1.1),o.1.2);digits(r);v)
m(z:EXPR INT,a0:Float,a1:Float,n:INT):List Float==(n:=n-1;y:=operator 'y;r:=[g(D(y x,x,2)=-z,y,a0,a1,i/n)for i in 0..n];r)

```

ungolf it and test

```
Len(w,y)==(r:=0;for i in 1..y|index?(i,w)repeat r:=i;r)

-- g(z,a0,a1,a2)
-- Numeric solve z as f(y''(x),y'(x),y(x))=g(x) with ini conditions y(0)=a0   y(1)=a1 in x=a2
NSolve2order(z:EQ EXPR INT,y:BasicOperator,a0:Float,a1:Float,a2:Float):Float==
      r:=digits();digits(r+30)
      q:=seriesSolve(z,y,x=0,[a,b])::UTS(EXPR INT,x,0)
      w:=eval(q,0);s:=Len(w,r+30)
      o:=solve([w.s=a0,eval(q,1).s=a1]::List(EQ POLY Float),[a,b])
      v:=eval(eval(eval(q,a2).s,o.1.1),o.1.2);digits(r)
      v

InNpoints(z:EXPR INT,a0:Float,a1:Float,n:INT):List Float==(n:=n-1;y:=operator 'y;r:=[NSolve2order(D(y x,x,2)=-z,y,a0,a1,i/n)for i in 0..n];r)

```

the function for the question is m(,,,) the above code is put in the file "file.input" and load in Axiom. The result depends from the digits() function.

if some one think it is not golfed =\> he or she can show how to do it... thanks

PS

it seems the 6 numbers afther the . for e^(x^2) are not ok here or in the examples but here i increase the digits but numbers not change... for me it means that numbers in example are wrong. Why all other has not showed their numbers?

for sin(2\*%pi\*x) there are problems too

"Here the exact solution is u = (sin(2\*π\*x))/(4\*π^2)+1" i copyed the exact solution for x=1/19:

```
              (sin(2*π/19))/(4*π^2)+1

```

in WolframAlpha https://www.wolframalpha.com/input/?i=(sin(2*%CF%80%2F19))%2F(4*%CF%80%5E2)%2B1 it result

```
1.008224733636964333380661957738992274267070440829381577926...
1.0083001
  1234
1.00822473

```

1.0083001 proposed as result is different in the 4th digit from the real result 1.00822473... (and not 6th)

```
-- in interactive mode
(?) -> )read  file
(10) -> digits(9)
   (10)  10
                                                        Type: PositiveInteger
(11) -> m(-2,0,0,10)
   (11)
   [0.0, - 0.0987654321, - 0.172839506, - 0.222222222, - 0.24691358,
    - 0.24691358, - 0.222222222, - 0.172839506, - 0.098765432, 0.0]
                                                             Type: List Float
(12) -> m(10*x,0,1,15)
   (12)
   [0.0, 0.189868805, 0.376093294, 0.555029155, 0.72303207, 0.876457726,
    1.01166181, 1.125, 1.21282799, 1.27150146, 1.29737609, 1.28680758,
    1.2361516, 1.14176385, 1.0]
                                                             Type: List Float
(13) -> m(sin(2*%pi*x),1,1,20)
   (13)
   [1.0, 1.00822473, 1.01555819, 1.02120567, 1.0245552, 1.02524378, 1.02319681,
    1.0186361, 1.01205589, 1.00416923, 0.99583077, 0.987944112, 0.981363896,
    0.976803191, 0.97475622, 0.975444804, 0.978794326, 0.98444181, 0.991775266,
    1.0]
                                                         Type: List Float
(14) -> m(exp(x^2),0,0,30)
   (14)
   [0.0, 0.0202160702, 0.0392414284, 0.0570718181, 0.0737001105, 0.0891162547,
    0.103307204, 0.116256821, 0.127945761, 0.138351328, 0.147447305,
    0.155203757, 0.161586801, 0.166558343, 0.170075777, 0.172091643,
    0.172553238, 0.171402177, 0.168573899, 0.163997099, 0.157593103,
    0.149275146, 0.13894757, 0.126504908, 0.111830857, 0.0947971117,
    0.0752620441, 0.0530692118, 0.0280456602, - 0.293873588 E -38]
                                                             Type: List Float

```

---
Tags: code-golf, math, calculus
---


title: Why don't you grow up?

text:
# Question
Title: Why don't you grow up?
# Why don't you grow up?

In the past week a meme involving the young actor Aaron Bailey became trending in most Brazilian social networks. Entitled "why don't you grow up" it consists in repeating a sentence replacing its vowels with `i`s (it's a bit more complicated than that, I'll explain below). As I want to be a cool guy I decided to write a program that `mimimifies` a given string.

# Challenge

The challenge consists of `mimimifying` a string, following the rules:

* `ão` and `õe` should be replaced with `im`.
* `ca`, `ka`, `que`, `ke`, `qui`, `ki`, `co` ,`ko`, `cu`, and `ku` should be replaced with `ki`.
* `ça`, `ce`, `çe`, `ci`, `çi`, `ço`, and `çu` should be replaced with `ci`.
* `ga`, `gue`, `gui`, `go`, and `gu` should be replaced with `gui`.
* `ja`, `ge`, `je`, `gi`, `ji`, `jo`, and `ju` should be replaced with `ji`
* You can assume that `qua`, `quo`, `quu`, `gua`, `guo`, and `guu`, will never appear, only `a` and `o` can have tildes and if they do they'll be followed by `o` and `e`, repsectively (`ão`, `õe`).
* The only time `u`s are allowed in output strings is `gui`, besides that case all other vowels present should be `i`s.
* In all other circumstances all vowels must be replaced with `i`s.
* Other than tilde all other accents may be ignored.
* Two or more `i`s in a row are not allowed, you should replace them with only one (`Piauiense` -\> `Pinsi`)

# Examples

**Input**

```
Por que você só fala assim?

```

**Output**

```
pir ki vici si fili issim?

```

**Input**

```
Que horas são?

```

**Output**

```
ki hiris sim?

```

**Input**

```
Óculos sem lente pode ser armação

```

**Output**

```
ikilis sim linti pidi sir irmicim

```

**Input**

```
Ganha o código com menos bytes

```

**Output**

```
guinhi i kidigui kim minis bytis

```

# Rules

* The vowels are `a`, `e`, `i`, `o`, and `u`.
* You can see the full list of possible accents here.
* : the shortest code in bytes wins. Check meta if counting bytes is awkward in your language.
* Standard loopholes are forbidden
* Your output must be consistent in case: all upper/all lower.
* You may assume the input to be in whichever encoding you want but if you do you must specify it.

**Happy golfing!**/**Hippy guilfing!**

# Answer
> 4 votes
# Retina, 150 bytes

```
[ÀÁÂàáâ]
a
[ÉÊéê]
e
Í|í
i
[ÓÔóô]
o
[ÚÜúü]
u
T`L`l
ão|õe
im
[ck][aou]|qu[ei]|ke
ki
ç[aeiou]|ce
ci
g[aou]|gue
gui
j[aeou]|g[ei]
ji
(gu)i|[aeou]
$1i
ii
i

```

Try it online!

This is my first Retina program, so there's probably a lot of improvements to make. Suggestions are welcome.

Thanks to Martin for correcting some mistakes and for some golfing suggestions.

## Explanation

I'm going to break up the explanation into 3 sections, to make it easier on me.

### Section 1: Preprocessing

```
[ÀÁÂàáâ]
a
[ÉÊéê]
e
Í|í
i
[ÓÔóô]
o
[ÚÜúü]
u
T`L`l

```

The first 5 rules replace any accented vowel with the corresponding unaccented version. It's shorter to list out the matches in character classes (or, in the third case, as two options) than to use the culture-invariance and case-insentivity options each time. The last rule converts all ASCII letters to lowercase.

### Section 2: Mimimification

```
ão|õe
im
[ck][aou]|qu[ei]|ke
ki
ç[aeiou]|ce
ci
g[aou]|gue
gui
j[aeou]|g[ei]
ji

```

These rules simply apply the substitutions specified.

### Section 3: Cleanup

```
(gu)i|[aeou]
$1i
i+
i

```

The first rule matches any vowel except for the `u` in `gui`, and replaces them with `i`s. The second rule removes repeated `i`s.

# Answer
> 2 votes
# JavaScript, ~~396~~ ~~392~~ 389 bytes (~~383~~ ~~379~~ 376 characters)

Too many `replace`s, too much regex, ...

```
f=s=>s.toLowerCase().replace(/ão|õe/g,"im").replace(/[àâá]/g,"a").replace(/é|ê/g,"e").replace(/í/g,"i").replace(/ó|ô/g,"o").replace(/ú|ü/g,"u").replace(/(k[aeou])|(c[aou])|que|qui/g,"ki").replace(/(ç[aeiou])|ce/g,"ci").replace(/(g[aou])|gue/g,"gui").replace(/(j[aeou])|ge/g,"ji").split("gui").map(function(a){return a.replace(/[aeou]/g,"i")}).join("gui").replace(/i{2,}/g,"i")

```

I have used this link for a list of Brazilian accented letters so that I know for which letters I have to remove the accent.

### Explanation

```
s.toLowerCase()

```

First, everything is converted to lowercase.

```
.replace(/ão|õe/g,"im")

```

Then I'm am implementing this rule.

```
.replace(/[àâá]/g,"a").replace(/é|ê/g,"e").replace(/í/g,"i").replace(/ó|ô/g,"o").replace(/ú|ü/g,"u")

```

Then the accents are removed using regex.

```
.replace(/(k[aeou])|(c[aou])|que|qui/g,"ki").replace(/(ç[aeiou])|ce/g,"ci").replace(/(g[aou])|gue/g,"gui").replace(/(j[aeou])|ge/g,"ji").split("gui")

```

After that, the the string is being bombarded by regular expressions to "memify" it.

```
.split("gui").map(function(a){return a.replace(/[aeou]/g,"i")}).join("gui")

```

Now all the vowels, except those in `gui` (that is why I used `split`) are being converted to `i`. After that, I rejoin the Array using `gui` as the delimiter.

```
.replace(/i{2,}/g,"i")

```

Finally, I am replacing 2 or more `i`s with just 1 of them.

# Snack Snippet!

```
f=s=>s.toLowerCase().replace(/ão|õe/g,"im").replace(/[àâá]/g,"a").replace(/é|ê/g,"e").replace(/í/g,"i").replace(/ó|ô/g,"o").replace(/ú|ü/g,"u").replace(/(k[aeou])|(c[aou])|que|qui/g,"ki").replace(/(ç[aeiou])|ce/g,"ci").replace(/(g[aou])|gue/g,"gui").replace(/(j[aeou])|ge/g,"ji").split("gui").map(function(a){return a.replace(/[aeou]/g,"i")}).join("gui").replace(/i{2,}/g,"i")

console.log(f("Por que você só fala assim?"))
console.log(f("Que horas são?"))                                                                                //They call me the professional Brazilian-meme-maker
console.log(f("Óculos sem lente pode ser armação"))                                                                                //dank memes, dank memes everywhere
console.log(f("Ganha o código com menos bytes"))
```

Golfing suggestions are welcome

---
Tags: code-golf, string, natural-language
---