title: Tips for golfing in Java

text:
# Question
Title: Tips for golfing in Java
Are there any useful shortcuts that can be used in Java?

As shown below, `import` already adds at least 17 characters to a program.

```
import java.io.*;

```

I understand that the simple solution would be to use another language, but it seems to be a real challenge to shorten Java programs.

---

Tips should be specific to Java: if they're applicable to most C-like languages, they belong in the more general list of tips.

# Answer
* Use the most recent possible java. Java 8 lets you use lambda expressions, so use it if you need anything even *like* functional objects.
* Define shortened functions for things you use a lot. For instance, you have a hundred calls to `exampleClassInstance.doSomething(someParameter)`, define a new function `void d(ParameterType p){exampleClassInstance.doSomething(p)}` and use it to save yourself some characters.
* If you are using a particular long class name more than once, like

```
MyEventHandlerProxyQueueExecutorServiceCollectionAccessManagerFactory

```

instead define a new class:

```
class X extends MyEventHandlerProxyQueueExecutorServiceCollectionAccessManagerFactory{}

```

If you are only using one particular method of that class (but still need to instantiate it), you can define a shortened version inside the new class at the same time.
* Use function type parameters to shorten things, where possible, like this:

```
<T>void p(T o){System.out.println(o);}

```
* Use `for(;;)` instead of `while(true)`.
* Do not use access modifiers unless absolutely necessary.
* Do not use `final` for anything.
* Never put a block after a `for` loop (but a foreach loop `for(x:y)` is different). Additional statements should be placed inside the `for` statement itself, like `for(int i=0;i<m;a(i),b(++i))c(i);`.
* Use inline assignment, incrementation, instantiation. Use anonymous inline classes where appropriate. Use lambdas instead if possible. Nest function calls. Some functions are guaranteed to return their parent object, these ones are actually even *meant* to be chained together.
* Your `main` method `throws Exception`s, not catches them.
* `Error` is shorter than `Exception`. If for some reason you *really* need to `throw` messages up the stack, use an `Error`, even if it is perfectly normal situation.
* If some condition would require immediate termination, use `int a=1/0;` rather than `throw null;` or `System.exit(0);`. At run time, this throws an `ArithmeticException`. If you already have a numeric variable in your code, use it instead. (If you already have `import static java.lang.System.*;`, go with `exit(0);`.)
* Instead of implementing interfaces, like `List<E>`, extend an immediate (or not-so-immediate, if there is any advantage to doing so at all) child class, like `AbstractList<E>`, which provides default implementations of most of the methods, and requires only the implementation of a few key pieces.
* Write your code out in longhand first, with newlines, indentation, and full variable names. Once you have working code, then you can shorten names, move declarations around, and add shortcut methods. By writing it out long to start, you give yourself more opportunity to simplify the program as a whole.
* Compare alternative optimizations to a piece of code, because the most optimal strategy can change dramatically with very small changes to the code. For instance:

+ If you have only up to two calls to `Arrays.sort(a)`, the most efficient way to is to call it with its fully qualified name, `java.util.Arrays.sort(a)`.
    + With three or more calls, it is more efficient to instead add a shortcut method `void s(int[]a){java.util.Arrays.sort(a);}`. This should still use the fully-qualified name in this case. (If you need more than one overload, you are probably doing it wrong.)
    + However, if your code needs to also copy an array at some point (usually done with a short `for` loop in golfing, in the absence of an easily-accessible library method), you can take advantage of `Arrays.copyOf` to do the task. When more than one method is used, and there are 3 or more calls, doing `import static java.util.Arrays.*;` is the most efficient way of referring to those methods. After that, only if you have more than 8 separate calls to `sort` should you be using a shortcut method for it, and only at 5 or more calls is a shortcut warranted for `copyOf`.

The only real way of performing such analysis on code is to actually perform potential modifications on copies of the code, and then compare the results.
* Avoid using `someTypeValue.toString();` method, instead just append `someTypeValue+""`.
* If you do need windows, don't use Swing, use AWT (unless you really need something from Swing). Compare `import javax.swing.*;` and `import java.awt.*;`. Additionally, components in Swing have a `J` prepended to their name (`JFrame`, `JLabel`, etc), but components in AWT don't (`Frame`, `Label`, etc)
> 95 votes

# Answer
**Use `interface` instead of `class`.**

In java 8, static methods were added to interfaces. In interfaces, all methods are public by default. Consequently

```
class A{public static void main(String[]a){}}

```

can now be shortened to

```
interface A{static void main(String[]a){}}

```

which is obviously shorter.

For example, I used this feature in the Hello, World! challenge.
> 58 votes

# Answer
With varargs you can "cast" a parameter to an array of the same type:

```
void f(String...x){
    x=x[0].split("someregex");
    // some code using the array
}

```

instead of

```
void f(String s){
    String[]x=s.split("someregex");
    // some code using the array
}

```
> 41 votes

# Answer
With a **static import**:

```
import static java.lang.System.out;
// even shorter (thanks to Johannes Kuhn):
import static java.lang.System.*;

```

you can save some boilerplate later, but you need multiple invocations to reach a payoff:

```
public static void main (String[] args) {
    out.println ("foo");
    out.println ("bar");
    out.println ("baz");
}

```
> 37 votes

# Answer
The argument to `main` doesn't have to be called `args`, and you can cut some whitespace:

```
public static void main(String[]a){}

```

will do just fine.
> 33 votes

# Answer
If you ever have to use the boolean expressions `true` or `false`, replace them with `1>0` and `1<0` respectively.

For example:

```
boolean found=false;
for(i=0; i<10; i++) if(a[i]==42) found=true;

```

This linear search example can be reduced to

```
boolean f=1<0;
for(i=0;i<10;)if(a[i++]==42)f=1>0;

```
> 30 votes

# Answer
This may seem obvious, but there are shorter options for some `Math` functions:

```
a=Math.max(b,c);
a=b>c?b:c;

a=Math.min(b,c);
a=b<c?b:c;

a=Math.abs(b);
a=b<0?-b:b;
(In certain situations, (a|1)%2*a, may be shorter)

a=Math.round(b);
a=(int)(b+.5);          // watch for precision loss if it matters

```
> 26 votes

# Answer
If you are going to be using some method a lot, assign its resident class to a variable. For example, assign `System.out` to a variable:

```
java.io.PrintStream o=System.out;
//now I can call o.print() or o.println() to the same effect as System.out.println()

```

Also for `Integer.parseInt()`:

```
Integer i=1;
i.parseInt("some string");

```

This will almost surely trigger an ide warning about "accessing static method from variable"
> 25 votes

# Answer
Rather than using the `import static java.lang.System.*` technique to save on `println()` statements, I've found that defining the following method is much more effective at saving characters:

```
static<T>void p(T p){
    System.out.println(p);
}

```

This is because it can be invoked as `p(myString)` rather than `out.println(myString)` which has a much quicker and more dramatic character payoff.
> 24 votes

# Answer
# Some small code-golfing tips

These tips were a bit too small for a separated answers, so I will use this answer for very small codegolfing tips that I found or came up with, and aren't mentioned in the other tips yet:

### Removing the last character of a String:

```
// I used to do something like this:
s.substring(0,s.length()-1)     // 27 bytes

// But this is shorter:
s.replaceAll(".$","")           // 21 bytes

```

In some cases you know what the last character is beforehand, and you also know this character only occurs once in the String. In that case you can use `.split` instead:

```
// As example: "100%" to "100"
s.split("%")[0]                 // 15 bytes

```

### Encoding shortcuts:

```
// When you want to get the UTF-8 bytes I used to do this:
s.getBytes("UTF-8");     // 20 bytes

// But you can also use "UTF8" for the same result:
s.getBytes("UTF8");      // 19 bytes

```

All encodings have a canonical name used in the `java.nio` API, as well as a canonical name used in the `java.io` and `java.lang` APIs. Here is a full list of all supported encodings in Java. So always use the shortest of the two; the second is usually shorter (like `UTF-8` vs `utf8`, `Windows-1252` vs `Cp1252`, etc.), but not always (`UTF-16BE` vs `UnicodeBigUnmarked`).

### Random boolean:

```
// You could do something like this:
new java.util.Random().nextBoolean()     // 36 bytes

// But as mentioned before in @Geobits' answer, Math.random() doesn't require an import:
Math.random()<.5                         // 16 bytes

```

### Primes:

There are a lot of different ways to check for primes or get all primes. @SaraJ's answer here is the shortest for positive integers (\\$\geq1\\$), and *@primo*'s method is the shortest for integers \\$\geq2\\$.

```
// Check if n (≥ 1) is a prime (@SaraJ's method):
n->{int i=1;for(;n%++i%n>0;);return n==i;}

// Check if n (≥ 2) is a prime (@primo's method):
n->{int i=n;for(;n%--i>0;);return i<2;}

```

These prime checks can be modified to loop over primes. Here doing so with *@SaraJ*'s approach for example:

```
v->{for(int n=2,i;;){for(i=1;n%++i%n>0;);if(n++==i)/*do something with prime `i` here*/;}}

```

NOTE: Usually you can merge it with other existing loops depending on how you want to use it, so you won't need a separate method. This saved a lot of bytes in this answer for example.

### Integer truncation instead of Math.floor/Math.ceil:

If you are using ***positive*** doubles/floats and you want to `floor` them, don't use `Math.floor` but use an `(int)`-cast instead (since Java truncates on integers):

```
double d = 54.99;

int n=(int)Math.floor(d);     // 25 bytes

int m=(int)d;                 // 13 bytes

// Outputs 54 for both

```

The same trick can be applied to ***negative*** doubles/floats you want to `ceil` instead:

```
double d = -54.99;

int n=(int)Math.ceil(d);     // 24 bytes

int m=(int)d;                // 13 bytes

// Outputs -54 for both

```

### Use `&1` instead of `%2` to get rid of parenthesis:

Because the Operator Precedence of `&` is lower than default arithmetic operators like `*/+-` and `%`, you can get rid of parenthesis in some cases.

```
// So instead of this:
(i+j)%2     // 7 bytes

// Use this:
i+j&1       // 5 bytes

```

Note that this doesn't really help in boolean-checks, because then you'd still need parenthesis, they're just moved a bit:

```
(i+j)%2<1    // 9 bytes
(i+j&1)<1    // 9 bytes

```

### BigIntegers and creating variables for static method calls:

When using BigIntegers, only create it once which you can then re-use. As you may know, BigInteger contains static fields for `ZERO`, `ONE` and `TEN`. So when you only use those three, you don't need an `import` but can use `java.Math.BigInteger` directly.

```
// So instead of this:
import java.math.BigInteger.*;
BigInteger a=BigInteger.ONE,b=BigInteger.ZERO;                // 76 bytes

// or this:
java.math.BigInteger a=java.math.BigInteger.ONE,b=a.ZERO;     // 57 bytes

// Use this:
java.math.BigInteger t=null,a=t.ONE,b=t.ZERO;                 // 45 bytes

```

NOTE: You have to use `=null` so `t` is initialized in order to use `t.`.

Sometimes you can add multiple BigIntegers to create another to save bytes. So let's say you want to have the BigIntegers `1,10,12` for some reason:

```
// So instead of this:
BigInteger t=null,a=t.ONE,b=t.TEN,c=new BigInteger(12);     // 55 bytes

// Use this:
BigInteger t=null,a=t.ONE,b=t.TEN,c=b.add(a).add(a);        // 52 bytes

```

As correctly pointed out in the comments, the trick with `BigInteger t=null;` for it's static method calls can also be used with other classes.
For example, this answer from 2011 can be golfed:

```
// 173 bytes:
import java.util.*;class g{public static void main(String[]p){String[]a=p[0].split(""),b=p[1].split("");Arrays.sort(a);Arrays.sort(b);System.out.print(Arrays.equals(a,b));}}

// 163 bytes
class g{public static void main(String[]p){java.util.Arrays x=null;String[]a=p[0].split(""),b=p[1].split("");x.sort(a);x.sort(b);System.out.print(x.equals(a,b));}}

```

### `getBytes()` instead of `toCharArray()`

When you want to loop over the characters of a String, you'll usually do this:

```
for(char c:s.toCharArray())    // 27 bytes
// or this:
for(String c:s.split(""))      // 25 bytes

```

Looping over the characters can be useful when printing them, or appending them to a String, or something similar.

However, if you only use the chars for some unicode-number calculations, you can replace the `char` with `int`, AND you can replace `toCharArray()` with `getBytes()`:

```
for(int c:s.getBytes())        // 23 bytes

```

Or even shorter in Java 8+:

```
s.chars().forEach(c->...)      // 22 bytes

```

In Java 10+ looping over the character to print can now also be done in 22 bytes:

```
for(var c:s.split(""))         // 22 bytes

```

### Random item from a `List`:

```
List l=...;

// When we have an `import java.util.*;` in our code, shuffling is shortest:
return l.get(new Random().nextInt(l.size()));     // 45 bytes
return l.get((int)(Math.random()*l.size()));      // 44 bytes
Collections.shuffle(l);return l.get(0);           // 39 bytes

// When we don't have an `import java.util.*` in our code, `Math.random` is shortest:
return l.get(new java.util.Random().nextInt(l.size()));     // 55 bytes
return l.get((int)(Math.random()*l.size()));                // 44 bytes
java.util.Collections.shuffle(l);return l.get(0);           // 49 bytes

```

### Check if a String contains leading/trailing spaces

```
String s=...;

// I used to use a regex like this:
s.matches(" .*|.* ")     // 20 bytes
// But this is shorter:
!s.trim().equals(s)      // 19 bytes
// And this is even shorter due to a nice feature of String#trim:
s!=s.trim()              // 11 bytes

```

Why does this work, when `!=` on Strings is to check for reference instead of value in Java? Because `String#trim` will return "*A copy of this string with leading and trailing white space removed, or **this string if it has no leading or trailing white space**.*" I've used this, after someone suggested this to me, in this answer of mine.

### Palindrome:

To check if a String is a palindrome (keeping in mind both even and odd lengths of Strings), this is the shortest (`.contains` works here because we know both the String itself and its reversed form are of equal length):

```
String s=...;
s.contains(new StringBuffer(s).reverse())    // 41 bytes

```

`.contains(...)` instead of `.equals(...+"")` thanks to *@assylias*'s comment here.

### Either is 0, or both are 0?

I think most already know this one: if you want to check if either `a` or `b` is zero, multiply instead to save bytes:

```
a==0|b==0    // 9 bytes
a*b==0       // 6 bytes

```

And if you want to check if both `a` and `b` are zero, you could use a bitwise-OR, or add them together if they are always positive:

```
a==0&b==0    // 9 bytes
(a|b)==0     // 8 bytes (if either `a`, `b` or both can be negative)
a+b<1        // 5 bytes (this only works if neither `a` nor `b` can be negative)

```

### Even = 1, odd = -1; or vice-versa

```
// even = 1; odd = -1:
n%2<1?1:-1        // 10 bytes
1-n%2*2           // 7 bytes

// even = -1; odd = 1:
n%2<1?-1:1        // 10 bytes
n%2*2-1           // 7 bytes

```

The reason I add this was after seeing `k+(k%2<1?1:-1)` in this answer:

```
k+(k%2<1?1:-1)    // 14 bytes

// This would already have been shorter:
k%2<1?k+1:k-1     // 13 bytes

// But it can also be:
k%2*-2-~k         // 9 bytes

```

### Loop `n` times in Full Program

If we have a challenge where a full program is mandatory, and we need to loop a specific amount of times, we can do the following:

```
// instead of:
interface M{static void main(String[]a){for(int n=50;n-->0;)/*do something*/}}  // 78 bytes
// we could do:
interface M{static void main(String[]a){for(M m:new M[50])/*do something*/}}    // 76 bytes

```

The same applies when we have to take this range as input:

```
interface M{static void main(String[]a){for(int n=new Byte(a[0]);n-->0;)/*do something*/}}  // 90 bytes
interface M{static void main(String[]a){for(M m:new M[new Byte(a[0])])/*do something*/}}    // 88 bytes

```

Credit to *@JackAmmo* in this comment.

### try-finally instead of try-catch(Exception e), and when/how to use it

If you have to catch and ignore an Exception, in most cases it's shorter to use `finally{...;}` instead of `catch(Exception){}`. Some examples:

When you want to return the result as soon as you hit an error:

```
try{...}catch(Exception e){return ...;}    // 33 bytes
try{...}finally{return ...;}               // 22 bytes

```

I've used this initially to save bytes in this answer of mine (credit for the indirect golf goes to *@KamilDrakari*). In this challenge we have to loop diagonally over an NxM matrix, so we have to determine whether the amount of columns or amount of rows is the lowest as our maximum in the for-loop (which is quite expensive in terms of bytes: `i<Math.min(a.length,a[0].length)`). So, simply catching the `ArrayIndexOutOfBoundsException` using `catch-finally` is shorter than this check, and thus saves bytes:

```
int[] a = ...;

int r=0,i=0;for(;i<Math.min(a.length,a[0].length);)r=...i++...;return r;    // 66 bytes

int r=0,i=0;try{for(;;)r=...i++...;}finally{return r;}                      // 48 bytes

```

This also works with a void `return;`, like this:

```
try{...}catch(Exception e){}  // 25 bytes
try{...}finally{return;}      // 21 bytes

```

Which actually saved an additional byte in that same linked answer above by putting the answer in the very first cell, like *@KamilDrakari* does in his C# answer as well:

```
m->{try{for(...);}finally{return;}}

```

But what about a try-catch where you don't want to immediately return? Unfortunately, you can't have a completely empty `finally{}` block as alternative to catch an Exception. You can however still use it inside a loop by using `continue` (or `break`) as alternatives. Here an example where we want to continue with the next iteration of the loop when an Exception occurs:

```
for(...)try{...}catch(Exception e){}  // 30 bytes
for(...)try{...}finally{continue;}    // 28 bytes

```

I've used this approach in this answer of mine to save 2 bytes.

So when you can use a `return`, `continue` or `break`, it's always better to use `try{...}finally{...;}` instead of `try{...}catch(Exception e){}`. And in most cases, especially when checking boundaries of matrices, it's shorter to `try-finally` any `ArrayIndexOutOfBoundsExceptions`, instead of doing manual checks to see whether the indices are still in bounds.

### Math.pow(2,n)

When you want a power of 2, a bit-wise approach is much shorter:

```
(int)Math.pow(2,n)    // 16 bytes
(1<<n)                // 6 bytes

```

### Combining bit-wise and logical checks instead of using parenthesis

I think it is well-known by now that `&` and `|` can be used instead of `&&` and `||` in Java (boolean) logical checks. In some cases you'd still want to use `&&` instead of `&` to prevent errors though, like `index >= 0 && array[index].doSomething`. If the `&&` would be changed to `&` here, it will still evaluate the part where it uses the index in the array, causing an `ArrayIndexOutOfBoundsException`, hence the use of `&&` in this case instead of `&`.

So far the basics of `&&`/`||` vs `&`/`|` in Java.

When you want to check `(A or B) and C`, the shortest might seem to use the bit-wise operators like this:

```
(A|B)&C    // 7 bytes

```

However, because the bit-wise operators have operator precedence over the logical checks, you can combine both to save a byte here:

```
A|B&&C     // 6 bytes

```

### Use `n+=...-n` instead of `(long)...`

When you have a long as both in and output in a lambda, for example when using `Math.pow`, you can save a byte by using `n+=...-n` instead of `(long)...`.
For example:

```
n->(long)Math.pow(10,n)    // 23 bytes
n->n+=Math.pow(10,n)-n     // 22 bytes

```

This saved a byte in this answer of mine, and even two bytes by combining `-n-1` to `+~n` in this answer of mine.
> 22 votes

# Answer
Don't use `public class`. The main method needs to be public, but its class doesn't. This code works:

```
class S{public static void main(String[]a){System.out.println("works");}}

```

You may run `java S` even though `class S` is not a public class. (*Update:* I was using Java 7 when I wrote this tip. In Java 8, your main method should be in an interface. In Java 5 or 6, your main method should be in an enum.)

Plenty of Java programmers don't know this! About half the answers to a Stack Overflow question about main in non-public class wrongly claim that the main method must be in a public class. Now you know better. Delete the `public` in `public class` and save 7 characters.
> 17 votes

# Answer
You don't have to use `Character.toLowerCase(char c)`. Instead use `(c|32)`. Instead of `Character.toUpperCase(char c)` use `(c&95)`. This only works with ASCII letters.
> 17 votes

# Answer
If you need `Integer.MAX_VALUE` (2147483647), use `-1>>>1`. `Integer.MIN_VALUE` (-2147483648) is better written `1<<31`.
> 17 votes

# Answer
If you need to grab *a number* from an argument (or any other string), normally you see something like:

```
public static void main(String[]a){
    int n=Integer.valueOf(a[0]);
    ...
}

```

Many times, you don't *need* an `Integer`. Plenty of challenges don't use large numbers. Since `Short` and `Byte` will both unbox to an `int`, use the more appropriate `valueOf()` instead and save a couple bytes.

Keep your actual *variable* as an `int`, though, since it's shorter than both `byte` and `short`:

```
int n=Byte.valueOf(a[0]);

```

If you need to do this for multiple numbers, you can combine with this method:

```
Byte b=1;
int n=b.valueOf(a[0]),m=b.valueOf(a[1])...

```
> 16 votes

# Answer
# Convert String to number

There are multiple ways to convert a String to an numeric value:

```
String s = "12";

```

*ABC.parseABC*:

```
Short.parseShort(s); // 20 bytes
Integer.parseInt(s); // 20 bytes
Long.parseLong(s);   // 18 bytes

```

*ABC.valueOf*:

```
Short.valueOf(s);    // 17 bytes
Integer.valueOf(s);  // 19 bytes
Long.valueOf(s);     // 16 bytes

```

*ABC.decode*:

```
// Note: does not work for numeric values with leading zeros,
// since these will be converted to octal numbers instead
Short.decode(s);     // 16 bytes
Integer.decode(s);   // 18 bytes
Long.decode(s);      // 15 bytes

```

*new ABC*:

```
new Short(s);        // 13 bytes
new Integer(s);      // 15 bytes
new Long(s);         // 12 bytes

```

So, for code-golfing, it's best to use the constructor when converting a String to a numeric value.

The same applies to `Double`; `Float`; and `Byte`.

---

This doesn't always apply when you can re-use an already present primitive as object.
As example, let's say we have the following code:

```
// NOTE: Pretty bad example, because changing the short to int would probably be shorter..
//       but it's just an example to get the point across

short f(short i,String s){
  short r=new Short(s);  // 21 bytes
  ... // Do something with both shorts
}

```

You can use `.decode` instead of the shorter constructor by re-using the parameter as object:

```
short f(Short i,String s){   // Note the short parameter has changed to Short here
  short r=i.decode(s);   // 20 bytes
  ... // Do something with both shorts
}

```
> 15 votes

# Answer
For golfing that doesn't require input, you can use static blocks, and run it just fine without any main method, just compile it with Java 6.

```
public class StaticExample{
    static {
        //do stuff
    }
}

```
> 13 votes

# Answer
We all know about the bitwise xor (`^`), but it is also a logical xor.

So `(a||b)&&!(a&&b)` simply becomes `a^b`.

Now we can use xor.

Additionally, the operators `|` and `&` also work, just remember that operator precedence changes.
> 13 votes

# Answer
**Don't use `Random`!**

*In general,* if you need random numbers, `Random` is a horrible way to go about it\*. Much better to use `Math.random()` instead. To use `Random`, you need to do this (let's say we need an `int`):

```
import java.util.*;
Random r=new Random();
a=r.nextInt(9);
b=r.nextInt(9);

```

Compare that to:

```
a=(int)(Math.random()*9);
b=(int)(Math.random()*9);

```

and:

```
int r(int m){return(int)(Math.random()*m);}
a=r(9);
b=r(9);

```

The first method takes `41+15n` characters (`n` is number of calls). The second is `25n` characters, and the third is `43+7n`.

So, if you only need it once or twice, use the inline `Math.random()` method. For three or more calls, you'll save by using a function. Either one saves characters on the *first use* over `Random`.

---

If you're already using `Math.random()` for `double`, remember that at four uses, it's still a savings to pull it out into:

```
double r(){return Math.random();}

```

For 33 characters, you'll save 10 on each call to `r()`

---

**Update**

If you need an integer and want to save on casting, *don't cast it!* Java auto-casts if you do an operation instead of an assignment. Compare:

```
a=(int)(Math.random()*9);
a=9;a*=Math.random();

```

<sup>* *Unless you have to seed the PRNG for predictable results. Then, I don't see much of a way around it.*</sup>
> 11 votes

# Answer
# Don't be afraid to use scientific notation

If you are dealing with doubles, or floats, you can use scientific notation for numbers. So instead of writing `double a=1000` you can change it to `double a=1e3` to save 1 byte.
> 11 votes

# Answer
# Try using `int` instead of `boolean`

In some cases I've found that it's shorter to return an integer value from a method that would normally return a boolean, similarly to what might be done in C programs.

Right off the bat `int` is 4 bytes shorter than `boolean`. Each time you write `return 0` instead of `return 1<0`, you save an additional 2 bytes and the same for `return 1` over `return 1>0`.

The pitfall here is that each time you want to use the return value directly as a boolean, it costs 2 bytes (`if(p(n))` v. `if(p(n)>0)`). This can be made up for by use of boolean arithmetic. Given a contrived scenario where you want to write

```
void a(int[]t){t[0]+=p(n)?10:0;}

```

you can instead write

```
void a(int[]t){t[0]+=p(n)*10;}

```

in order to save 2 bytes.
> 10 votes

# Answer
If you use **enum instead of class**, you save one character.

```
enum NoClass {
    F, G, H;
    public static void main (String[] args) {

    }
}

```

But you have to introduce at least one enum instance (F, G, H in this example) which have to payoff themselves.
> 9 votes

# Answer
I don't know if you would consider this 'pure' Java, but Processing allows you to create programs with little initial setup (completed automatically).

For console output, you can have something as simple as:

```
println("hi"); //done

```

for graphical output, a little more:

```
void setup() {
  size(640,480);
}
void draw() {
  fill(255,0,0); //color used to fill shapes
  rect(50,50,25,25); //25x25 pixel square at x=50,y=50
}

```
> 8 votes

# Answer
## Shortening returning

You can shorten return statements of strings by a byte with:

```
return "something";
```

to

```
return"something";
```

And, if you happen to begin your return statement with a parenthesis, you can do the same thing with them:

```
return (1+taxRate)*value;
```

to

```
return(1+taxRate)*value;
```

I guess quotes are considered like parentheticals? I actually picked this up through AppleScript, funnily enough, and thought it might be worth mentioning.
> 8 votes

# Answer
# Use Java 10's `var`

If you define a single variable of a specific type, use `var`.

### Examples

```
var i=0;                        // int
var l=0L;                       // long
var s="";                       // String
var a=new int[]{1,2,3};         // int[]
var i=java.math.BigInteger.ONE; // BigInteger
var m=new java.util.HashMap();  // HashMap
var i=3+"abc".length()          // int
var a="a b c".split(" ");       // String[]
for(var a:"a b c".split(" "))   // String

```

### Not usable in any of the following examples

`var` cannot be used in many examples

```
var i=1,j=2;           // only one variable is accepted at a time
var a={1,2,3};         // arrays must be explicitly declared
var f=a->a+" ";        // can't know what type a is.
var f=String::replace; // method references aren't properly inferred (weirdly, though)

```
> 8 votes

# Answer
# Avoid `StringBuilder`s

Appending stuff to a `String` takes up much fewer bytes.

```
// s is a StringBuilder
s.append("Hello, World!");

// S is a String
S+="Hello, World!";

```

If you have to reverse a string and print it right away, use a `StringBuffer`.

```
System.out.print(new StringBuilder("Hello, World!").reverse());
System.out.print(new StringBuffer("Hello, World!").reverse()); // Note that you can omit toString() when printing a non-String object

```

If you have to reverse a string and then do something else than printing it, use a `for`each loop.

```
String b=new StringBuffer("Hello, World!").reverse().toString();
String B="";for(String c:"Hello, World!".split(""))B=c+B;

```
> 7 votes

# Answer
# Use `new Stack()` when you need basic `List` functionality

When you need a `java.util.List` (for example when you want to `.add(Object)`, `.remove(Object)`, `java.util.Collections.shuffle(java.util.Collection)`, etc.), I used to use `java.util.ArrayList` in most of my answers. But I was recently tipped to use `java.util.Vector` instead, and `java.util.Stack` is even shorter:

```
import java.util.*;

List a=new ArrayList();   // 23 bytes
List b=new Vector();      // 20 bytes
List c=new Stack();       // 19 bytes

```
> 7 votes

# Answer
# Shortest full program templates.

### Introduction

The Java spec never ever say that a full program must contain a `main` method. It only says:

> The Java Virtual Machine starts execution by invoking the method main of some specified class, passing it a single argument, which is an array of strings.

So to the best of our efforts, we can define a Java program as something which when invoked in this way will provide an output:

```
$ javac A.java
$ java A

```

All the following templates do that.

### Java 8 (42 bytes)

```
interface A{static void main(String[]a){/* Your code here */}}

```

### Java 7 (45 bytes)

```
class A{public static void main(String[]a){/* Your code here */}}

```

### Java 5, 6 (12 or 27 bytes)

```
enum A{A;{/* Your code here */}}

```

This code above **will** write something on `stderr`. Usually something like `java.lang.NoSuchMethodError: main\nException in thread "main"`. If you can write on `stderr` after execution, use this!

```
enum A{A;{/* Your code here */System.exit(0);}}

```

This code above is longer (27 bytes), but it **will** execute your code **and** avoid writing anything on `stderr`.

### Conclusion

1. Don't ever use Java 7.
2. If your program can be written in Java 5 or 6, use it. If your program can be written in Java 5 or 6, but is longer than a Java 8 version, always check if it could be shorter to write it in Java 5 or 6.
> 7 votes

# Answer
Using Java Applet can save you a lot of space:

```
import java.applet.Applet;

public class B extends Applet{
    public B(){
        System.out.print("Hello world!");
    }
}

```

**Output:**

> Hello world!

Also this can be even more shorten by making `B` to extends nothing.

```
public class B{
    public B(){
        System.out.print("Hello world!");
    }
}

```

How ever in additional to desired output we will also get exception:

**Output:**

> Hello world!
> java.lang.ClassCastException: B cannot be cast to java.applet.Applet
> at sun.applet.AppletPanel.createApplet(Unknown Source)
> at sun.applet.AppletPanel.runLoader(Unknown Source)
> at sun.applet.AppletPanel.run(Unknown Source)
> at java.lang.Thread.run(Unknown Source)

Also you can combine this with constructor block and save another 10 bytes like this:

```
public class B{
    {
        System.out.println("Hello world!");
    }
}

```

Same output with exception as above.
> 6 votes

# Answer
When you have a method that should return a `boolean` or `Boolean`, i.e.:

```
// Return true if the (non-negative) input is dividable by 5
boolean c(int i){return i%5<1;}

```

You can change the `boolean`/`Boolean` return-type to `Object` to save 1 byte:

```
Object c(int i){return i%5<1;}

```

---

In addition, as you may have noticed, you can use a `<1` check instead of `==0` to save a byte. Although that is more a general code-golf tip instead of Java-specific.
This is mostly used when the integer can't be negative, like checking for length:

```
a.length<1

```

instead of

```
a.length==0

```
> 6 votes

# Answer
# How to Draw in Java...

Here's the shortest possible GUI paint boiler-plate:

```
import java.awt.*;
static void main(String[]x){
    new Frame(){
        public void paint(Graphics g){
            // Draw your stuff here.
        }
    }.show();
}

```

# Golfed for 111 Bytes:

```
import java.awt.*;static void main(String[]x){new Frame(){public void paint(Graphics g){/*CodeHere*/}}.show();}

```
> 6 votes

# Answer
In most cases, your program will be single-threaded, i.e it'll have only one thread running. You can exploit this fact by `return`ing from the main method when you have to exit instantly.

```
static void main(String[]a){if(condition)return;}

```

Compare it to "properly" terminating the program:

```
static void main(String[]a){if(condition)System.exit(0);}

```

Or pointing to `null`:

```
static void main(String[]a){if(condition)throw null;}

```

Or dividing by 0:

```
static void main(String[]a){if(condition)int A=1/0;}

```
> 5 votes

# Answer
# Using `...` (varags) as parameter

In some cases it's shorter to use a Java varargs as parameter instead of loose ones.
For example:

```
// Example input/output: 5, 4, 3 -> 60000
int calculateVolumeInLiters(int width, int height, int depth){
  return width * height * depth * 1000;
}

```

Would be golfed by most to this:

```
int c(int w,int h,int d){return w*h*d*1000;} // 44 bytes

```

But can be golfed an additional byte to this:

```
int c(int...a){return a[0]*a[1]*a[2]*1000;}  // 43 bytes

```

Note that all three integers are only accessed once in the method itself. Since `int` is pretty short it is only beneficial if you use them each only once inside the method, and have three or more of them as parameter.

With longer parameters this is usually more useful though. For example, this was my original answer for this challenge (calculate occurances of input character in input string):

```
// Example input/output: tttggloyoi, t -> 3

int c(String a,char b){return a.replaceAll("[^"+b+"]","").length();} // 68 bytes

```

And I was recommended to golf it to this:

```
int c(String a,char b){return a.split(b+"").length-1;}               // 54 bytes

```

But I ended up golfing it to this using `...`:

```
int c(String...a){return a[0].split(a[1]).length-1;}                 // 52 bytes

```

---

NOTE: If the question/challenge asks for a flexible input, the `...` can be shortened to `[]` of course. If the question/challenge specifically asks for, let's say, three `String` inputs and disallows an `String`-array containing three values, you can use `String...` instead of `String a,String b,String c`.
> 5 votes

# Answer
Sometimes, a single for-loop statement might be replaceable. Consider the following code:

```
int m(int x){int i=1;for(;x%++i==0;);return i;}

```

This is a simple for-loop which is a solution to this question.

Since we know that `i` will not be large enough to cause StackOverflow errors, we can replace the for-loop with recursion instead:

```
int m(int x,int i){return x%++i>0?i:m(x,i);}

```

We can simulate a loop by using a ternary operator in the return statement to cause recursion.

This reduction is rather specific, but I can imagine more situations where this would come in handy.
> 5 votes

# Answer
If you use Java 8, then you can:

## Replace Lambda expressions with method references

Lambda expressions can be replaced with method references. Method reference has following form:

```
ClassName::methodName

```

so if you use one letter names for classes it's shorter then lambda. Here are the rules

```
lambda form                  |  reference method form
-------------------------------------------------------------------------------------------------
p -> ClassName.methodName(p) |  ClassName::methodName
p -> new ClassName(p)        |  ClassName::new
p -> p.methodName()          |  ClassName::methodName // where ClassName is class of object p
(p, q) -> p.methodName(q)    |  ClassName::methodName // where ClassName is class of object p

```

Examples (respectivly):

```
lambda                       |  reference method
-------------------------------------------------------------------------------------------------
p -> System.out.println(p)   |  System.out::println
p -> new HashSet<>(p)        |  HashSet::new
p -> p.getName()             |  Beer::getName
(p, q) -> p.compareTo(q)     |  String::compareTo

```

So, if ClassName is "C", then we have following length diffs:

```
lambda form                  |  reference method form | length diff
-----------------------------------------------------------------------
p->C.methodName(p)           |  C::methodName         | 5 bytes
p->new C(p)                  |  C::new                | 5 bytes
p->p.methodName()            |  C::methodName         | 4 bytes
(p,q)->p.methodName(q)       |  C::methodName         | 9 bytes

```

## Simplify lambda expressions

And here are some rules of simplifying lambda expressions.

General form of lambda expression is

```
(parameters) -> { statements;}  // (String a, String b) -> {return a.compareTo(b);}

```

When there is only one expresion, it can be simplified as follows (**`return` should me ommitted**):

```
(parameters) -> expression      // (String a, String b) -> a.compareTo(b)

```

When **type declaration can be ommited**, it can be simplified as follows:

```
(parameters) -> expression      // (a, b) -> a.compareTo(b)

```

When there is only one parameter and there is **no need to declare type**, it can be simplified as follows:

```
parameter -> expression         // (String s) -> System.out.printout(s)
                                // to
                                // s -> System.out.println(s)

```
> 5 votes

# Answer
# Use `String#isEmpty()`

To check if a String is empty, you could use either of these:

```
s.length()<1  // 12 bytes
s.equals("")  // 12 bytes

```

However, using `.isEmpty()` is one byte shorter:

```
s.isEmpty()   // 11 bytes

```

---

Note that for Lists it's still shorter to check the size instead of using `isEmpty()`:

```
l.size()<1    // 10 bytes
l.isEmpty()   // 11 bytes

```
> 3 votes

# Answer
# Bit twiddling actions

## Swap variables

You might want to swap `int` and `long` variables. The usual way is to have a temporary variable:

```
void swap(int a, int b) {
  int t=a;a=b;b=t;     //  16 bytes
  System.out.printf("a=%d, b=%d%n", a, b);
}

```

But you can shorten it like this:

```
void swap(int a, int b) {
  a^=b^(b=a);          // 11 bytes
  System.out.printf("a=%d, b=%d%n", a, b);
}

```

Even if you reuse a temporary variable, it's just shorter to write that code, no matter the length of each variable name.

Does work with `short` and `byte` but at the cost of casting.

## Swap the variables so that the min is in a specific variable and the max is in the other

You have `a` and `b` and you don't know which is greater. But you want `a` to contain the lowest and `b` to contain the greatest.

```
void swapMinMax(int a, int b) {
  a^=b<a?b^(b=a):0;            // 17 bytes
  System.out.printf("a=%d, b=%d%n", a, b);
}

```
> 3 votes

# Answer
Sometimes, you can use lambdas with iterators:

```
// SUBOPTIMAL: Don't use lambdas here!
Iterator<A>i=a.iterator();for(A x:(Iterable<A>)()->i){if(x==y)break;}return i.hasNext()?i.next():null;
Iterator<A>i=a.iterator();for(;i.hasNext();){if(i.next()==y)break;}return i.hasNext()?i.next():null;
Iterator<A>i=a.iterator();while(i.hasNext()){if(i.next()==y)break;}return i.hasNext()?i.next():null;

// Lambdas save 11 bytes here!
Iterator<A>i=a.iterator();Iterable<A>j=()->i;for(A x:j){if(x==y)break;}for(A x:j){if(x==z)break;}return i.hasNext()?i.next():null;
Iterator<A>i=a.iterator();for(;i.hasNext();){if(i.next()==y)break;}for(;i.hasNext();){if(i.next()==z)break;}return i.hasNext()?i.next():null;
Iterator<A>i=a.iterator();while(i.hasNext()){if(i.next()==y)break;}while(i.hasNext()){if(i.next()==z)break;}return i.hasNext()?i.next():null;

```
> 1 votes

# Answer
# Use *Try it online* to share lambdas

If the solution can be writen in a lambda, Try it online can help you format and reduce what characters need to be included in the solution.

See this for an example.
> 1 votes

# Answer
## Convert number to string

It may seem obvious, you can shorten your code by adding the number to "":

```
// int a = 123
Integer.toString(a) // 0
String.valueOf(a)   // -2 chars
"".valueOf(a)       // -6 chars
(""+a)              // -13 chars

```
> 0 votes

---
Tags: code-golf, tips, java
---


# Question
Title: Write a continuous quine (quine-variant)
> Let's define a 2-quine as a program that prints its source code two times. For example, if the program `ABC` printed `ABCABC`, it would be a 2-quine.
>
> Let's define a 3-quine as a program that prints its source code three times. For example, if the program `ABC` printed `ABCABCABC`, it would be a 3-quine.
>
> Let's define a *n*-quine as a program that prints its source code *n* times.

Your task is to write a 2-quine, that prints a 3-quine, that prints a 4-quine, that prints a 5-quine, etc...

For example, here is an example of a valid submission (which is fictional of course):

```
AB

```

which prints

```
ABAB

```

which prints

```
ABABABABABAB

```

which prints

```
ABABABABABABABABABABABABABABABABABABABABABABABAB

```

etc.

Remember, this is , so the program with the fewest bytes wins.

# Answer
## QBasic (224 bytes incl. trailing CR+LF)

(Tested with QBasic/MS-DOS on a virtual machine as well as with FreeBASIC with "-lang qb" setting)

```
a$="a$=:l=l+1:if l>y then f=f+1:y=y*f+y+f:while x<=y:x=x+1:print mid$(a$,1,3)+chr$(34)+a$+chr$(34)+mid$(a$,4):wend":l=l+1:if l>y then f=f+1:y=y*f+y+f:while x<=y:x=x+1:print mid$(a$,1,3)+chr$(34)+a$+chr$(34)+mid$(a$,4):wend

```
> 3 votes

# Answer
# Javascript ES6 (REPL), 52 bytes

```
var a=a||'';$=_=>a+=`$=${$};$();`.repeat(a?1:2);$();

```

Initial working implementation, may be golfable.

```
y.onclick=_=>z.innerText=eval("var a=a||'';$=_=>a+=`$=${$};$();`.repeat(a?1:2);$();".repeat(x.value))
```

```
<input id=x><button id=y>Submit!</button><pre id=z></pre>
```

# Explanation

Based on my usual quine implementation (`$=_=>`$=${$};$()`;$()`).

`var a||''` coerces `a` to an empty string if it isn't defined; otherwise, `a` is left as is. `a` will store our final result.

Each function call, `a` will be checked to see if it is empty/falsy. The first function call will append 2 copies of the quine because `a` is empty; subsequent calls will only append 1 copy because `a` is no longer empty.

The last function call will output the final value of `a` after finishing.
> 1 votes

# Answer
# Ruby, 154 bytes

```
s=DATA.read.lines;s+=s[0,2];n=s.size/4;k=1;n/=k+=1while n>0;puts s*k
__END__
s=DATA.read.lines;s+=s[0,2];n=s.size/4;k=1;n/=k+=1while n>0;puts s*k
__END__

```

The trailing newline matters.

This program first duplicates itself; the output triplicates itself; that output quadruplicates itself, etc.

Thus the **n**-th program is a repetition of these 4 lines, **n!** times.

`s=DATA.read.lines;s+=s[0,2];` gets us the current source code as an array of lines. We take its length, divide it by 4, compute the inverse factorial, add one, then print `s` that many times.
> 1 votes

# Answer
# Python 3.8 (pre-release), 117 bytes

```
for x in 1,0:
 exec(s:="if x%2:a=1;d={}\nx or~input('for x in 1,0:\\n exec(s:=%r)#'%s*~-a*d[a-1]);a+=1;d[x]=a;x*=a")#

```

Try it online!

## How it works :

* `for x in 1,0:` allows me to iterate through the code twice
* then I execute some code
* `#` at the end comment the `for x in 1,0:` if the "base" is repeated multiple times

the code executed :

```
if x%2: # execute if x=1 (happen only once at the start,
        # after that x will always be a multiple of 2)
    a=1
    d={}

# if x==0: print the quine the right number of time then crash
x or~input('for x in 1,0:\\n exec(s:=%r)#'%s*~-a*d[a-1])

a+=1   # a increments itelf by one for each line of the code
d[x]=a # store (a-1)! and a
x*=a   # x = a!

```

If the actual code is a `n` quine, it has `(n-1)!` times the "base" and should print it `n!` times:

* Because `a` is incremented by 1 each line, after the first iteration of the `for` loop, a is equal to `(n-1)!+1`.
* I then search `a-1` into `d` (wich store relation beetween `(k-1)!` and `k`) to find `n`.
* I multiply `n` by `a-1` to get `n!`
* I print this number times the "base"
> 0 votes

---
Tags: code-golf, quine
---


title: Calculate a User's Reputation

text:
# Question
Title: Calculate a User's Reputation
# Challenge

Given a user's **name** (not ID, we have that challenge already), output their current reputation and their ID.

### Input

Input will be a single string which is the user's username. You may assume that this user exists.

### Output

Output will be two integers to either STDOUT or STDERR which will be the user's reputation and the user's ID. They must be in that specific order and can be output in any reasonable format

### Specifics

* The reputation output must not be more than 10 minutes out of date.
* Your program may not throw any errors during normal execution
* Standard loopholes apply (including No URL Shorteners)
* If there is more than one user with that username, you may output the stats of any user with that username. This is also why you must output the ID.
* The reputation to be output is the reputation of the user on PPCG, not the network total score.

The Stack Exchange API site can be found here. You can read the documentation from there.

# Answer
> 1 votes
# Bash + JQ, 93 bytes

Rolled back the 87 byte version, as it was not handling multi-user responses correctly.

**Golfed**

```
curl "api.stackexchange.com/users?site=codegolf&inname=$1"|zcat|jq ..\|numbers|sed -n 4p\;12p

```

Will output first user id and reputation on the separate lines.

**How It Works ?**

1)`curl + zcat` are used to fetch the JSON formatted API reply

2) `jq ..|numbers` will unfold JSON recursively, and print all the numeric values, one per line

```
...
1   35
2   8
3   2
4   3315904
5   1487694154
6   1492702469
7   4565
8   82
9   82
10  60
11  20
12  6275
...

```

(line numbers were added with `nl` for illustration purposes only)

3) Next we use `sed` to lookup the first `account_id` and `reputation`, by their absolute row numbers

**Test**

```
>./reputation zeppelin
3315904
6275

```

# Answer
> 6 votes
# JavaScript (ES6), 145 139 136 125 123 117 bytes

```
a=>fetch(`//api.stackexchange.com/users?site=codegolf&filter=!)LgZAmQ6ls0hH&inname=`+a).then(_=>_.text()).then(alert)

```

Saved 6 bytes thanks to Shaggy and 6 bytes thanks to Cyoce.

I'm not sure if it should output all users with the same name, or just one of them; this code outputs all of them.

```
f=a=>fetch(`//api.stackexchange.com/users?site=codegolf&filter=!)LgZAmQ6ls0hH&inname=`+a).then(_=>_.text()).then(alert)

f("tom")
```

# Answer
> 4 votes
# Python 2, ~~178~~ ~~169~~ 149 Bytes

I'd use requests for this:

```
from requests import*
a=get("http://api.stackexchange.com/users?site=codegolf&inname="+input()).json()["items"][0]
print a["reputation"],a["user_id"]

```

Basically, it uses stack's api to fetch the information as JSON and then gets the item "reputation". Additionally, the API featured many extra parameters, I shaved those off as well.

Generous contributions from: carusocomputing, ElPedro, Malivil, Keerthana Prabhakaran

# Answer
> 4 votes
# Groovy, ~~144~~ 156 bytes

```
{new groovy.json.JsonSlurper().parse(new URL("http://api.stackexchange.com/2.2/users/?site=codegolf&inname=$it")).items.collect{[it.user_id,it.reputation]}}

```

Anonymous closure.

EDIT: forgot to use import of `groovy.json.` for JSON Slurper + 14 bytes.

**Example output `[[UserID, Reputation],...]`:**

```
[[20260, 60695], [20469, 21465], [3103, 8856], [41805, 7783], [134, 6829], [42643, 5622], [45268, 4389], [10732, 3976], [32, 3635], [53745, 3392], [10801, 3216], [49362, 2418], [2104, 2160], [3563, 1988], [18280, 1491], [742, 1466], [59487, 1362], [19039, 1330], [56642, 1133], [9522, 951], [34438, 886], [1744, 793], [52661, 778], [18187, 768], [11426, 751], [26850, 711], [178, 637], [29451, 631], [19700, 616], [15862, 601]]

```

# Answer
> 1 votes
# Swift, ~~225~~ 201 bytes

```
import Foundation;var f:(String)->Any={return try!JSONSerialization.jsonObject(with:Data(contentsOf:URL(string:"http://api.stackexchange.com/users?site=codegolf&filter=!)LgZAmQ6ls0hH&inname=\($0)")!))}

```

Un-golfed:

```
import Foundation

var f:(String) -> [String: Any] = {
    return try! JSONSerialization.jsonObject(with:Data(contentsOf:URL(string:"http://api.stackexchange.com/users?site=codegolf&filter=!)LgZAmQ6ls0hH&inname=\($0)")!)) as! [String:Any]
}

```

Example output:

```
["items": <__NSArrayI 0x6180001ffc00>(
{
    reputation = 2820;
    "user_id" = 42295;
},
{
    reputation = 2468;
    "user_id" = 31203;
},
{
    reputation = 2106;
    "user_id" = 2800;
},
{
    reputation = 1479;
    "user_id" = 6689;
},
{
    reputation = 1287;
    "user_id" = 64424;
},
{
    reputation = 1037;
    "user_id" = 64070;
},
{
    reputation = 644;
    "user_id" = 25193;
},
{
    reputation = 641;
    "user_id" = 3171;
},
{
    reputation = 639;
    "user_id" = 743;
},
{
    reputation = 590;
    "user_id" = 33233;
},
{
    reputation = 571;
    "user_id" = 26993;
},
{
    reputation = 563;
    "user_id" = 1730;
},
{
    reputation = 321;
    "user_id" = 18570;
},
{
    reputation = 309;
    "user_id" = 39156;
},
{
    reputation = 291;
    "user_id" = 7880;
},
{
    reputation = 281;
    "user_id" = 25190;
},
{
    reputation = 261;
    "user_id" = 40820;
},
{
    reputation = 231;
    "user_id" = 14154;
},
{
    reputation = 206;
    "user_id" = 2774;
},
{
    reputation = 196;
    "user_id" = 48231;
},
{
    reputation = 181;
    "user_id" = 1230;
},
{
    reputation = 176;
    "user_id" = 64077;
},
{
    reputation = 171;
    "user_id" = 31365;
},
{
    reputation = 171;
    "user_id" = 43455;
},
{
    reputation = 163;
    "user_id" = 21469;
},
{
    reputation = 161;
    "user_id" = 11845;
},
{
    reputation = 157;
    "user_id" = 25181;
},
{
    reputation = 131;
    "user_id" = 263;
},
{
    reputation = 131;
    "user_id" = 3922;
},
{
    reputation = 128;
    "user_id" = 67227;
}
)
]

```

# Answer
> 1 votes
# 05AB1E, 58 bytes

```
’¸¸.Â‚‹º.ŒŒ/†š?€¼=ƒËŠˆ&€†‚ˆ=ÿ’.wD„n"¡1è¦',¡н,'‡¾¡2è¦¦',¡н,

```

Beats all other answers.

```
’...’.wD„n"¡1è¦',¡н,'‡¾¡2è¦¦',¡н,  # trimmed program
                   ,               # output...
                  н                # first element of...
             è                     # element at 0-based index...
            1                      # literal...
             è                     # in...
     .wD                           # content of response to request to URL...
                                   # (implicit) "http://" concatenated with...
’...’                              # "api.stackexchange.com/users?site=codegolf&inname=ÿ"...
                                   # (implicit) with ÿ replaced by...
                                   # implicit input...
           ¡                       # split by...
        „n"                        # literal
              ¦                    # excluding the first character...
                 ¡                 # split by...
               ',                  # literal
                                ,  # output...
                               н   # first element of...
                         è         # element at 0-based index...
                        2          # literal...
                         è         # in...
     .w                            # content of response to request to URL...
                                   # (implicit) "http://" concatenated with...
’...’                              # "api.stackexchange.com/users?site=codegolf&inname=ÿ"...
                                   # (implicit) with ÿ replaced by...
                                   # implicit input...
                       ¡           # split by...
                    '‡¾            # "id"...
                          ¦        # excluding the first character...
                           ¦       # excluding the first character...
                              ¡    # split by...
                            ',     # literal

```

---
Tags: code-golf, stack-exchange-api
---


title: Who's Who in the Name-Change Game?

text:
# Question
Title: Who's Who in the Name-Change Game?
Very recently, I changed my SE username because I made this account some years ago and wanted to get back into asking questions. However, I’m still planning to post questions and potentially earn votes. We can imagine a site that has some issues dealing with name changes. The problem: given a list of names, reputation changes, and name changes, can you create a leaderboard of reputation? **Assume everyone's reputation starts at 0.**

Input comes in any reasonable format, and has two forms: a *name change* `<String, String>` and a *rep change* `<String, Number>`.

What does *any reasonable format* mean? When I write questions, it usually means the input can be rearranged or repackaged to work with the way your language takes in input (do you want a list of pairs? two lists? a string? that’s all fine) as long as it doesn’t add information or otherwise offload some of the computational work onto the human.

Name changes change a person’s username to any username *not currently in use.* For example, if A changes name to D, and B changes name to C, D (previously known as A) could still change their name to A or to B, even though these names have been used before. However, at any given moment the set of names are unique.

Rep changes represent something like getting up/down votes on a post, receiving a bounty, etc. All rep changes are guaranteed to be integers. They might come in the form \<“Bob”, 5\> or \<“Alice”, -53000\>. At the end, you must output all usernames that are currently in existence, and their rep counts, in descending order.

Test case:

```
Alice 5
Bob 7
Bob John
John 113
Alice Cheryl
Daniel 13
John Alice
Alice 12

```

Result:

```
Alice 132
Daniel 13
Cheryl 5

```

Test case, suggested by Unrelated String:

```
Jimmy Adam
Donald 12
Amelia -11

```

Result:

```
Donald 12
Adam 0
Amelia -11

```

Test case:

```
CodegoLfer65 12
Bluman 9
CodegoLfer65 n4me
n4me -3

```

Result:

```
Bluman 9
n4me 9 (note: these two can be in either order)

```

Usernames are composed of only \[A-Za-z0-9\], i.e. alphanumerics. However, the input will not be a number in your language. This means usernames like `144`, `015`, `0x0F`, `1e7` will not appear in the input. Numbers such as `1/3`, `2.8` do not appear due to the character specification in the first place.

This question seems heavy on data structures, so golfing languages may not perform as well. Maybe other languages will have a fighting chance? Scoring is by lowest number of bytes, i.e. tag:code-golf .

# Answer
> 7 votes
# Python 3, 115 bytes

```
def f(l):
 r={}
 for n,m in l:q=m*0!=0;r[[n,m][q]]=r.pop(n,0)+[m,0][q]
 return sorted(r.items(),key=lambda i:-i[1])

```

Try it online!

# Answer
> 5 votes
# Ruby, ~~102~~ ~~101~~ ~~95~~ ~~94~~ ~~93~~ 90 bytes

```
->c{l={};c.map{|a,b|x=l[a]||0;b*0!=0?(l[b],l[a]=x,p):l[a]=x+b};l.compact.sort_by{|a,b|-b}}

```

This takes input in the form of a list of `["name", "new_name"/score]` pairs. And it outputs in an ordered list of `["name", score]`

Golfy Tricks

* I used `p` with no args to get a `nil` value.
* ~~I used `String===b` instead of `b.is_a?String`~~
* ~~I used ~~`b!=b.ord`~~ `b.ord!=b` to find out if it's a string or not. See `String.ord` and `Integer.ord`~~
* I'm using `b*0!=b` to check if it's a string or not.
* For some reason, `b.ord!=b` means that I don't need a space between the `?` ternary operator and the following `(`, but if I swap it to `b!=b.ord`, then another whitespace is needed.
* I sorted by `-b`, rather than by `b` and then reversing (d'oh!)

## Try it online!

Edit: Thanks to Veskah, for pointing out some problems this solution was missing. Somehow adding a temporary variable to hold `l[a]||0` has shortened the code by a byte.

Edit: Thanks to G B, for suggesting `b*0!=0` instead of `b.ord!=b`, which also allowed me to get rid of the space before the `?`, saving 3 characters.

# Answer
> 3 votes
# PHP, 111 bytes

```
for(;$n=$argv[++$i];+$r&&$a[$n]+=$r)if(!+($r=$argv[++$i])&&$a[$r]=+$a[$n])unset($a[$n]);arsort($a);print_r($a);

```

Try it online!

Inputs are command arguments (`$argv`) as a plain list like: `Alice`, `5`, `Bob`, `7`. Every item is a separate argument.

### Commented

```
for(;
  $n=$argv[++$i];    // $n is set to the first parameter (name) for each event
  +$r&&$a[$n]+=$r)   // at the end of each iteration if $r is a number
                     //   add it to reputation of $n
  if(
    !+(
      $r=$argv[++$i] // $r is set to the second event parameter (name or reputation change)
    )&&
    $a[$r]=+$a[$n])  // if $r is a name, transfer reputation of $n to $r
      unset($a[$n]); //   and remove $n from $a
arsort($a);          // after the loop, sort $a by its values in descending order
print_r($a);         // print $a as string

```

---

# PHP, 98 bytes

This one shows non-existing users too (at the end of the list), but shows nothing as their reputation.

```
for(;$n=$argv[++$i];arsort($a))+($r=$argv[++$i])?$a[$n]+=$r:[$a[$r],$a[$n]]=[+$a[$n]];print_r($a);

```

Try it online!

# Answer
> 3 votes
# K (ngn/k), 65 bytes

```
{(>x)!x@>x}(0#`!0){(n;a):y;$[`i~@a;@[x;n;+;a];@[x;a;:;0^x@n]_n]}/

```

Try it online!

Input is taken as a list of pairs; user names are symbols (rather than strings).

* `(0#`!0){...}/` set up a reduce, seeded with an empty dictionary (mapping symbols to integers) that tracks the active usernames and their respective reputation scores
* `{(n;a):y;...}` destructure the next pair into its `n`ame and `a`ction
* `$[`i~@a;...;...]` check whether or not the `a`ction is an integer (representing a reputation change) or not
* if the action was a reputation adjustment...
    + `@[x;n;+;a]` add the reputation change to that user (if this is the first time the username appears, use `0` as the fill element)
* if the action was a username change...
    + `@[x;a;:;0^x@n]` carry over the reputation from the previous name to the new name (if the prior name didn't have any reputation or name changes yet, set its reputation to 0)
    + `..._n` delete the old user name from our reputation tracker
* once done handling the reputation/name changes...
    + `{(>x)!x@>x}` sort the users by their reputation, descending (outputting both the username and their "final" reputation)

# Answer
> 2 votes
# Pip `-rS`, ~~71~~ 53 bytes

```
{IaNI@ZllPB[a0](lY@Zl@?a1)+:bI+bNEb(ly0):b}MUg^sRVSNl

```

Try it online!

I'm gonna golf this some more before writing a thorough explanation. The basic idea:

* Keep a list of \[name score\] pairs in `l`
* Loop through the lines of input, split on spaces, using `MU` (for each line, the first item is `a` and the second item is `b`):
    + If `a` is not one of the names in `l`, append `[a 0]` to `l`
    + Add `b` to the score in `l` associated with the name `a` (if `b` is a name, this adds 0\*)
    + If `b` is not a number, change the name `a` in `l` to `b`
* Once the loop is done, sort `l` in descending numerical order (since all the names are 0 in numeric context\*, this sorts by the scores)

<sup>* Assuming that no names start with a digit, which I argue is the best Pip-specific interpretation of "whatever the input is, it won't be able to be parsed as a number."</sup>

# Answer
> 1 votes
# JavaScript (Node.js), 118 bytes

```
a=>a.flatMap(v=>([p,q]=v,u=a[p])?(q+-q?a[a[u[0]=q]=u,p]=0:u[1]+=q,[]):[q+-q?a[q]=[q,0]:a[p]=v]).sort((a,b)=>b[1]-a[1])

```

Try it online!

Expect input `([string, string]|[string, number])[]` type.

`q+-q` is used to test whether `q` is a number or string. if `q` is number, `q+-q` will be falsy. If `q` is string, `q+-q` will be truthy.

# Answer
> 1 votes
# Haskell, 253 bytes

```
import Text.Read
import Data.List
m l(k,d)=maybe((d,o):n)(\a->(k,a+o):n)(readMaybe d)where o=maybe 0id(lookup k l);n=filter(\(x,_)->x/=k)l
f v=sortBy(\(_,x)(_,y)->compare y x)$filter(\(x,y)->maybe("",0)id(find(\(a,_)->a==x)r)==(x,y))r where r=foldl m[]v

```

The function takes a list of String pairs and returns a list of `(String, Int)` pairs

## Full programme, **355 bytes**

```
module Main where
import Text.Read
import Data.List
m l[k,d]=maybe((d,o):n)(\a->(k,a+o):n)(readMaybe d)where o=maybe 0id(lookup k l);n=filter(\(x,_)->x/=k)l
main=getContents>>= \c->let r=foldl m[]$map words$lines c in putStr$unlines$map(\(x,y)->unwords[x,show y])$sortBy(\(_,x)(_,y)->compare y x)$filter(\(x,y)->maybe("",0)id(find(\(a,_)->a==x)r)==(x,y))r

```

The programme takes input as specified in the testcases via STDIN

## Try it online!

# Answer
> 1 votes
# 05AB1E, 48 bytes

```
¯svÐ˜y`Uk;©di®èX.ïi`X+‚ëy`:}®ǝëX.ïiyëX¾‚}ª]Σθï}R

```

Input as a list of pairs.

Try it online or verify all test cases.

**Explanation:**

```
¯                # Start with an empty list: []
 sv              # Loop over each input-pair `y`
   Ð             #  Triplicate the current list
    ˜            #  Flatten it
     y`          #  Push the key and value of the current item `y` separated to the stack
       U         #  Pop the value, and store it in variable `X`
       k         #  Get the index of the key in the flattened list
        ;©       #  Halve it, and store it in variable `®` (without popping)
    di           #  If this index/2 is non-negative (>= 0):
      ®è         #   Get the `®`'th pair from the current list
        X.ïi     #   If `X` is an integer:
            `    #    Push the key and value of the indexed pair separated to the stack
             X+  #    Add `X` to the value
               ‚ #    And pair the key and this new value back together
           ë     #   Else (it's a rename):
            y`   #    Push the key and value of the current item `y` separated to the stack
              :  #    And replace key with value in the indexed pair
           }     #   After the if-else:
            ®ǝ   #   Insert this modified pair at index `®` back into the list
     ë           #  Else (the current key doesn't exist yet):
      X.ïi       #   If `X` is an integer:
          y      #    Simply use the current item `y`
         ë       #   Else:
          X¾‚    #    Pair `X` with 0
         }       #   After the if-else:
          ª      #   Append this new pair to the list
  ]              # After the loop:
   Σ  }          # Sort the resulting list in ascending order by:
    θ            #  The last item of each pair (the values)
     ï           #  Casted to an integer (because the `:` might have made it a string)
       R         # And then reverse this sorted list to make it descending
                 # (after which it is output implicitly as result)

```

# Answer
> 1 votes
# AWK (with shell callout to "sort"), 105 bytes

```
b=$1,d=$2{g=f[b]=d+0==d;f[d]=!g;g?m[b]+=d:m[d]=0+m[b]}END{for(n in m)if(f[n])print n" "m[n]|"sort -k2rn"}

```

Try it online!

This one builds two arrays, one with the score for a give name, and one that's a boolean flag indicating if a name is active or not. At the end, the code prints the reputation scores for all the active accounts and pipes those lines to a `sort` call. Sorting things in AWK is a nightmare...

Here's a description of the components.

```
b=$1,d=$2{                                              }

```

This test/code-block runs for each input line. The `b=$1` and `d=$2` are just a shortcuts for positional variables used repeatedly in the code. The first one is always truthy, so the code block runs even if the reputation is `0`.

```
g=f[b]=d+0==d;

```

The first expression sets the "is an active account" flag (the `f[]` array) to true or false depending on whether or not the second token on the input line is a number. The test `d+0==d` catches that since AWK converts a non-numeric string to `0` if you try an use it as an integer in a mathematical expression. And `g` is set just to shorten the code when `f[b]` is needed later.

```
f[d]=!g;

```

The "is an active account" flag for the second token is the opposite of the value computed for the first token. That will set some garbage entries for input lines that have a numeric reputation as the second token, but they will be ignored.

```
g?m[b]+=d:m[d]=0+m[b]

```

This ternary sets increments the reputation counter (the `m[]` array) for the first token if we got a numeric second token. Otherwise it sets the reputation token for the second token to the reputation token of the first token. In other words, it copies the reputation to the new name.

```
END{for(n in m)if(f[n])print n" "m[n]|"sort -k2rn"}

```

Once all the input lines have been handles, the code loops through all the names in the reputation array `m[]` and for any that are active users per the `f[]` array, it prints the name and final reputation. The `sort -k2rn` command sorts the whole set and prints the output.

# Answer
> 0 votes
# AWK, 132 bytes

```
/.* -?[0-9]/{a[$1]+=$2}
!/.* -?[0-9]/{a[$2]=a[$1]+0;delete a[$1]}
END{PROCINFO["sorted_in"]="@val_num_desc";for(k in a)print k,a[k]}

```

Try it online!

We're careful to `+0` to make sure the new name has reputation. The hardest part of this problem is printing the list out sorted by values. Thankfully, GNU Awk has an array called `PROCINFO`, and by writing the special value `"@val_num_desc"`, the array will be `num`erically sorted in `desc`ending order by `val`ue.

# Answer
> 0 votes
# Perl 5 `-a`, 114 bytes

```
$_=pop@F;/^-?\d+$/?$k{$F[0]}+=$_:($k{$_}=$k{$F[0]}+0,delete$k{$F[0]})}{say"$_ $k{$_}"for sort{$k{$b}-$k{$a}}keys%k

```

Try it online!

# Answer
> 0 votes
# Java 10, ~~166~~ 251 bytes

```
import java.util.*;a->{var r=new HashMap<String,Long>();for(var l:a)if(l[1].matches("-?\\d+"))r.merge(l[0],new Long(l[1]),Long::sum);else{var t=r.remove(l[0]);r.put(l[1],t==null?0:t);}return r.entrySet().stream().sorted(Map.Entry.comparingByValue());}

```

+85 bytes because I hadn't noticed the output should be sorted by value.. \>.\>

Input as a 2D list of Strings, output as a sorted stream of key-value pairs.

Try it online.

**Explanation:**

```
import java.util.*;            // Required import for Map and HashMap
a->{                           // Method with 2D String-array as parameter
                               //  and a Stream of String-Long KeyValue-pairs as return-type
  var r=new HashMap<String,Long>();
                               //  Map, starting empty
  for(var l:a)                 //  Loop over the lines of the input:
    if(l[1].matches("-?\\d+")) //   If the second part is an integer:
      r.merge(l[0],            //    Use the first part as key
              new Long(l[1]),  //    Convert the second part to an integer
              Long::sum);      //    And sum it with a potential existing value for this key
    else{                      //   Else (it's a rename):
      var t=r.remove(l[0]);    //    Remove the first part from the map;
                               //    store the current value (of null if not present) in `t`
      r.put(l[1],              //    Use the second part as new key
            r.remove(l[0]));   //    And remove the first part from the map,
                               //    which will return the current value
                               //    (or null if not present)
  return r                     //  Return the Map as result
    .entrySet().stream()       //  after we've converted it to a steam of KeyValue pairs,
    .sorted(Map.Entry.comparingByValue());}
                               //  and sorted it by value

```

---
Tags: code-golf
---


title: ASCII Borromean Rings

text:
# Question
Title: ASCII Borromean Rings
The Borromean rings are a curious set of three circles, linked such that the removal of any one of them will unlink the other two:

You can make a set for yourself with a couple rubber bands and a binder ring. With more rubber bands, it's easy to make any Brunnian link.

Write a program or function that outputs (prints or returns) this ascii-art representation of Borromean rings:

```
    +-----+
    |     |
+-----+   |
|   | |   |
| +-|---+ |
| | | | | |
| | +-|---+
| |   | |
+-|---+ |
  |     |
  +-----+

```

The lines may have trailing spaces and there may be a trailing newline.

The shortest code in bytes wins.

# Answer
> 7 votes
# CJam, ~~53 51 50~~ 49 bytes

Plain old base conversion...

```
"FÓîÞ¤ÛYËB[¢O²êÍÓ
}²|äG"299b4b"+ -|"f=B/N*

```

All characters are well in extended ASCII range (ASCII code 1 to 255), so number of characters == number of bytes.

Try it online here and get the original code here

# Answer
> 6 votes
# Pyth - 51 bytes

I'm sure someone's gonna beat this quick, but just a base compression answer cuz I'm feeling lazy. I'll try to write a serious answer soon.

```
s@L"
 +-|"jC" zB²;¶Ê ¿ïÁ»#-ÌClHõy%|ap"5

```

Try it here online.

```
s              Reduce on string concatenation
 @L            Map second arg to index first arg
  "..."        String of all chars (Pyth allows literal newlines)
  j            Base conversion to list
   C           Base conversion 256 -> 10
    "..."      Base 256 string
   5           To Base 5

```

# Answer
> 4 votes
# Pyth, 49 bytes

```
jbc11s@L"+ -|"jC"Tª]UÊ¨WÕÝ_K¨}ÝÝ÷K¨Ý]Òê]UÕ*¡"4

```

Demonstration.

This uses base 4 encoding, and chops the string into elevenths, then rejoins them on newlines.

# Answer
> 3 votes
# Ruby, 110

```
-2.upto(8){|i|s=" "*(i%6)+"+-----+"*(1-i%2)+" "*9
6.times{|j|"@d me?K[RR@"[i+2].ord>>j&1>0&&s[j*2]=?|}
puts s}

```

Something different from straight base conversion.

Ungolfed:

```
-2.upto(8){|i|                                           #for each line
  s=" "*(i%6)+"+-----+"*(1-i%2)+" "*9                    #load s with "+-----+" (if required!) padded appropriately with leading spaces and with nine trailing spaces.
  6.times{|j|"@d me?K[RR@"[i+2].ord>>j&1>0&&s[j*2]=?|}   #replace characters with | as necessary, according to the 6-bit number encoded by each character in the magic string.
  puts s}                                                #print the line.

```

# Answer
> 3 votes
# Ruby, 117 bytes

Not winning, but I thought it was a cute approach:

```
puts'    --
    |     |
--  |
|   | |   |
| -||
| | | | | |
| | -|
| |   | |
-||
  |     |
  --'.gsub /-./,'+\0---+ '

```

# Answer
> 2 votes
# BrainFuck, 361 bytes

Here is a little BrainFuck program, only printing char by char.

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

```

# Answer
> 2 votes
# brainfuck, ~~282~~ ~~280~~ 271 bytes

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

```

Try it online!

# Answer
> 2 votes
# Vyxal `j`, 43 bytes

```
»⟑|Ḃṗ=›ḟL«w_¬⌊†⁰÷↳ḋ≈∑Ġ«Ṅ⁽ǔ7₇ÞyΠj»`-+| `τ11/

```

Try it Online!

```
»...»           # Base-255 compressed number
     `-+| `τ    # Decompress using key `-+| `
            11/ # Divide into 11 pieces
                # join by newlines

```

# Answer
> 1 votes
# Staq, 109 chars

```
&iiiqi{1" "}{211}{c"| "}{fcc}{o"+-|"}{p"+--"}{r"---+"}{ec;}22pr;22c22epr21ec2f2ecor1effcefor;f2ceor1e2c22e2pr

```

output:

```
Executing D:\codegolf\Staq borromean rings.txt

    +-----+
    |     |
+-----+   |
|   | |   |
| +-|---+ |
| | | | | |
| | +-|---+
| |   | |
+-|---+ |
  |     |
  +-----+

Execution complete.
>

```

# Answer
> 1 votes
# Charcoal, 31 bytes

```
Ｂ⁷¦⁷Ｍ±⁴¦²Ｂ⁷¦⁷Ｍ²¦²Ｂ⁷¦⁷Ｍ²→|Ｍ³¦²¦¹

```

Try it online!

Link is to verbose version of code.

It's pretty fun to have a box function.

Basically draws three boxes at the required location, and patches the required places.

# Answer
> 1 votes
# Haskell, 79 bytes

```
"]O|f]S]S6|g[:[S[VO1g$S)S*)O1f)])61g&S]RZ|x">>=(mapM(:"|\n -")"+++"!!).fromEnum

```

Try it online!

A base-5 decompression technique. Each ASCII value in the string is used as an index into the list of parts `["+++", "++|", "++\n", ..., "---"]` created by `mapM`.

## Approach

See this tip for Cartesian product with `mapM`.

At first, I used `mapM(\_->"......")"123"` to create the decoding list, with some permutation of `" +-|\n"` in place of the dots. The best permutations (yielding the shortest encoded string literals) gave 83-byte solutions:

```
">:]P>H>F+]%FpHpFob[FrHrFr:vPr>r\bvRfH>F=][">>=(mapM(\_->"\n+ -|")"123"!!).fromEnum
">;|i>C>A1|%AWCWAVwyAXCXAX;ciX>X\tckMC>A=|y">>=(mapM(\_->"\n+ |-")"123"!!).fromEnum
"]R>7]b]_%>+_vbv_tH=_wbw_wRp7w]w\ap:gb]_[>=">>=(mapM(\_->"\n+- |")"123"!!).fromEnum
"|k>7|w|s%>1scwcs`C=sbwbsbkW7b|b\aW;Ow|sy>=">>=(mapM(\_->"\n+-| ")"123"!!).fromEnum
"]T|i]X]U1|+UDXDUBryUCXCUCTJiC]C\tJl5X]U[|y">>=(mapM(\_->"\n+| -")"123"!!).fromEnum
"|l]P|r|n+]1nJrJnGX[nHrHnHlDPH|H\bDT6r|ny][">>=(mapM(\_->"\n+|- ")"123"!!).fromEnum

```

Each contains one low-ASCII byte, `\b` or `\t` or `\a`.

Then I realized I could write `mapM(\_->"\n+ -|")"123"` as `mapM(:"+ -|")"\n\n\n"` to save two bytes. But maybe I could save even *more* bytes if I used a permutation *not* starting with `\n`, because `"\n\n\n"` is pretty long.

Sadly, the permutations not starting with `\n` yielded bad values making the string literal longer. The best programs are all still 81 bytes:

```
">6|g>9>:\24|\f:%9%:#mx:$9$:$61g$>$O1f*9>:<|x">>=(mapM(:"| \n-")"+++"!!).fromEnum
">5]O>9>;\18]\f;%9%;#SZ;$9$;$5+O$>$g+M/9>;<]Z">>=(mapM(:"| -\n")"+++"!!).fromEnum
"|f>5|m|l\f>\24l1m1l-9<l.m.l.f%5.|.M%6,m|lx><">>=(mapM(:"|-\n ")"+++"!!).fromEnum
"]M>6]S]T\f>\18T+S+T(9<T)S)T)M%6)])f%50S]TZ><">>=(mapM(:"|- \n")"+++"!!).fromEnum

```

However, I had another trick up my sleeve: the problem statement allows for trailing spaces on each line, and maybe I could insert 3 trailing spaces in such a way that the string literal becomes one "actual character" longer, but ends up not having stuff like `\24` and `\f` in it.

So I ran a brute force search for all positions to add such trailing spaces. And indeed, adding a trailing space on lines 2, 4, and 6 lets us write the above 79-byte program, where the encoded string is fully printable ASCII.

There are many other permutation-space-placement pairs that tie this one. Here are just a few:

```
"]O|f]S]SU|x]$])]$O1g$S)S*)O1f)])61g&S]RZ|x" (44,"+|\n -",[1,1,5])
"|g]M|m|m5]Oyz1m1k-SZk.m.k.g+M.|.5+O'm|kx]Z" (44,"+|\n- ",[1,2,2])
">6|fW=>=A|x>)>$>)61f&$9$:$61g$>$O1f*9>:<|x" (44,"+| \n-",[0,1,4])
">5]Mp=>=g]M=G>$>.5+M.9$9'$5+O$>$g+M/9>;<]Z" (44,"+| -\n",[0,2,5])
"|f>5|m|ms><|)|.|)f%60.m.l.f%5.|.M%6,m|lx><" (44,"+|-\n ",[1,1,4])
"]M>5b]+]-><],+S+T(9<T)S)T)M%6)])f%50S]TZ><" (44,"+|- \n",[0,0,2])

```

## I tried a few other things

I tried a few other things. If you pad each line in the target string to "11 characters followed by a newline", then the newlines will only occur at indices ≡ 3 mod 4. In fact, if you look at each *k* mod 4 and count the unique characters there, they group themselves quite nicely:

```
target!!k `elem` " +-|"   when k ≡ 0 mod 4.
target!!k `elem` " -"     when k ≡ 1 mod 4.
target!!k `elem` " +-|"   when k ≡ 2 mod 4.
target!!k `elem` " -\n"   when k ≡ 3 mod 4.

```

So a mixed-base approach is tempting.

Of course, something like `mapM id[" +-|"," -"," +-|"," -\n"]` is too long, but I played with `mapM(`drop`"+|\n- ")[0,3,0,2]`. Sadly, the strings just aren't great. The best I could get out of this was 93 bytes.

```
"³F{³;¥F}¥;/¥1(K//-/={/§9=}9§³9©\130W">>=(mapM(`drop`"||+\n- ")[0,4,1,3]!!).fromEnum

```

Alternatively, you could try a base-4 approach with different alphabets for each k mod 4. This is easy to express with `mapM`. I got this 84 byte solution, which would be 70 bytes if Haskell programs used some ANSI encoding rather than UTF-8.

```
"ÿJ¤ÿ?ðJ§ð?3ð6*p3303B¤3ó<B§<óÿ<öª|">>=(mapM(:"+- ")"|-|\n"!!).fromEnum

```

# Answer
> 0 votes
# Python 3, 139 bytes

This is the closest I can get to printing it directly (which would be 134 bytes) without actually doing so.... I'm not sure how to shorten it any more.

```
a='+-----+'
b='+-|---+'
c=' '*4
d='| '
e=c+d
print(c+a,e*2,a+e[1:],"|   | "*2,d+b+" |",d*6,d+d+b,"| |   "*2,b+" |",e[2:]+e,"  "+a,sep='\n')

```

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---