title: Let's write a Minifier

text:
# Question
Title: Let's write a Minifier
# Background

Minifiers are used, commonly, when serving JavaScript to your Web Browser. It is commonly used to reduce the number of bytes that have to be sent. Saving bandwidth is useful for obvious reasons. Some people use obfuscaters (that intentionally make code harder to read), I am not talking about those.

# We will be minifying Python 2

I was debating on whether or not use JavaScript or Python for the minifying experience and I decided on Python for two reasons: white space matters and I think that will add an interesting dynamic the problem. Additionally, using Python 2.7 will provide another dynamic, such as remove superfluous `()` during a print (i.e. `print("Hello world")` vs. `print"Hello world"`). I would have, personally, preferred to open it up to any language, but for some languages this process won't make a lot of sense for. And, what language you decide to minify will directly impact your score (and if the language even can be minified).

# Specs

Your goal is to only modify the code in a way that will not change it's functionality in anyway. You may, of course, change variable names (inside your minifying program) as long as it doesn't effect output (keep track of **scope**). Although I am giving you a specific program, please don't optimize for the test case as all standard loopholes are forbidden.

**Score**: length of the program after you minified it.

**Input**: Any Python 2.7 program (that contains no errors)

**Output**: A minified version.

Although your code should be able to accomodate all valid Python 2.7 input, it is necessary to test your script against something in order to prove it's effectiveness.

Click here to view the example program.

# Making the problem more approachable

Feel free to use or modify any code found inside my solution (listed bellow). I did this to get you started with quote basic quote handling; however, you can expand it to indentation, and etc.

# Example ways to minify Python

All white space could be replaced with the minimum possible amount (I acknowledge that in Python you can do some tricky stuff with tabs, but I'll leave that up to you to decide whether or not to implement it).

**Example**

The following:

```
def print_a_range(a):
    for i in range(a):
        print(i)

```

Could be:

```
def print_a_range(a):
 for i in range(a):
  print(i)

```

Technically, if there is only one line inside a loop, you can compress it even more:

```
def print_a_range(a):
 for i in range(a):print(i)  #Note, you can also remove the `()` here.

```

However, there is another way you can minify white space in Python:

The following:

```
print ([a * 2 for a in range(20) if a % 2 == 0])

```

Could be:

```
print([a*2for a in range(20)if a%2==0])

```

Note, that there is no need for a space between `2` and `for`. Variable, functions, and keywords **cannot** start with a number. So, the Python interpreter is okay with `<num><keyword>`, no space. You should also note there does not have to a space between `)` and `if`.

Note, you must not change the output of the program! So:

```
print"f(x)=x*2 is a great equation!"

```

The above print statement should stay the same because removing the space between `2` and `is` would modify the output.

# Answer
> 4 votes
# Python 2.7, 2013 score

**This program can be used as reference, and you are allowed to take the following code and modify it and then post it in your own solutions.**

In hindsight, I maybe should have used regex for the quote handling too, but I think in its current state it may be enough to jump-start people into the problem.

Why I chose Python 2.7: I thought it would be easier to test to see if I made the program crash via the `exec` keyword.

This code intakes the program as `in.txt`.

I figured I should at least get the ball rolling for whoever want to participate by writing a quote parser (that also happens to handle comments) and a brief example on how regex, when combined with the quote parser can really change the game in terms of complexity of this problem.

**Note:** there is still plenty of room for improvement in this minifier. Like you could play around with indentation, variable names, and removing the parenthesis when they're being used my keywords, like `print` or `yield`.

```
import re

with open("in.txt","r") as fi:
    code = fi.read()

class QuoteHandler():
    def __init__(self):
        pass
    def loadCode(self,code):
        quoteFlag = False
        currentQuoteChar = ""
        ignoreNext = False
        inEndLineComment=False
        startLocation = 0

        self.reAddStrings = []

        outStr = ""

        for i, character in enumerate(code):
            if ignoreNext:
                ignoreNext = False
            elif inEndLineComment:
                if character in "\r\n":
                    inEndLineComment=False
            elif character == "#" and not quoteFlag:
                inEndLineComment = True
            elif character in "'\"" and (currentQuoteChar == character or not quoteFlag):
                if quoteFlag:
                    self.reAddStrings.append(code[startLocation+1:i])
                else:
                    currentQuoteChar = character
                    startLocation = i
                quoteFlag = not quoteFlag
            elif character == "\\":
                ignoreNext = True

            if not inEndLineComment and not quoteFlag:
                outStr+=character
        return outStr

    def find_all_locations(self,substr,code):
        return [m.start() for m in re.finditer(substr, code)]

    def unloadCode(self,code):
        temp = self.reAddStrings[::-1]
        for i, location in enumerate(list(self.find_all_locations('"',code))[::-1]):
            code = code[:location] + "\"" + temp[i] + code[location:]
        return code

def applyRegexes(code):#\w here?
    operatorRegexCleaner = ["([\d\/*\-\"=,'+{}:[\](\)])","[ \t]+","(\w)"]
    regexes = [
        [''.join(operatorRegexCleaner),r"\1\2"],
        [''.join(operatorRegexCleaner[::-1]),r"\1\2"],#removes whitespace between operators
        ["\n\s*\n","\n"]#removes empty lines
    ]
    for regex in regexes:
        code = re.sub(regex[0],regex[1],code)
    return code

qh = QuoteHandler()
code = qh.loadCode(code)
code = applyRegexes(code)
code = qh.unloadCode(code)
print(code)
exec(code)

```

Output of program:

```
def factor(factor_number):
    for n in range(2,factor_number):
        if factor_number % n==0:
            yield(n)
def gcd(a,b):
    """Calculate the Greatest Common Divisor of a and b.

    Unless b==0, the result will have the same sign as b (so that when
    b is divided by it, the result comes out positive).
    """
    while b:
         a,b=b,a%b
    return a
class Apricot:
    def __init__(self):
        self.mold=False
    def get(self):
        return self.mold
    def update(self):
        self.mold=not self.mold
    def blue(self):return5
def tell_me_about_these_numbers(*a):
    print("%d is the first number!" % a[0])
    print("{} / 3 is {}".format(a[0],a[0]/3.))
    myFavorate=Apricot()
    for number in a:
        print list(factor(number))
        myFavorate.update()
    print[gcd(a,b)for a,b in zip(a[:-1],a[1:])]
    print(myFavorate.get())
tell_me_about_these_numbers(5,6,9,45,200)
print"Let's play with scope!"
a,b=10,9
def randomFunction(a):
    print(a)
randomFunction(b)
print(a)
for a in range(100):
    b+=a
print(a)
print(b)
li=[]
for i in range(10):
 li.append(i*2)
print(li)
print([i*2for i in range(10)])
a=c=b=d=e=f=g=h=i=j=k=l=m=n=o=p=q=r=s=t=u=v=w=x=y=z=5
print(a)
a-=1
print(a)
g=10
print(str(10**g+5)[::-1])
def blue_fish(a):
    def blue_fish(a):
        def blue_fish(a):
            return a
        a+=1
        return blue_fish(a)
    a-=1
    return blue_fish(a)
print(blue_fish(10))
def blue_fish(a):
    if a==0:
        return"0"
    return"1" +blue_fish(a-1)
print(blue_fish(5))
blue_fish=lambda a,b,c:a*b*c
print(blue_fish(1,2,3))
blue_fish=lambda*a:reduce(lambda a,b:a*b,a)
print(blue_fish(1,2,3))
print(max([[6,1],[5,2],[4,3],[3,4],[2,5],[1,6]],key=lambda a:a[1]))
print(zip(*[[1],[2],[3],[4],[5]]))
print"Now let's test to see if you handle quotes correctly:"
print"test \'many diffent\' \"types of \" quotes, even with \' \" trailing quotes"
print"""

Multi line quotes are great too!

"""
a=""" ::
one more multi-line quote won't hurt
"""
print a

```

---
Tags: python, test-battery
---


title: Decomposing into primes

text:
# Question
Title: Decomposing into primes
Given an integer `n`, return the number of ways that n can be written as a list of prime numbers. For example, `2323` can be written as `(2,3,23)`, `(23,23)` or `(2,3,2,3)` or `(23,2,3)`, so you would output `4`. If it can not be written in this way, you should output `0`.

A prime number such as `019` or `00000037` is a valid prime for this problem.

Test cases:

```
5 -> 1
55 -> 1
3593 -> 4 (359 and 3, or 3 and 593, or 3 and 59 and 3, or 3593)
3079 -> 2 (3 and 079, or 3079)
119 -> 0
5730000037 -> 7 (5,7,3,000003,7, 5,7,3,0000037, 5,73,000003,7, 5,73,0000037, 5,73000003,7, 5,7,30000037, 5730000037)
0-> undefined (you do not have to handle this case)

```

This is , so the shortest answer in bytes in each language wins!

Edit: now I know why I should use the sandbox next time

# Answer
> 7 votes
# Haskell, ~~96~~ 89 bytes

*5 bytes saved thanks to H.PWiz's primality test*

```
p x=[1|0<-mod x<$>[2..x]]==[1]
f[]=1
f b=sum[f$drop i b|i<-[1..length b],p$read$take i b]

```

Try it online!

## Explanation

The first thing that's done is creating a prime test function ~~using Wilson's theorem~~ using the definition of prime.

```
p x=[1|0<-mod x<$>[2..x]]==[1]

```

Then begin defining `f`. The first thing I thought when I saw this problem was to use dynamic programming. However dynamic programming costs bytes so this uses a "psuedo-dynamic programming" algorithm. Whereas in dynamic programming you would store a Directed Acyclic graph in memory here we just use recursion and recalculate each node every time we need it. It loses all of the time benefits of dynamic programming, but this is so who cares. (still better than brute force search though)

The algorithm is as follows, we construct a Directed Acyclic Graph, **L**, where each node represents a substring of the number. In particular **Li** represents the last **i** digits of our input (lets call it **n**).

We define **L0** to have a value of 1 and each other value in **L** to have the sum of each **Lj** such that **j \< i** and the substring of **n** from **i** to **j** is prime.

Or in a formula:

We then return the value at the largest largest index of **L**. (**Lk** where **k** is the number of digits of **n**)

# Answer
> 6 votes
# Jelly, 8 bytes

```
ŒṖḌÆPẠ€S

```

Try it online!

-1 byte thanks to Leaky Nun
-1 byte thanks to Dennis

# Explanation

```
ŒṖḌÆPẠ€S  Main Link
ŒṖ        List Partitions (automatically converts number to decimal digits)
  Ḍ       Convert back to integers (auto-vectorization)
   ÆP     Are they primes? (auto-vectorization)
     Ạ€   For each, are they all truthy (were the numbers all primes?); 1/0 for truthy/falsy
       S  Sum; gets number of truthy elements

```

# Answer
> 6 votes
# Brachylog, 10 bytes

```
ṫ{~cịᵐṗᵐ}ᶜ

```

Try it online!

First  converts the input into a string. `{…}ᶜ` Counts the number of possible outputs for .

Inside `{…}` the output of  is fed to `~c`. The output of this predicate satisfies that, when concatenated, it is equal to the input. This is fed into `ịᵐ`, which specifies that its output is it's input with each string converted into an integer. `ṗᵐ` specifies that its input consists of primes

# Answer
> 4 votes
# Pyth, 13 bytes

```
lf.AmP_sdT./`

```

Test suite.

# Answer
> 3 votes
# Python 2, ~~105~~ ~~95~~ 91 bytes

```
f=lambda n:sum(0**k|f(n%10**k)for k in range(n)if sum(n/10**k%j<1for j in range(1,n+2))==2)

```

This is *very* slow.

Try it online!

# Answer
> 2 votes
# Python 2, 161 bytes

```
lambda n:sum(all(d>1and all(d%i>0for i in range(2,d))for d in v)for v in g(`n`))
g=lambda s:[[int(s[:i])]+t for i in range(1,len(s))for t in g(s[i:])]+[[int(s)]]

```

Try it online!

The function `g` creates the partitions recursively (it takes a string as input but outputs a list of lists of ints). Most of the remaining code is just to implement 'is `d` a prime?'.

# Answer
> 2 votes
# Gaia, 12 bytes

```
₸B¦ṗ¦Π
$ḍ↑¦Σ

```

Try it online!

# Answer
> 1 votes
# Clean, ~~199~~ ~~141~~ 131 bytes

```
import StdEnv
?n|n<2=0|and[gcd n i<2\\i<-[2..n-1]]=1=0
@n#s=toString n
#f=toInt o(%)s
= ?n+sum[@(f(0,i))\\i<-[0..n]| ?(f(i+1,n))>0]

```

Try it online!

# Answer
> 1 votes
# , 65 64 bytes

```
(1#.[:*/"1*/@>)@(#`(1,.[:#:[:i.2^#-1:)@.(1<#)(1:p:&.>".);.1])@":

```

Try it online!

# Answer
> 0 votes
# Pyth, 12 bytes

```
lf*FmP_sdT./

```

Takes input as an integer, outputs `True` or `False`

Try it online!

---
Tags: code-golf, math, primes, set-partitions
---


# Question
Title: The struggling college student's GPA Calculator
# GPA Calculator

(GPA = Grade Point Average)

You are a stressed out college student during finals week. Instead of studying for your exams coming up, you decide it is best to determine what GPA you will have at the end of the semester. This way you have data to back up your decision of staying up all night to get that A in Calculus instead of a B to remain on the Dean's list!

Being a computer science major you want to find the coolest way to determine this GPA. Of course the coolest way is with the **shortest code!** This is , so shortest code in bytes wins!

# Details

* The college that you go to uses a basic GPA scaled along with credit hours.
* A letter grade of A is a 4.0, B is 3.0, C is 2.0, D is 1.0, and F is 0.0
* Your GPA is a weighted GPA, so an A in a 4 credit hour class counts 4 times as much as an A in a 1 credit hour class (See examples below for more weight explanantion)
* Credit Hours range from 1-4
* Your program will need to have a list of two command line inputs, Grade and Credit Hour. You can determine the best way to input these into your program through the command line. You do not need to worry about too many inputs, but ensure your code can handle a 19 credit hour semester.

+ i.e. Input: A 1 B 4 C 2…
* Your program must output the GPA, using 3 digits (i.e. X.XX)
* Your GPA needs to be rounded to two decimal places. Round in whichever way you like (floor, ceil, base, etc…)

## Input Examples(Choose whichever one works best for your design)

* A1B3C2F3B4
* A1 B3 C2 F3 B4
* A 1 B 3 C 2 F 3 B 4
* A,1,B,3,C,2,F,3,B,4
* A1,B3,C2,F3,B4

Or any of the above combinations where you use the format of listing all grades, then their credit hours:

* i.e. A B A A 3 4 1 1

## Examples

```
Input - A 3 B 4 A 1 A 1
Output - 3.56
Explanation: (4.0 * 3 + 3.0 * 4 + 4.0 * 1 + 4.0 * 1)/(3+4+1+1) = 3.555556 rounded off to 3.56

Input - A 4 F 2 C 3 D 4
Output - 2.00
Explanation: (4.0 * 4 + 0.0 * 2 + 2.0 * 3 + 1.0 * 4)/(4+2+3+4) = 2 rounded off to 2.00

```

# Answer
> 5 votes
# Jelly,  ~~15~~  21 bytes (12 with no rounding)

+6 bytes for the strict formatting (almost certainly possible in less but it's bed time)

```
Oạ69.Ḟ×S×ȷ2÷⁹S¤RLDż”.

```

A full program taking the grades and the respective credit hours which prints the calculated GPA (Note: the rounding method is to floor, as allowed in the OP).

**Try it online!**

With no rounding for **12 bytes**:

```
Oạ69.Ḟ×S÷⁹S¤

```

### How?

```
Oạ69.Ḟ×S×ȷ2÷⁹S¤RLDż”. - Link: list of characters, grades; list of number, creditHours
                      -                                   e.g. "AFBDC", [5, 2, 4, 1, 2]
O                     - cast to ordinals (vectorises)          [65,70,66,68,67]
  69.                 - literal 69.5
 ạ                    - absolute difference (vectorises)       [4.5,0.5,3.5,1.5,2.5]
     Ḟ                - floor (vectorises)                     [4,0,3,1,2]
      ×               - multiply by creditHours (vectorises)   [20,0,12,1,4]
       S              - sum                                    37
         ȷ2           - literal 100
        ×             - multiply                               3700
              ¤       - nilad followed by link(s) as a nilad:
            ⁹         -   chain's right argument, creditHours  [5, 2, 4, 1, 2]
             S        -   sum                                  14
           ÷          - division                               264.2857142857143
               R      - range                                  [1,2,3,...,264]
                L     - length                                 264
                 D    - digits                                 [2,6,4]
                   ”. - literal '.'
                  ż   - zip together                           [[2,'.'],6,4]
                      - implicit print (smashing)              2.64

```

# Answer
> 4 votes
# Python 3, 66 bytes

*-5 bytes thanks to Rod.*

```
lambda g,c:'%.2f'%sum('FDCBA'.find(i)*j/sum(c)for i,j in zip(g,c))

```

Try it online!

# Answer
> 4 votes
# Perl 5, ~~57~~ 53 + 2 (`-an`) = ~~59~~ 55 bytes

```
$c+=$F[1];$\+=$F[1]*=!/F/&&69-ord}{printf'%.2f',$\/$c

```

Try it online!

*Edit: swapped the input around to save 4 bytes*

Input format: line separated, credits followed by grade:

```
grade credits

```

Example:

```
A 3
B 4
A 1
A 1

```

# Answer
> 3 votes
# Python 2, 69 bytes

```
lambda x:'%.2f'%sum('FDCBA'.find(a)*b*1./sum(zip(*x)[1])for a,b in x)

```

Try it online!

# Answer
> 3 votes
# Wolfram Language (Mathematica), 39 bytes

```
N[(5-LetterNumber@#2/.-1->0).#/Tr@#,3]&

```

Takes a list of credit hours, and then a string of grades.

Does not work on TIO because TIO uses Mathematica kernel (which doesn't want to print arbitrary precision numbers)

# Answer
> 2 votes
# JavaScript (ES6), 72 bytes

Input format: `A1B3C2F3B4`

```
f=([c,d,...s],a=b=0)=>c?f(s,a+~'DCBA'.search(c,b-=d)*d):(a/b).toFixed(2)

```

### Test cases

```
f=([c,d,...s],a=b=0)=>c?f(s,a+~'DCBA'.search(c,b-=d)*d):(a/b).toFixed(2)

console.log(f('A3B4A1A1')) // 3.56
console.log(f('A4F2C3D4')) // 2.00
```

# Answer
> 2 votes
# , 64 bytes

```
function(G,H)sprintf("%.2f",(5-match(G,LETTERS[-5]))%*%H/sum(H))

```

Try it online!

*thanks to user2390246 for fixing a bug!*

# Answer
> 2 votes
# Java 1.8, ~~287~~ 249 Bytes

-38 bytes thanks to Bumptious

# Golfed

```
static String N(String[]j){float g=0;float b=0;for(int i=0;i<j.length;i+=2){g=((m(j[i])*Float.parseFloat(j[i+1])+g));b+=Double.parseDouble(j[i+1]);}return String.format("%.2f",g/b);}static float m(String l){return l.equals("F")?0:('E'-l.charAt(0));}

```

## Ungolfed

```
interface C {
static void main(String[] z) throws Exception {
    String[] j = {"A", "4", "B", "3", "C", "2", "D", "1", "F", "1"};
    System.out.println(N(j));
}

static String N(String[] j) {
    float g = 0;
    float b = 0;
    for (int i = 0; i < j.length; i += 2) {
        g = ((m(j[i]) * Float.parseFloat(j[i + 1]) + g));
        b += Double.parseDouble(j[i + 1]);
    }
    return String.format("%.2f", g / b);
}

static float m(String l) {
    return l.equals("F") ? 0 : ('E' - l.charAt(0));
}
}

```

# Answer
> 2 votes
# Java, 211 bytes

Input format: A1B3C2F3B4

## Golfed

```
interface A{static void main(String[] a){int p=0,t=0,h=0,s=0;for(int c:a[0].toCharArray())if(p++%2==0)t=c=='A'?4:c=='B'?3:c=='C'?2:c=='D'?1:0;else{s+=(c-=48)*t;h+=c;}System.out.print(Math.ceil(100d*s/h)/100);}}

```

## Unglofed

```
static void main(String[] a) {
    int p=0, //position in string
    t=0, //temp var, used to store the grade between iterations
    h=0, //credit sum
    s=0; //sum of weighted grade

    for(int c:a[0].toCharArray())
        if(p++%2==0)
            //map c to grade value, assign to temp variable t
            t=c=='A'?4:c=='B'?3:c=='C'?2:c=='D'?1:0;
        else{
            //map c to credit value, add temp variable (grade from previous char) * value of this char (credit) to sum
            s+=(c-=48)*t;
            //also, add credit to credit sum
            h+=c;
        }
    System.out.print(Math.ceil(100d*s/h)/100); //grade sum / credit hours sum, to 2dp*/
}

```

### Other version

My gut frealing told me that using a different input format (ABCF1324) would make the code shorter. It seems like it didn't. The version below is 234 bytes long.

### Golfed

```
interface A{static void main(String[] b){char[] a=b[0].toCharArray();int l=a.length/2,h=0,s=0,g,c,i;for(i=0;i<l;i++){g=a[i];g=g=='A'?4:g=='B'?3:g=='C'?2:g=='D'?1:0;c=a[i+l]-48;s+=g*c;h+=c;}System.out.print(Math.ceil(100d*s/h)/100);}}a

```

### Ungolfed

```
static void main(String[] b) {
    char[] a=b[0].toCharArray(); //char array
    int l=a.length/2, //first grade char
    h=0, //credit sum
    s=0, //sum of weighted grade
    g,c, //avoid declaration in for loop. grade and credit being iterated
    i; //avoid declaration in for loop
    for(i=0;i<l;i++) {
        g=a[i];//get char representing grade from array
        g=g=='A'?4:g=='B'?3:g=='C'?2:g=='D'?1:0; //convert to grade
        c=a[i+l]-48;//get char representing grade from array and convert to credit (48 is value of '0')
        s+=g*c; //add weighted grade to sum
        h+=c; //add credit to sum
    }
    System.out.print(Math.ceil(100d*s/h)/100); //grade sum / credit hours sum, to 2dp*/
}

```

# Answer
> 1 votes
# Julia 0.6, 46 43 42 bytes

```
g%h=round(max.(69-Int.(g),0)⋅h/sum(h),2)

```

Try it online!

**Explanation**

Input format: `g`: vector of grades; `h`: vector of credit hours

* `g%h`: Redefine `%` operator.
* `69-Int.(g)`: Convert `'F','D','C','B','A'` to `-1,1,2,3,4` respectively for each element of g.
* `max.( ,0)`: Clamp range to `0:4` (element-wise).
* The rest is simple vector math.
* Rounding costs 9 bytes.

---
Tags: code-golf
---


title: FOIL Python's strong typing!

text:
# Question
Title: FOIL Python's strong typing!
Your task is to write some code in Python 2 or 3 such that this expression:

```
(a+b)(c+d) == a*c + b*c + a*d + b*d

```

will evaluate to `True` without raising any exceptions.

To clarify, I will copy your code into a file, then `from` the file `import *`. Then I will type the expression into the console and verify that it is `True`.

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

# Answer
> 21 votes
## ~~54~~ ~~52~~ ~~50~~ ~~49~~ ~~48~~ ~~45~~ 39 bytes

Removed 4 bytes thanks to Dennis.

The latest version is inspired by the "some reason" in xnor's answer.

```
class t(int):__add__=type
a=b=t()
c=d=0

```

# Answer
> 10 votes
## 54 bytes

```
class m(int):__call__=__add__=lambda*x:m()
a=b=c=d=m()

```

Make an object that inherits from `int`, except adding or calling just returns a copy of itself.

Same length:

```
class m(int):__call__=__add__=lambda a,b:a
a=b=c=d=m()

```

I thought `min` or `{}.get` would work in place of `lambda a,b:a`, but for some reason they act only on the second argument.

# Answer
> 3 votes
# ~~81~~ 66 bytes

```
class e:__mul__=lambda*o:0;__add__=lambda*o:lambda x:0
a=b=c=d=e()

```

# Answer
> 2 votes
### 68 bytes

While it cannot really compete with the existing answers, this one actually performs the calculation in question:

```
from sympy.abc import*
type(a+b).__call__=lambda x,y:(x*y).expand()

```

Explanation:

* SymPy is a module for symbolic computations.
* `sympy.abc` contains all single-letter symbols, in particular ones named `a`, `b`, `c`, and `d`.
* `a+b` is an `Add` object, which represents a general sum.
* `type(a+b).__call__= […]` monkey-patches the `Add` class to give it evaluation capabilities, in this case enabling it to work like a multiplication of caller and callee.
* `expand` is necessary to make the expressions actually equal (since SymPy only performs thorough equality checks on demand).

---
Tags: code-golf, python
---


title: You've got a book to make!

text:
# Question
Title: You've got a book to make!
You work at a virtual, old-fashioned printing press. To help you arrange your monospace letters faster, you decide to make the shortest program possible to help you. Given a string of text and a page size, generate and output each page of the text.

## Examples

For example, with a page width of 14, height 7, and some text, here is your book:

```
14, 7, "Fruits make an extremely good snack due to their utterly scrumptious sweetness. They are also very healthy for you."
+------------+
| Fruits     |
| make an    |
| extremely  |
| good snack |
| due to     |
+------------+

+------------+
| their      |
| utterly    |
| scrumptio- |
| -us        |
| sweetness. |
+------------+

+------------+
| They are   |
| also very  |
| healthy    |
| for you.   |
|            |
+------------+

```

Here's the basic page setup:

```
|---i.e.14---|
+------------+ -
| Xxxxxxxxxx | |
| Xxxxxxxxxx | i.
| Xxxxxxxxxx | e.
| Xxxxxxxxxx | 7
| Xxxxxxxxxx | |
+------------+ -

```

## A few things

1. There is a one-space margin between the page edges and the text.
2. The width and height include the box edges, if that wasn't clear.
3. Wraparound only occurs if a word can't fit on a single line.
4. The program needs to be able to output as many pages as needed, and only that many.
5. Your program has to support any page size, not just 14 by 7.
6. This is code golf, so the smallest solution in bytes (any language) wins.
7. Don't ruin the fun. Standard loopholes are obviously not allowed.

## Oh, and, by the way:

```
+------------+
| May the    |
| best book  |
| publisher  |
| win. Good  |
| Luck!      |
+------------+

+------------+
| Best       |
| program    |
| so far:    |
| Charcoal   |
|            |
+------------+

```

# Answer
> 5 votes
# Python 2, ~~306~~ ~~304~~ ~~283~~ 279 bytes

```
def f(w,h,s):
 b=[];w-=4;h-=2;H='+-'+'-'*w+'-+';x=l='';s=s.split()
 while s:
	W=s.pop(0)
	if W[w:]:W,s=W[:w-1]+'-',['-'+W[w-1:]]+s
	if len(l+W)<=w-(l>x):l+=' '*(l>x)+W
	else:b+=[l];l=W
 b+=[l]+[x]*h
 while any(b):print'\n'.join([H]+['| %-*s |'%(w,b.pop(0))for _ in' '*h]+[H,x,x])

```

Try it online!

# Answer
> 3 votes
# Charcoal, ~~105~~ 83 bytes

```
ＮθＮηＭ⁺η²↑Ｆ⪪Ｓ «Ｗ›Ｌι⁻θ⁴«⊞υ⁺…ι⁻θ⁵-≔⁺-✂ι⁻θ⁵Ｌι¹ι»⊞υι»Ｆυ«¿‹Ｌι±ⅈ «Ｍ⁻⁻⁴ⅈθ¹¿¬﹪ⅉ⊕η«↙↙Ｂθη↘→»»ι

```

Try it online! Link is to verbose version of code ~~the deverbosifier can't handle the  and  nilary operators~~. If leading blank lines were acceptable, I could get it down to 76 bytes:

```
≔⁻Ｎ⁴θＭθ→ＮηＦ⪪Ｓ «Ｗ›Ｌιθ«⊞υ⁺…ι⊖θ-≔⁺-✂ι⊖θＬι¹ι»⊞υι»Ｆυ«¿‹⁺ⅈＬιθ «Ｆ¬﹪ⅉ⊕η«⸿↙↙Ｂ⁺θ⁴η»⸿»ι

```

Explanation:

```
ＮθＮη

```

Input the width into `q` and the height into `h`.

```
Ｍ⁺η²↑

```

Move to a position that will trigger the first box to be drawn, but without generating a top margin.

```
Ｆ⪪Ｓ «

```

Loop over all the words in the input string.

```
Ｗ›Ｌι⁻θ⁴«

```

Repeat while a word is too wide to fit into a box.

```
⊞υ⁺…ι⁻θ⁵-

```

Push as much of the word that will fit plus a trailing hyphen.

```
≔⁺-✂ι⁻θ⁵Ｌι¹ι»

```

Prefix a hyphen to the rest of the word.

```
⊞υι»

```

Push the rest of the word.

```
Ｆυ«

```

Loop over all the hyphenated words.

```
¿‹Ｌι±ⅈ

```

Check whether the word fits on the current line.

```
 «

```

If so then print a space.

```
Ｍ⁻⁻⁴ⅈθ¹

```

Otherwise move to the start of the next line.

```
¿¬﹪ⅉ⊕η

```

Check whether we need a new box.

```
«↙↙Ｂθη↘→»»

```

If so then draw the box.

```
ι

```

Finally, print the word.

# Answer
> 2 votes
# JavaScript (ES8), 242 bytes

*Thanks to @Tvde1 for reporting a bug*

```
(s,w,h)=>s.split` `.map(g=s=>l=(l+s)[W=w-5]?s[l&&A(l),l='',w-4]?g('-'+s.slice(W),A(s.slice(0,W)+'-')):s:l?l+' '+s:s,n=o=l='',h-=2,b=`+${'-'.repeat(w-2)}+
`,A=s=>o+=(!n|n++%h?'':b+`
`+b)+`| ${s.padEnd(w-3)}|
`)&&(g=s=>A(s)&&n%h?g(''):b+o+b)(l)

```

Try it online!

### Commented

```
(s, w, h) =>                        // given s = string, w = width, h = height
  s.split` `                        // get all words by splitting the string on spaces
  .map(g = s =>                     // for each word s:
    l = (l + s)[W = w - 5] ?        //   if the word is too long for the current line:
      s[ l && A(l),                 //     append the line (if not empty)
         l = '',                    //     clear the line
         w - 4 ] ?                  //     if the word itself doesn't fit:
        g(                          //       do a recursive call with:
          '-' + s.slice(W),         //         a hyphen + the next part
          A(s.slice(0, W) + '-')    //         and append the current part + a hyphen
        )                           //       end of recursive call
      :                             //     else:
        s                           //       initialize a new line with this word
    :                               //   else:
      l ?                           //     if the current line is not empty:
        l + ' ' + s                 //       append a space + the word
      :                             //     else:
        s,                          //       initialize a new line with this word
    n = o = l = '',                 //   n = line counter, o = output, l = line
    h -= 2,                         //   adjust h
    b = `+${'-'.repeat(w - 2)}+\n`, //   b = border + linefeed
    A = s =>                        //   A = function that updates the output o:
      o += (                        //     append to o:
        !n | n++ % h ?              //       if we haven't reached an end of page:
          ''                        //         an empty string
        :                           //       else:
          b + `\n` + b              //         bottom border + linefeed + top border
      ) +                           //       followed by
      `| ${s.padEnd(w - 3)}|\n`     //       left border + padded text + right border
  ) &&                              // end of map()
  (g = s =>                         // g = recursive function taking s:
    A(s) &&                         //   append s
    n % h ?                         //   if we haven't reached an end of page:
      g('')                         //     go on with an empty line
    :                               //   else:
      b + o + b                     //     return top border + output + bottom border
  )(l)                              // initial call to g() with the last pending line

```

# Answer
> 2 votes
# Perl 5, ~~203~~ 182 + 1 (`-a`) = 183 bytes

```
$t=($\=-3+shift@F)-2;$h=shift@F}{say$_='+'.'-'x$\.'-+';map{$_="";{$_.=shift@F;s/.{$t}\K..+/-/&&unshift@F,-$&;$_.=$";y///c+length$F[0]<$\&&redo}printf"| %-$\s|
",$_}3..$h;say;@F&&redo

```

Try it online!

# Answer
> 2 votes
# SOGL V0.12, 92 bytes

```
Aē:b⁾\&?Q¶oQ}cI@*¼|a31žO■
.⁾:0EHC┌*¼+Q,θK;{⁴D@Κ+lc<‽Xd■Flc<‽ø;c⁾{Kh+;}D┌+■d┌Κ}}}■beb⁾%-⁾{ø■}

```

Try it Here!

# Answer
> 1 votes
# Jelly, 93 bytes

```
1,⁴Ṭị⁾+-W,`
ṣ⁶µḊṖs⁴_6¤j⁾--;@Ḣ;Ṫḟ0s⁴_©4¤µ€ẎŒṖK€€µL€>®ẸµÐḟṪ;€⁶x®¤ḣ€®s⁵_2¤Zz⁶x®¤j@€€⁾| ,U¤j@€¢ẎY

```

A full program taking three arguments (`text`, `width`, `height`) which prints the pages.

**Try it online!** N.B. Too inefficient to run the example from the OP within the 60 second limit.

(97 bytes if the blank line between pages is actually a requirement)

### How?

```
1,⁴Ṭị⁾+-W,` - Link 1, make header & footer: no arguments
  ⁴         - program's 2nd argument, width
1           - literal one
 ,          - pair = [1,width]
   Ṭ        - untruth = [1,0,0,...,0,0,1] (a 1 at index 1 and index width; 0 elsewhere)
     ⁾+-    - literal list of characters = "+-"
    ị       - index into (1-based & modular) = "+--...--+"
        W   - wrap = ["+---...--+']
          ` - use as both arguments of the dyad:
         ,  - pair = [["+---...--+'],["+---...--+']]

ṣ⁶µḊṖs⁴_6¤j⁾--;@Ḣ;Ṫḟ0s⁴_©4¤µ€ẎŒṖK€€µL€>®ẸµÐḟṪ;€⁶x®¤ḣ€®s⁵_2¤Zz⁶x®¤j@€€⁾| ,U¤j@€¢ẎY

 - Main link. This is long so splitting it up into parts like so:
ṣ⁶µ "A" µ€ "B" µ "C" µÐḟ "D"
ṣ⁶                           - split 1st argument (text) at spaces
  µ "A" µ€                   - for €ach resulting word do "A" (get hyphenated parts)
           "B"               - do "B" (all ways to partition those joining with spaces)
                     µÐḟ     - filter discard if:
               µ "C"         -   do "C" (any parts are too long)
                         "D" - do "D" (format the resulting list into the page-format)

"A" = ḊṖs⁴_6¤j⁾--;@Ḣ;Ṫḟ0s⁴_©4¤ - Hyphenate: list, word     e.g. "Something"
      Ḋ                        - dequeue                        "omething"
       Ṗ                       - pop                            "omethin"
            ¤                  - nilad followed by link(s) as a nilad
         ⁴                     -   program's 2nd argument  e.g. 9  (width)
           6                   -   literal six                  6
          _                    -   subtract                     3
        s                      - split into chunks             ["ome","thi","n"]
              ⁾--              - literal list of characters     "--"
             j                 - join                           "ome--thi--n"
                   Ḣ           - head (word)                    "S"
                 ;@            - concatenate (sw@p arguments)   "Some--thi--n"
                     Ṫ         - tail (word)                    "g"
                    ;          - concatenate                    "Some--thi--ng"
                      ḟ0       - filter out zeros (tail yields 0 for words of length 1)
                             ¤  - nilad followed by link(s) as a nilad:
                         ⁴      -   program's 2nd argument      9
                            4   -   literal four                4
                          _     -   subtract                    5
                           ©    -   copy to register & yield    5
                        s       - split into chunks             ["Some-","-thi-","-ng"]

"B" = ẎŒṖK€€ - Line arrangements: list of lists of hyphen-parts / single words
      Ẏ      - flatten by one (make a list of words and hyphen-parts
             - e.g. [["Not"],["hyph-","-ena-","-ted"]] -> ["Not","hyph-","-ena-","-ted"]
       ŒṖ    - partition e.g. [1,2,3]->[[[1],[2],[3]],[[1],[2,3]],[[1,2],[3]],[[1,2,3]]]
         K€€ - join with spaces for €ach for €ach e.g. ["one","two"]->"one two"

"C" = L€>®Ẹ - Any part too long?: one of the list of lines from "B"
      L€    - length of €ach
         ®  - recall from the register (width minus 4)
        >   - greater than (vectorises) - 1 if so 0 if not
          Ẹ - any truthy? (1 if any too long)

"D" = Ṫ;€⁶x®¤ḣ€®s⁵_2¤Zz⁶x®¤j@€€⁾| ,U¤j@€¢ẎY - Format as pages: list of valid arrangements
      Ṫ                                     - tail (last valid partition is greediest)
            ¤                               - nilad followed by links as a nilad:
         ⁶                                  -   literal space character
           ®                                -   recall from register (width minus 4)
          x                                 -   repeat elements
       ;€                                   - concatenate to €ach
               ®                            - recall from register (width minus 4)
             ḣ€                             - head €ach to index
                    ¤                       - nilad followed by links as a nilad:
                 ⁵                          -   program's 3rd argument, height
                   2                        -   literal two
                  _                         -   subtract
                     Z                      - transpose
                          ¤                 - nilad followed by link(s) as a nilad:

                       ⁶                    -   literal space character
                         ®                  -   recall from register (width minus 4)
                        x                   -   repeat elements

                      z                     - transpose with filler (repeated spaces)
                                    ¤       - nilad followed by link(s) as a nilad:
                               ⁾|<space>    -   literal list of characters = "| "
                                   U        -   upend = " |"
                                  ,         -   pair = ["| "," |"]
                           j@€€             - join for €ach for €ach (sw@p arguments)
                                        ¢   - call last link (1) as a nilad
                                     j@€    - join for €ach (sw@p arguments)
                                         Ẏ  - flatten by one
                                          Y - join with line feeds
                                            - implicit print

```

# Answer
> 1 votes
# PHP, 299 bytes

```
for($a=explode(" ",$argv[3]);$y|$e=strlen($d=$a[+$i++]);$x||print"|",$x|$e<$w?$e<$w-$x?$x+=$e+print" $d":$i-=!$x=!$y+=print str_pad("",$w-$x)." |
":$y+=print" ".substr($d,0,$w-2)."- |
".!$a[--$i]="-".substr($d,$w-2),$y>$argv[2]-2&&$y=!print"$t
")$y||$y=print$t=str_pad("+",2+$w=$argv[1]-3,"-")."+
";

```

Run with `php -nr '<code>' <width> <height> '<text>'` or or try it online.

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


title: Now we're thinking in n dimensions!

text:
# Question
Title: Now we're thinking in n dimensions!
The question: Given an a number `n` ≥ 2, how many distinct pairs of points on an `n`-dimensional `n x n x n x n x n x n ... x n` lattice, where the coordinates range from `0` to `n - 1`, are a distance **at least** `n` apart? The pairs `{(2,1,3,1), (3,2,1,3)}` and `{(3,2,1,3), (2,1,3,1)}` are not considered distinct from each other, as they consist of the same two points in reverse order. Note that the total number of pairs grows very rapidly. The number of total pairs goes `6`, `351`, `32 640`, `4 881 250`, `1 088 367 840`, etc.

Test cases:

```
2 -> 0 (all pairs are at most a distance of sqrt(2) < 2 apart)
3 -> 28 (They must either be (2,2,1) or a permutation apart, or (2,2,2) apart. Each corner
has three non-corner (2,2,1) points corresponding to it. And each corner is associated
with a corner pair that is a (2,2,2). Thus. 3.5 * 8 = 28.
4 -> 4,888
5 -> 1,501,948
6 -> 486,039,360 (I would like someone to verify this if possible)

```

Your code should work for n \<= 5, at least in theory. Don't hardcode it, that's a standard loophole.

# Answer
# MATL, 12 bytes

```
tt:Z^tZPR>~z

```

**Try it online!**

### Explanation

```
tt   % Implicit input n. Duplicate twice
     % STACK: n, n, n
:    % Range [1 2 ... n]
     % STACK: n, n, [1 2 ... n]
Z^   % Cartesian power. Gives an n^n × n matrix C where each row is a Cartesian tuple
     % STACK: n, C
t    % Duplicate
     % STACK: n, C, C
ZP   % Euclidean distance. Gives an n^n × n^n matrix D of pairwise distances
     % STACK: n, D
R    % Upper triangular part: sets elements below the main diagonal to 0. Call that U
     % STACK: n, U
>~   % Less than or equal? Element-wise. Gives a true-false matrix B
     % STACK: n, B
z    % Number of nonzeros. Implicitly display
     % STACK: number of entries in B that equal true

```
> 3 votes

# Answer
# Jelly, ~~14~~ 13 bytes

1 byte thanks to Dennis.

```
ṗ⁸Œc_/€ÆḊ€<ċ0

```

Try it online!

## Quick maffs version

```
ŒgL€!P:@L!$×P
²S<
ḶœċçÐḟ²ð>0S’2*×⁸ạ⁹$Ñ¤ð€S

```

Try it online!
> 2 votes

# Answer
# Python 2, ~~137~~ 133 bytes

```
lambda n:sum(n*n<=sum((o[i]-p[i])**2for i in range(n))for o,p in q(q(range(n),repeat=n),repeat=2))/2
from itertools import*
q=product

```

Mr Xcoder & ovs: -4 bytes. Try it online!
> 2 votes

# Answer
# , 40 bytes

```
2%~[:+/^:_]<:[:+/&.:*:"1[:-"1/~#~#:i.@^~

```

Try it online!

Will time out on TIO for 5 if you use extended precision (`5x` instead of `5`). I'm not going to bother trying with 6 on my computer since that will no doubt crash the interpreter.

Looking for advice on golfing, specifically the part past the generation of the coordinates. I feel like there ought to be a way to remove some of the caps.

`]<:[:+/&.:*:"1` may be equivalently replaced by `*:<:[:+/"1[:*:`.

# Explanation

This explanation is done on the REPL (three spaces indicate a command, no spaces indicate an output). I will be building up to the answer.

### Generating the coordinates

`#~ #: i.@^~` gives all the coordinates we care about on the lattice.

`^~` is a number raised to itself, and `i.` gives the range \[0,n) where n is its input. `@` composes those functions.

```
   i.@^~ 2
0 1 2 3

```

`#~` copies a number by itself, e.g.

```
   #~ 3
3 3 3

```

`#:` converts its right argument to the base specified by the *array* given as its left argument. The number of digits in the array corresponds to the number of digits in that base output (and you can have a mixed base) For example,

```
   3 3 3 #: 0
0 0 0
   5 5 #: 120
4 0
NB. If you want 120 base 5 use #.inv
   #.inv 120
4 4 0

```

So, all together, this says enumerate through all of the values base n (where n is the input) up to n^n, effectively giving us our coordinates.

```
   (#~ #: i.@^~) 2
0 0
0 1
1 0
1 1

```

### Getting the distances between each pair

First we take the difference of each coordinate with all of the others using the dyad `/`-table and `~`-reflexive. Note that this doesn't account for the fact that order doesn't matter for the pairs: this generates duplicate distances.

```
  NB. 2 {. takes the first two elements (I'm omitting the rest).
  2 {. -"1/~ (#~ #: i.@^~) 2
 0  0
 0 _1
_1  0
_1 _1

 0  1
 0  0
_1  1
_1  0

```

Then we use this verb `+/&.:*:` on each coordinate (at `"1`, aka rank one). This verb is sum (`+/`) under (`&.:`) square (`*:`). Under applies the right verb (square) then collects its results and gives it as the argument to the left verb (sum). It then applies the inverse of the right verb (which would be square root).

```
   +/&.:*: 3 4
5
   +/&.:*:"1 ([: -"1/~ #~ #: i.@^~) 2
      0       1       1 1.41421
      1       0 1.41421       1
      1 1.41421       0       1
1.41421       1       1       0

```

Unsurprisingly, many distances are the same.

### Counting the distances greater than or equal to the input

The last part is seeing if the distance is greater than or equal to the input using `]<:`. Then all of the results are summed using `+/^:_` (sum until converge), counting the number of truthy values. Then this value is divided by 2 (`2%~`, here `~` means swap the order of the arguments supplied to `%`). The reason why we can divide by 2 is because for each truthy pairing, there will be another one for the flipped order *except* for pairings which are a coordinate with itself. That's ok, though, since those will result in a distance of 0.
> 2 votes

---
Tags: code-golf, combinatorics
---


title: Shortest Code to Translate a PHP array

text:
# Question
Title: Shortest Code to Translate a PHP array
## NOTE: This question was migrated from https://stackoverflow.com/q/27134588/1442685

PHP QUESTION

Almost purely out of curiousity, how can I take an array like this:

```
array( 'fruit' => 'banana', 'drink' => 'milk')

```

And convert it to an array like this:

```
array( 'fruit=banana', 'drink=milk')

```

**Requirements**

* Cannot use anonymous functions
* If needed, can only use `array_*` functions that accept callable if that callable is native to PHP
* Must be a one-liner solution

---

This is not for a class. I'm curious to see how clever one can be with array functions. Given the requirements, is it possible?

# Answer
```
explode('&',http_build_query($a))

```

33 bytes
> 7 votes

# Answer
# PHP (33 bytes)

I am not 100% sure if this is valid.

I used 0 (**zero**) functions.

This solution is 1 byte shorter than @Devon's solution.

The code:

```
foreach($a as$k=>$v)$z[]="$k=$v";

```

The var `$a` is the array, the var `$z` will have the new array.

There are no restrictions to the vars or how it should be implemented.
> 5 votes

# Answer
# 32 bytes

```
foreach($a as$k=>&$v)$v="$k=$v";

```

Update by reference, shaves off 1 byte.

Not sure how important removing the original key is, sort of a grey area.

This is what I mean:

```
[
    ['fruit'] => 'fruit=banana',
    ['drink'] => 'drink=milk'
]

```

But it saves on variables, as your not creating a new array
> 1 votes

---
Tags: code-golf, tips, array, php
---


title: 52 Week Challenge

text:
# Question
Title: 52 Week Challenge
The 52 week challenge is a way to save money. For example, Week 1, you save $1.00. Week 2 you save $2.00, and it continues through the year, adding one more dollar to each week’s savings goal. By Week 52, you’ll set aside $52.00, which will bring the year’s total savings to $1,378! Of course, you can decide how much money you start saving and how many weeks.

Given an amount for Week 1 and the number of weeks the challenge should run for, return the total amount saved at the end of the challenge.

Week 2 will have as twice the amount of Week 1, Week 3 will have thrice the amount of Week 1, etc.

### Examples

`1` and `52` weeks: `1378`

`5` and `6` weeks: `105`

`.25` and `100` weeks: `1262.5`

`10` and `1` week: `10`

`7` and `0` weeks: `0`

`0` and `30` weeks: `0`

`0` and `0` weeks: `0`

# Answer
> 1 votes
# Japt, 5 bytes

Takes weeks as the first input and starting amount as the second.

```
õ x*V

```

Try it

# Answer
> 1 votes
# , 6 bytes

```
*2!1+]

```

Takes the amount as the left argument and the weeks as the right argument.

Try it online!

### Explanation

```
* 2 ! 1 + ]
      1 + ]  Add 1 to the weeks.
  2 !        (Weeks + 1 choose 2)
*            Multiply by the starting amount.

```

This takes advantage of the fact that the nth triangle number is (n+1 choose 2). Perhaps unsurprisingly, this is almost the exact same answer as the one I have for the sum of digits from 1 to n challenge. Just substitute `>:` for `1+]` and tack on the `*`.

# Answer
> 1 votes
# Wolfram Language (Mathematica), 13 bytes

```
#*(#+1)*#2/2&

```

Try it online!

# Answer
> 0 votes
# , 23 bytes

```
function(a,w)sum(0:w*a)

```

Try it online!

Takes input as `a`mount, `w`eeks.

# Answer
> 0 votes
# Python 3, 20 bytes

```
lambda a,w:a*w*-~w/2

```

Try it online!

# Answer
> 0 votes
# Jelly, 3 bytes

```
R×S

```

Try it online!

---
Tags: code-golf, math, sequence, arithmetic, simulation
---


title: Find Hybridizations

text:
# Question
Title: Find Hybridizations
Covalent bonding uses so-called "hybrid" orbitals to form tetrahedral, octahedral, etc. formations out of the *s*, *p*, and sometimes *d* orbitals. Their naming conventions are pretty much the concatenation of the component orbitals; for example, the hybridization of the *s* orbital and one *p* orbital would be the two *sp* orbitals, and the hybridization of the *s* orbital, all three *p* orbitals, and 2 of the 5 *d* orbitals would be the 6 *sp*3*d*2 orbitals. Real-life hybrid orbitals rarely go beyond this, but of course we'll do it anyway.

# The Challenge

Write a program that takes in the number of orbitals needed and outputs the name of the hybrid orbital as a string such as `sp3d4`. Superscripts can be omitted.

The standard orbitals, ordered by the order in which they're hybridized, are as follows:

```
letter   # orbitals
  s           1
  p           3
  d           5
  f           7

```

No orbital should be used unless all lower orbitals have already been consumed. For example *spd*2 is not a valid orbital hybridization because there is still a *p* orbital that is not used.

If you go beyond the *f* orbital, then use the angular momentum quantum number (the zero-indexed position in this series: 0 is *s*, 1 is *p*, etc.) in parentheses. For example, 27 would be `sp3d5f7(4)9(5)2`. The number of orbitals for each set should continue with the pattern of "twice the angular momentum quantum number plus one".

Also, don't list the number of orbitals used in the output if that would be 1. It's *sp*3*d*, not *s*1*p*3*d*1.

# Test Cases

```
1 => s
2 => sp
3 => sp2
5 => sp3d
12 => sp3d5f3
36 => sp3d5f7(4)9(5)11

```

# Victory

The winner will be the shortest answer in bytes.

# Answer
## JavaScript (ES6), 75 bytes

```
f=(n,l=0,r=n>l*2?l*2+1:n)=>n?("spdf"[l]||`(${l})`)+(r-1?r:'')+f(n-r,l+1):''

```
> 3 votes

# Answer
## JavaScript 121 bytes

Works thanks to Stephen Leppik :)

```
o="";a=["s","p","d","f"];i=0;while(x>0){i<4?o+=a[i]:o+="("+i+")";b=Math.min(2*i+1,x);b>1?o+=b:z=0;x-=b;i++}console.log(o)

```

Here is the not golfed version :

```
o="";
a=["s","p","d","f"];
i=0;
while(x>0){
    i<4?o+=a[i]:o+="("+i+")";
    b=Math.min(2*i+1,x);
    b>1?o+=b:z=0;             //z : useless assignment
    x-=b;i++;
}
console.log(o);

```
> 2 votes

---
Tags: code-golf, chemistry
---


title: Make a Spiky Box

text:
# Question
Title: Make a Spiky Box
Given two positive integers, W and H, output an ASCII-art box whose border is made of slashes (`/` and `\`) with W "spikes" on the top and bottom edges, and H "spikes" on the left and right edges. The box's interior is filled with spaces.

A "spike" is simply two slashes coming together to form an arrow shape:

```
/\    \/

/      \
\      /

```

So the output for `W = 4, H = 3` would be

```
/\/\/\/\
\      /
/      \
\      /
/      \
\/\/\/\/

```

as there are 4 spikes on the top pointing up, 4 on the bottom pointing down, 3 on the left pointing left, and 3 on the right pointing right.

Here are some other input/output pairs:

```
W H
[spiky slash box]

1 1
/\
\/

1 2
/\
\/
/\
\/

2 1
/\/\
\/\/

2 2
/\/\
\  /
/  \
\/\/

1 3
/\
\/
/\
\/
/\
\/

3 1
/\/\/\
\/\/\/

2 3
/\/\
\  /
/  \
\  /
/  \
\/\/

3 2
/\/\/\
\    /
/    \
\/\/\/

10 1
/\/\/\/\/\/\/\/\/\/\
\/\/\/\/\/\/\/\/\/\/

10 2
/\/\/\/\/\/\/\/\/\/\
\                  /
/                  \
\/\/\/\/\/\/\/\/\/\/

4 5
/\/\/\/\
\      /
/      \
\      /
/      \
\      /
/      \
\      /
/      \
\/\/\/\/

```

No lines in the output should have leading or trailing spaces. There may optionally be one trailing newline.

**The shortest code in bytes wins.**

# Answer
> 15 votes
# Charcoal, 9 bytes

```
Ｂ×²Ｎ×²Ｎ/\

```

Try it online!

### Explanation

```
Ｂ           Box
  ×²Ｎ       Next input as number * 2
      ×²Ｎ   Next input as number * 2
          /\ With border "/\"

```

# Answer
> 11 votes
# MATL, 18 bytes

```
'\/',iE:]!+)O6Lt&(

```

Try it at MATL Online!

### Explanation

Consider inputs `W = 4`, `H = 3`. The code builds the row vectors `[1 2 3 4 5 6 7 8]` (range from `1` to `2*W`) and `[1 2 3 4 5 6]` (range from `1` to `2*H`). Transposing the latter and adding to the former with broadcast gives the matrix

```
2  3  4  5  6  7  8  9
3  4  5  6  7  8  9 10
4  5  6  7  8  9 10 11
5  6  7  8  9 10 11 12
6  7  8  9 10 11 12 13
7  8  9 10 11 12 13 14

```

Modular indexing into the string `\/` produces the desired result in the matrix border:

```
/\/\/\/\
\/\/\/\/
/\/\/\/\
\/\/\/\/
/\/\/\/\
\/\/\/\/

```

To remove the non-border values, we set them to `0` (when interpreted as char it is displayed as space):

```
/\/\/\/\
\      /
/      \
\      /
/      \
\/\/\/\/

```

Commented code:

```
'\/'    % Push this string. Will be indexed into
,       % Do twice
  i     %   Input a number
  E     %   Multiply by 2
  :     %   Range
]       % End
!       % Transpose
+       % Add
)       % Index
O       % Push 0
6L      % Push [2 -1+1j]. As an index, this means 2:end
t       % Duplicate
&(      % Write 0 into the center rectangle. Implicit display

```

# Answer
> 8 votes
# Python 2, ~~69~~ 68 bytes

-1 thanks to Kevin Cruijssen

```
lambda w,h:'/\\'*w+'\n'+'\\%s/\n/%s\\\n'%(('  '*~-w,)*2)*~-h+'\\/'*w

```

Try it online!

# Answer
> 7 votes
# Haskell, ~~90~~ ~~88~~ ~~87~~ 82 bytes

*~~1~~ 6 bytes saved thanks to Lynn*

```
a#b=[1..a]>>b
x!y|i<-(x-1)#"  "=x#"/\\":(y-1)#['\\':i++"/",'/':i++"\\"]++[x#"\\/"]

```

Try it online!

Still feels really long, I'll see what I can do.

# Answer
> 6 votes
# 05AB1E, 14 bytes

```
„/\|∍`S¦`).B∞∊

```

Try it online!

### Explanation

```
„/\|∍`S¦`).B∞∊   Arguments: x, y
„/\              Push the string "/\"
   |             Push inputs as array: [x,y]
    ∍            Push the string extended/shortened to those lengths
     `           Flatten
      S          Push seperate chars of second string
       ¦`        Remove first char and flatten again
         )       Wrap stack to an array
          .B     Squarify
            ∞∊   Mirror on both axes

```

This only creates the top left corner, x characters wide and y characters tall. It then mirrors this on both axes:

```
x=3, y=2

/\/|
\  |
---+

```

# Answer
> 4 votes
## JavaScript (ES6), 84 bytes

Takes input in currying syntax `(w)(h)`.

```
w=>h=>'/\\'[R='repeat'](w)+`
${`\\${p='  '[R](w-1)}/
/${p}\\
`[R](h-1)}`+'\\/'[R](w)

```

### Demo

```
let f =

w=>h=>'/\\'[R='repeat'](w)+`
${`\\${p='  '[R](w-1)}/
/${p}\\
`[R](h-1)}`+'\\/'[R](w)

function upd() { O.innerHTML = W.value+'x'+H.value+'\n\n'+f(W.value)(H.value) }
upd()
```

```
<input id=W type=range value=5 min=1 max=10 oninput="upd()">
<input id=H type=range value=5 min=1 max=10 oninput="upd()">
<pre id=O>
```

# Answer
> 3 votes
# Swift 3, 166 bytes

```
func f(a:Int,b:Int){let k=String.init(repeating:count:),n="\n";var r="\\"+k("  ",a-1)+"/";print(k("/\\",a)+n+k(r+n+String(r.characters.reversed())+n,b-1)+k("\\/",a))}

```

**Full test suite.**

The closure version is a bit longer, unfortunately (175 bytes):

```
var g:(Int,Int)->String={let k=String.init(repeating:count:),n="\n";var r="\\"+k("  ",$0-1)+"/";return k("/\\",$0)+n+k(r+n+String(r.characters.reversed())+n,$1-1)+k("\\/",$0)}

```

**Test suite with the closure version.**

# Answer
> 3 votes
# Retina, ~~77~~ 73 bytes

```
\d+
$*
 1+|1(?=1* (1+))
$1¶
1
/\
.((..)*.)
/$1¶$1/
¶$

(?<=¶.+).(?=.+¶)

```

Try it online! Link includes test cases. Takes input in the format `<height> <width>`. Explanation:

```
\d+
$*

```

Convert the inputs to unary.

```
 1+|1(?=1* (1+))
$1¶

```

Multiply the inputs, but add a newline so that the result is a rectangle.

```
1
/\

```

Create the spiky top.

```
.((..)*.)
/$1¶$1/

```

Duplicate each spiky row, but with the spikes offset on the second row.

```
¶$

```

Delete trailing newlines.

```
(?<=¶.+).(?=.+¶)

```

Delete the inside of the box. (Note space on last line.)

# Answer
> 3 votes
# C (gcc), ~~170~~ ~~166~~ ~~158~~ ~~155~~ ~~108~~ 105

*-3 bytes thanks to cleblanc*

```
x,y;f(w,h){for(y=h*=2;y--;puts(""))for(x=w*2;x--;)putchar(!x|x==w*2-1|!y|y==h-1?x&y&1|~x&~y&1?47:92:32);}

```

Try it online!

~~I think this can be golfed further with a less straightforward approach, I'll see what I can do when I find the time.~~

Ok I cannot find any other way to reduce the number of bytes for that code.

Explanation: a simple double-loop printing the box char by char.

When printing a border: if both x and y coordinates are either even or odd, it displays a `/`, otherwise, a `\` is displayed

If not a border, a space character is displayed instead

# Answer
> 3 votes
# APL (Dyalog), ~~41~~ 39 bytes

Prompts for a list of `[H,W]`

```
'\'@2@1⊢¯1⌽@1{⌽⍉⍵,'/\'⍴⍨≢⍵}⍣4⊢''⍴⍨2×⎕-1

```

Try it online!

`⎕-1` prompt for input (mnemonic: stylized console) and subtract 1

multiply by two

`''⍴⍨` use that to reshape an empty string (pads with spaces)

yield that (serves to separate it from `4`)

`{``}⍣4` apply the following function four times:

`≢⍵` tally (length of) the argument

`'/\'⍴⍨` cyclically **r**eshape `"/\"` to that length

`⍵,` append that to the right side of the argument

`⌽⍉` transpose and mirror (i.e. turn 90°)

`¯1⌽1` cyclically rotate the 1st row one step to the right

yield that (serves to separate it from `1`)

`'\'@2@1` put a backslash at the 2nd position of the 1st major item.

# Answer
> 3 votes
# Excel, 95 bytes

```
=REPT("/\",A1)&"
"&REPT("\"&REPT(" ",2*A1-2)&"/
/"&REPT(" ",2*A1-2)&"\
",B1-1)&REPT("\/",A1)

```

# Answer
> 3 votes
# ///, ~~172~~ 117 bytes

So, because the output consists of `///`s and `whitespace`s, there should be submissions in those 2 languages.

Put the input after the code in `W,H` as unary number (unary for /// is allowed, thanks to Challenger5 for suggestion) (use `*` to represent digit, separate with `,`) format.

```
/W/VV//V/\\\///`/\\\\\\\\\\\\\V/,/W>+  V`/`\>+W  !V!``WV>+WV-  V`\
`\W+  V`/
`/W-!V`\
W``\\V`\V>!//!*/+%-%!//*/  //%/
```

Try it online! (with input `W=4, H=3`)

# Answer
> 2 votes
# Python 3, 87 82 bytes

**Edit:** Saved 5 bytes thanks to @officialaimm, @Mr.Xcoder and @tsh

```
def f(a,b,n="\n"):r="\\"+"  "*~-a+"/";print("/\\"*a+n+(r+n+r[::-1]+n)*~-b+"\\/"*a)

```

Try it online!

# Answer
> 2 votes
# SOGL V0.12, ~~22~~ ~~21~~ 13 bytes

```
/\”m;HΙ»mč+╬¡

```

Try it Here! (expects both inputs on stack so `..` (and `"` because a string hasn't been explicitly started) - take number input twice is added for ease-of-use)

Explanation:

```
/\”            push "/\"
   m           mold to the 1st inputs length
    ;          get the other input ontop of stack
     H         decrease it
      Ι        push the last string - "/\"
       »       rotate it right - convert to "\/"
        m      mold "\/" to the length of 2nd input - 1
         č     chop into characters
          +    prepend the 1st molded string to the character array of the 2nd
           ╬¡  quad-palindromize

```

# Answer
> 2 votes
# J, 48 bytes

```
' '&((<,~<<0 _1)})@(+:@[$(1&|.,:])@('\/'$~+:)@])

```

## ungolfed

```
' '&((< ,~ <<0 _1)}) @ (+:@[ $ (1&|. ,: ])@('\/' $~ +:)@])

```

## explanation

```
                       (+:@[ $ (1&|. ,: ])@('\/' $~ +:)@])    creates box, but interior filled with slashes
                                           ('\/' $~ +:)@]       take right arg, W, doubles it, then fills that
                                          @                       many characters with '\/' repeating
                               (1&|. ,: ])                      stacks (,:) the above on top of itself rotated
                                                                  by one char, producing top and bottom spikes
                              $                                 reshape to..
                       (+:@[                                    double the length of the left arg, height
                                                                  this creates the sides, as well as a filled interior
                     @
' '&((< ,~ <<0 _1)})                                          removes slashes from interior by using the complement
                                                                form of amend }.  ie, replace everything but the first
                                                                and last row and first and last col with a space

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 19 bytes

```
4FNÈi¹}·„\/NÉiR}N·Λ

```

Try it online!

Takes arguments reversed.

# Answer
> 2 votes
# Haskell, ~~84~~ 79 bytes

```
w%h=[[last$"/\\"!!mod(x+y)2:[' '|x>1,y>1,x<2*w,y<2*h]|x<-[1..2*w]]|y<-[1..2*h]]

```

Try it online! Example usage: `3%6` yields a list of lines. Use `mapM putStrLn $ 3%6` to pretty-print the box.

# Answer
> 2 votes
# Java 8, 141 bytes

A curried lambda from width to height to output.

```
w->h->{String f="/",b="\\",t=f,o=b,p="";char i=1;for(;i++<w;t+=b+f,o+=f+b)p+="  ";t+=b;o+=f;for(i=10;--h>0;)t+=i+b+p+f+i+f+p+b;return t+i+o;}

```

Try It Online (no, `return t+i+o;` was not intentional)

## Ungolfed lambda

```
w ->
    h -> {
        String
            f = "/",
            b = "\\",
            t = f,
            o = b,
            p = ""
        ;
        char i = 1;
        for (; i++ < w; t += b + f, o += f + b)
            p += "  ";
        t += b;
        o += f;
        for (i = 10; --h > 0; )
            t += i + b + p + f + i + f + p + b;
        return t + i + o;
    }

```

This solution is atypically picky about input size since a `char` is used to count up to the width input. Fortunately, the algorithm is bad enough that at those sizes program completion is probably already an issue. I chose to use `char` for the loop index so I could reuse it later as a cheap alias for `'\n'`.

# Answer
> 1 votes
# Mathematica, 87 bytes

```
Table[Which[1<i<2#2&&1<j<2#," ",OddQ[i+j],"\\",1>0,"/"],{i,2#2},{j,2#}]~Riffle~"
"<>""&

```

Try it in Mathics (it prints extra spaces at the start of most lines for some reason), or at the Wolfram sandbox! Takes two integers as input.

It's a fairly naïve solution, but all of the clever things I tried had more bytes. Something that nearly works is

```
ArrayPad[Array[" "&,2#-2],1,{{"/",s="\\"},{s,"/"}}]~Riffle~"\n"<>""&

```

except it fails if either dimension is 1 (input is a list containing the dimensions).

# Answer
> 1 votes
# Pyth, ~~40 39~~ 38 bytes

```
+++*Q"/\\"b*tE+++K++\\*d*2tQ\/b_Kb*"\/

```

This takes the two integers separated by a newline.

**Full test suite.**

# Answer
> 1 votes
# Ruby, ~~62 61~~ 60 bytes

```
->r,c{["/\\"*c]+["\\#{w="  "*~-c}/",?/+w+?\\]*~-r+["\\/"*c]}

```

-1 byte thanks to Arnauld

Try it online!

# Answer
> 1 votes
# Actually, 38 bytes

```
"/\"*;.R;l¬' *"\/"@j;R(D(╗WD(;.(;.(Wé╜

```

Try it online!

# Answer
> 1 votes
# , 39 bytes

```
(' \/'{~=/&(2&|)(*>:)~0=*/&(*|.))&i.&+:

```

Try it online!

Takes two arguments as `height` on the LHS and `width` on the RHS.

# Answer
> 1 votes
# R, ~~160 bytes~~ 152 bytes

```
p=function(x,n){paste(rep(x,n),collapse='')}
function(w,h){f=p(' ',w*2-2)
cat(paste0(p('/\\',w),'\n',p(paste0('\\',f,'/\n/',f,'\\\n'),h-1),p('\\/',w)))}

```

Try it online!

Thanks BLT for shaving off 8 bytes.

# Answer
> 1 votes
# \>\<\>, 180 Bytes

```
0&0\
a*+>i68*-:0(?v$
/)\^0&1v?)0&~/
? 0 v:$<
/ \:<-1oo'/\'
\~$:@2*0&\
'/'1>&o1->a\ /'/'>o$:2*>1-:1)?\~$&1=?\
'\'0//?(3:o/?/'\'/     \o*48  /      \
/?)0\ &:&1=/;
\  \:~
'/'/\<oo'\'

```

# Answer
> 1 votes
**VBA (Excel) , 161 Bytes**

```
Sub a()
c=[A2]*2
r=[B2]*2
For i=1To r
For j=1To c
b=IIf(i=1 Or j=1 Or i=r Or j=c,IIf((i+j) Mod 2,"\","/")," ")
d=d & b
Next
d=d & vbCr
Next
Debug.Print d
End Sub

```

# Answer
> 0 votes
# Perl 5, 83 + 1 (-n) = 84 bytes

```
say"/\\"x($q=$F[0]);print(("\\".($s=$"x(2*$q-2))."/$//$s\\$/")x--$F[1]);say"\\/"x$q

```

Try it online!

# Answer
> 0 votes
# dc, 123 bytes

```
?1-sesf[/\]su[lfsh[lunlh1-dsh0<q]dsqx]dsrx[[
\]P[lf2*2-st[32Plt1-dst0<z]dszx]dsmx[/
/]Plmx92Ple1-dse0<l]slle0<l10P[\/]sulrx

```

It's far from the shortest, but, if one takes the last two lines and rotates them `pi/2` radians clockwise to an "upright" position, it kind of looks like a totem pole.

Takes input as two space-separated integers.

Try it online!

# Answer
> 0 votes
# Mathematica, 116 bytes

```
(c=Column;o=Table;v=""<>o[" ",2*#-2];w=""<>o["/\\",#];c[{w,c@o[c[{"\\"<>v<>"/","/"<>v<>"\\"}],#2-1],Rotate[w,Pi]}])&

```

# Answer
> 0 votes
# , 18 bytes

```
Ài/\Ùæ$Àäkllòjjkè

```

Answer wouldn't require the `ll` if `<M-h>ollow` left 2 char columns alone :(

Try it online!

# Answer
> 0 votes
# C# (.NET Core), 188 bytes

```
a=>b=>string.Join("\n",new int[2*b].Select((x,i)=>string.Concat(string.Concat(new int[a].Select(y=>i%2==0?"/\\":"\\/")).Select((y,j)=>i>0&i<2*b-1&j>0&j<2*a-1?" ":""+y))))

```

Byte count also includes:

```
using System.Linq;

```

Try it online!

I started making explanation command-by-command but it stopped making sense midway... Basic gist is to make full spiky box, and then hollow out the middle. I used Linq for the sake of using Linq, probably can be shorter using just standard iterations.

Here's explanation going middle-out (the inner-most command first):
First, create rows for the full box, and concatenate to a single string

```
string.Concat(new int[a].Select(y => i % 2 == 0 ? "/\\" : "\\/"))

```

Then get each character in a row, and if it isn't the outline of the box, replace with space, concatenate them back into one string for each row

```
string.Concat(PREVIOUS_STEP.Select((y, j) => i > 0 & i < 2 * b - 1 & j > 0 & j < 2 * a - 1 ? " " : "" + y))

```

Finally, get each row and concatenate them together with newlines (also includes generating of a collection for rows)

```
string.Join("\n", new int[2 * b].Select((x, i) => PREVIOUS_STEP));

```

# Answer
> 0 votes
# Jelly, 19 bytes

```
JṖḊ
Ḥ+þ/ị⁾\/⁶Ç¦€Ç¦Y

```

**Try it online!**

### How?

```
JṖḊ - Link 1, middle indexes: list
J   - range of length [1,2,3,...,length-1,length]
 Ṗ  - pop             [1,2,3,...,length-1]
  Ḋ - dequeue           [2,3,...,length-1]

Ḥ+þ/ị⁾\/⁶Ç¦€Ç¦Y - Main link: list of numbers [w,h]
Ḥ               - double (vectorises) -> [2*w,2*h]
   /            - reduce by:
  þ             -   outer product with:
 +              -     addition ->  [[1,2,...,w],[2,3,...,1+w],...,[h+1,h+2,...,h+w]]
     ⁾\/        - literal ['\','/']
    ị           - index into (vectorises) -> ["/\/\.../\","\/\/...\/",...,"\/\/...\/"]
             ¦  - sparse application:
            Ç   - ...to indexes: call the last link as a monad (the middle ones)
          ¦€    - ...of: sparse application for €ach:
         Ç      -        ...to indexes: call the last link as a monad (the middle ones)
        ⁶       -        ...of: a space character (blank out the middle entries)
              Y - join with newlines
                - as a full program: implicit print

```

# Answer
> 0 votes
# APL (Dyalog), 30 bytes

```
' \/'[(⌽⌈⊖)3|((-0=⌊)*+)/↑⍳2×⎕]

```

Try it online!

# Answer
> 0 votes
# Excel VBA, 89 Bytes

Anonymous VBE immediate window function that takes input as `w` from `[A1]` and `h` from `[B1]` and then outputs to the VBE immediate window.

```
a=[Rept("/\",A1)]:?a:s=space(2*[A1-1]):For i=1To[B1-1]:?"\"s"/":?"/"s"\":Next:?Mid(a,2)"/

```

---
Tags: code-golf, string, ascii-art, integer
---


title: Proto space invaders (can you blit it?)

text:
# Question
Title: Proto space invaders (can you blit it?)
**Proto space invaders**

This is a graphical output challenge where the task is to give the shortest code per language.

**Task**

Your code should allow the user to move the following alien around the screen/window.

Your code can simply load it from a local file. Feel free to convert it to another standard image format or even to fix the small pixel errors in the image that were pointed out in the comments.

The background should be white and the window/screen must be at least 400 pixels by 400 pixels. If your language doesn't support windows/screens that large then use the largest size it does support as long as that is not less than 200 by 200.

To move the alien around the screen the code should support up/down/left/right using the arrows keys on a standard keyboard.

Your code should be a **full program**.

**Restrictions/constraints**

The alien should stop at the borders. It should also move at a uniform rate **smoothly** with no visible flickering or stuttering and be shown at at least 24fps. It should take between 2 and 5 seconds to go from one side of the screen/window to the other.

**Languages and libraries**

You can use any language or library you like (that wasn't designed for this challenge). However, I would like to be able to test your code if possible so if you can provide clear instructions for how to run it in Ubuntu that would be very much appreciated.

### Catalog

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

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

```
## Language Name, N bytes

```

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

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

```

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

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

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

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

```

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 62426; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 9206; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
> 12 votes
# Scratch, ~~221~~ 217 bytes

Click the image to view it in action. The movement is determined by *keystrokes*, so it will be smoother the faster your key repeat is set.

The image is included within the project, but Scratch bytes are usually counted from the golfed textual representation, per this meta post. If there is disagreement as to whether this is acceptable (or whether the movement is smooth enough) let me know and I will try to work around it.

# Answer
> 6 votes
## Processing 2, ~~219 199 241 220~~ 219 bytes

```
int a,x=0,y=0;void setup(){size(500,500);}void draw(){background(-1);image(loadImage(".png"),x,y);if(keyPressed){a=keyCode;if(a==38)y--;if(a==37)x--;if(a==40)y++;if(a==39)x++;}x=constrain(x,0,436);y=constrain(y,0,454);}

```

Requires the image saved as `.png` in the same directory as the .pde

# Answer
> 6 votes
## Python 2, ~~262~~ ~~253~~ ~~246~~ 240 bytes

```
from pygame import*
init()
key.set_repeat(1)
p=[0,0]
d=display
c=d.set_mode((400,)*2)
while c.fill((255,)*3):
 e=event.get(2);c.blit(image.load("I"),p);d.flip()
 if e:x=e[0].key+1;q=x&2;b=q/2;p[b]=max(0,min(336+b*16,p[b]+(1-q)*(1-(2*x&2))))

```

Wow. What a lot of hackery.

Uses the module 'pygame' found at http://pygame.org.

### Explanation

`key.set_repeat(1)` \- Send repeat key events through the event system every millisecond

`c=d.set_mode((400,)*2)` \- Create the 400x400 display surface

`while c.fill((255,)*3):` \- Effectively `while 1:` but clears the screen as well

`e=event.get(2);c.blit(image.load("I"),p);d.flip()` \- Only collect keyboard events, load the image stored in a png file called `I` and draw it. Update the screen

`if e:x=e[0].key+1;q=x&2;b=q/2;p[b]=max(0,min(336+b*16,p[b]+(1-q)*(1-(2*x&2))))` \- If there was an event, work out which arrow key was pressed (does weird stuff if you press other keys), and then change the position of the surface depending on which key you pressed.

# Answer
> 5 votes
## Haskell, 410 bytes

```
import Graphics.Gloss
import Graphics.Gloss.Interface.Pure.Game
main=do b<-loadBMP"b";play(InWindow""(400,400)(0,0))white 200((0,0),id)(b#)e(%)
e(EventKey(SpecialKey k)Down _ _)(c,_)|k==KeyUp=(c,fmap(+1))|k==KeyDown=(c,fmap(+(-1)))|k==KeyLeft=(c,((+(-1))?))|k==KeyRight=(c,((+1)?))
e(EventKey _ Up _ _)(c,_)=(c,id)
e _ w=w
_%(c,f)=(s?(s<$>f c),f)
s=min 200.max(-200)
b#((x,y),_)=Translate x y b
f?(a,b)=(f a,b)

```

The picture of the alien is expected in a file named `b` in `.bmp` format.

I'm new to the Gloss library, so maybe this is not optimal. Does anyone know if I can check if a key is pressed instead of tracking `KeyUp`/`KeyDown` events?

How it works: the last four parameters of `play` are the world state (initialized with `((0,0),id)`, a function to draw a picture from a state (`#`), an event handler (`e`) and a function that changes the state over time (`%`).

The state is a pair of x-y-coordinates and a function how to change them whenever `%` is called.

`#` moves the bitmap (`b`) to the current coordinates and draw it.

`e` looks for either `KeyDown` events of the cursor keys and sets appropriate functions in the state or for `KeyUp` of any key to reset the function in the state to the identity function.

`%` applies the function from the state to the current coordinates and checks the boundaries.

# Answer
> 4 votes
# Elm, 240 bytes

```
import Graphics.Element as G
import Keyboard as K
import Time
import Signal exposing(..)
c=min 800>>max 64
i(x,y)=G.container x y G.middle(G.image 64 48"https://i.stack.imgur.com/CUweU.png")
main=i<~foldp(\{x,y}(v,w)->(c v+x,c w-y))(99,99)(sampleOn(Time.fps 200)K.arrows)

```

Try it here. Byte count is after replacing the URL with `.png`.

# Answer
> 3 votes
## AutoIt, ~~269~~ 267 bytes

```
#include<Misc.au3>
GUICreate(0,-1,-1,-1,-1,-1,34078728)
$0=GUICtrlCreatePic("b.bmp",0,0,64,48)
GUISetState()
Dim $1,$2
$3=_IsPressed
Do
$1+=$3("27")-$3("25")
$2+=$3("28")-$3("26")
$1=($1>336)?336:($1<0)?0:$1
$2=($2>352)?352:($2<0)?0:$2
GUICtrlSetPos($0,$1,$2)
Until 0

```

Requires the picture to be saved as b.bmp in the script directory. If you want to use a picture with actual transparency, you have to to convert it from PNG to a 32bit Bitmap (OT: a really unappreciated format).

### Explanation

We need to import `Misc.au3` to get access to `_IsPressed`. A function that accepts a key code and returns `True` or `False` when the key is pressed.

The spec of the challenge is quite cool in the way that we have to create a 400px square window. The default (denoted as `-1` or `Default`) size parameters are 400x400. The extended windows style is set to `34078728`. This forces the window to be double-buffered and drawn from bottom to top. This is necessary to eliminate flickering as per the challenge requirement. In Windows 10, this unusual (and somewhat undocumented) combination of styles breaks the window title bar (all hovering effects are disabled).

`$1` and `$2` are declared and will hold the x and y offset of the picture loaded by the control `$0`. `$3` becomes a pointer to the function `_IsPressed` to shorten the code significantly.

Since it is not required to be able to exit the program, this script runs in an infinite loop (`Until 0`).

`$1+=$3("27")-$3("25")` abuses the variant datatype in AutoIt by dynamically casting the boolean value returned from `_IsPressed` to an integer that can be added or sub'ed from the x offset. Same for y. `$1=($1>336)?336:($1<0)?0:$1` uses the ternary operator known from C-like languages to perform a bounds check to stop the alien at the borders.

`GuiCtrlSetPos` moves the picture control to the new coordinates.

Here's a screenshot with a transparent alien (you can even move diagonally):

# Answer
> 2 votes
# SpecBAS - ~~285~~ 255 bytes

```
1 GRAPHIC NEW v LOAD "inv8.bmp" TRANSPARENT 15
2 PALETTE COPY v,0,1 TO 5: GRAPHIC REMAP v
3 LET x,y=100
4 CLS : WINDOW PUT GRAPHIC v,0,x,y
5 LET x=x+KEYST(39)-KEYST(37),y=y+KEYST(40)-KEYST(38)
6 LET x=CLAMP(x,1 TO 400),y=CLAMP(y,1 TO 400)
7 WAIT SCREEN
8 GO TO 4

```

Loads the image - colour 15 is bright white, so that becomes transparent.

Using the original image and default SpecBAS palette made it come out a bit odd, so line 2 switches them around to match the input image. Below image shows how it looks without line 2 and after.

The CLAMP command limits the graphic between 1 and 400 in both directions, saves on several IF...THEN statements.

Line 9 just waits for things to catch up and prevents flickering.

It moves one pixel at a time based on a boolean check of which key is pressed, so takes slightly longer than 5 seconds to go from side to side.

# Answer
> 2 votes
# Ruby with Shoes, ~~252~~ 243 characters

```
Shoes.app{background white
i=image'i'
m=[0,0]
a=[:width,:height]
animate(99){i.left+=m[0]<=>i.left
i.top+=m[1]<=>i.top}
keypress{|k|d,v={?u=>[1,-1],?d=>[1,1],?l=>[0,-1],?r=>[0,1]}[k[0]];m[d]=[[m[d]+v*4,self.send(p=a[d])-i.send(p)].min,0].max}}

```

This uses a resizable window starting at default 600 x 500. If you resize the window so the invader is left out, will come back when the next movement key is pressed.

The trick to satisfy the requirements is that invader's position is changed in increments of 4, but the actual movement is made with increment of 1 at 99 frames per second.

# Answer
> 2 votes
# Lua + LÖVE, 291 characters

```
x=0
y=0
l=love
g=l.graphics
l.window.setMode(400,400)
i=g.newImage("i")
function l.update()d=l.keyboard.isDown
if d("left")and x>0 then x=x-1 end
if d("right")and x<336 then x=x+1 end
if d("up")and y>0 then y=y-1 end
if d("down")and y<352 then y=y+1 end
end
function l.draw()g.draw(i,x,y)end

```

This uses an unresizable 400 x 400 window. I had no success with adjusting `love.keyboard.setKeyRepeat()` to speed up the key reading, so I did the recommended way, polling each key's status.

As my relation with Lua `for` is not the best, neither this time managed to make looping shorter than the dump hardcoding of each key's condition.

# Answer
> 2 votes
# Tcl/Tk, 242 bytes

```
grid [canvas .c -w 400 -he 403 -bg #FFF -highlightt 0]
.c cr i 30 24 -i [image c photo -fi .png] -t p
lmap {k b x y} "Up 1]>25 0 -5 Right 0]<368 5 0 Down 1]<376 0 5 Left 0]>30 -5 0" {bind . <$k> "if \[lindex \[.c coo p] $b {.c move p $x $y}"}

```

# Answer
> 1 votes
# JavaScript (using paper.js), 215 bytes

```
v=new Raster("https://i.stack.imgur.com/CUweU.png",99,99);p=new Size(4,0)
onFrame=e=>{if(!v.isInside(view.bounds)){p=-p};v.position+=p}
onKeyDown=e=>{p=new Size([[0,-4],[0,4],[-4,0],[4,0]]["udlr".indexOf(e.key[0])])}

```

paper.js is a JS graphics framework, which means it features many useful features regarding image manipulation. To run, just copy the above into the section on the left here, then, to move the alien around, click once in the right section to give it focus. If your browser can handle it, it should run at 60fps.

---
Tags: code-golf, graphical-output, animation
---


title: Output the Goodstein sequence

text:
# Question
Title: Output the Goodstein sequence
(This might be quite classic but this is my first post here, so I'm not ready for the fancy stuff yet)

The Goodstein sequence is defined for an input number as follows:

*Pick a starting number **n**, let **b**=2 and repeat:*

* *write **n** in heriditary base **b** notation*
* *substitute all the (**b**)s to (**b**+1)s in **n** and substract 1*
* *output the new decimal evaluation of **n***
* *increment **b***

Hereditary Base notation is a decomposition of a number where the basis is the bigger number to appear. Examples:

* `83` in HB3: `3^(3+1)+2`
* `226` in HB2: `2^(2^(2+1))+2^(2+1)+2`

Goodstein sequences always end up at 0, but they tend to first get quite big quite fast so it is not asked to output the complete sequence.

---

**Task:**

Given an input number in any reasonable format, your job is to output the Goodstein sequence for this number at least until it reaches 10^25 or 0

**Examples:**

```
Input: 3
Output: 3, 3, 3, 2, 1, 0
Input: 13
Output: 13, 108, 1279, 16092, 280711, 5765998, 134219479, 3486786855, 100000003325, 3138428381103, 106993205384715, 3937376385706415, 155568095557821073, 6568408355712901455, 295147905179352838943, 14063084452067725006646, 708235345355337676376131, 37589973457545958193377292
Input: 38
Output: 38, 22876792454990

```

---

**Details:**

* Input number can be an array, a string, an integer, as long as it is in decimal base
* Output follows the same rule
* Separation of the terms in the output can be spaces, new-lines, or any reasonable separation
* As soon as the sequence becomes larger than 10^25, your program may exit normally, throw an error/exception, or continue (no restriction)
* This is , so the shortest answer (in bytes) wins
* Of course, standard loopholes are forbidden
* Python ungolfed working example here

# Answer
# Pyth, ~~28~~ 26 bytes

```
.V2JbL&bs.e*^hJykb_jbJ=ty

```

The trailing newline is significant.

Try it online! (This link includes an extra `Q` not needed by the current version of Pyth.)

### How it works

```
.V2JbL&bs.e*^hJykb_jbJ=ty
.V2                          for b in [2, 3, 4, ...]:
   Jb                          assign J = b
     L                         def y(b):
      &b                         b and
                   jbJ             convert b to base J
                  _                reverse
         .e                        enumerated map for values b and indices k:
             hJ                      J + 1
            ^  yk                    to the power y(k)
           *     b                   times b
(newline)                      print Q (autoinitialized to the input)
                        y      y(Q)
                       t       subtract 1
                      =        assign back to Q

```

It’s important that `y` is redefined in each loop iteration to prevent memoization across changes to the global variable `J`.
> 3 votes

# Answer
# Haskell, 77 bytes

`(&2)` is an anonymous function taking an `Integer` and returning a (potentially very long) list of `Integer`s, use as `(&2) 13`.

```
(&2)
n&b|n<0=[]|let _?0=0;e?n=(e+1)?div n b+mod n b*(b+1)^0?e=n:(0?n-1)&(b+1)

```

Try it online! (cuts off at `10^25`.)

# How it works

* `(&2)` starts the sequence with base `2`.
* `n&b` calculates the subsequence starting with the number `n` and base `b`.
    + It halts with an empty list if `n<0`, which generally happens the step after `n==0`.
    + Otherwise, it prepends `n` to the list returned recursively by the expression `(0?n-1)&(b+1)`.
* `?` is a local function operator. `0?n` gives the result of converting `n` to hereditary base `b`, then incrementing the base everywhere.
    + The conversion recurses with the variable `e` keeping track of the current exponent. `e?n` converts the number `n*b^e`.
    + The recursion halts with `0` when `n==0`.
    + Otherwise, it divides `n` by the base `b`.
        - `(e+1)?div n b` handles the recursion for the quotient and next higher exponent.
        - `mod n b*(b+1)^0?e` handles the remainder (which is the digit corresponding to the current exponent `e`), the increment of base, and converting the current exponent hereditarily with `0?e`.
> 4 votes

---
Tags: code-golf, sequence
---