title: Tips for code-golfing in C#

text:
# Question
Title: Tips for code-golfing in C#
What general tips do you have for golfing in C#? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C# (e.g. "remove comments" is not an answer). Please post one tip per answer.

-- borrowed from marcog's idea ;)

# Answer
Instead of using `.ToString()` use `+""` for numerics and other types that can be natively cast to a string safely.

```
.ToString() <-- 11 chars
+""         <--  3 chars

```
> 67 votes

# Answer
I once deliberately placed my program in `namespace System` so I can shorten access to a specific class. Compare

```
using System;using M=System.Math;

```

to

```
namespace System{using M=Math;

```
> 46 votes

# Answer
If using LINQ you can pass a method directly to `Select` instead of making a lambda.

So, instead of

```
foo.Select(x=>int.Parse(x))

```

you can use

```
foo.Select(int.Parse)

```

directly.

(Discovered recently when improving on one of Timwi's C# answers.)
> 34 votes

# Answer
Use `var` for declaring and initializing (single) variables to save characters on the type:

```
string x="abc";

```

becomes

```
var x="abc";

```

Isn't particulaly necessary for `int`, of course.
> 32 votes

# Answer
Remember that the smallest compilable program in C# is 29 characters:

```
class P
{
    static void Main()
    {
    }
}

```

So start by removing that from your length and judge your answer on how much over that it takes. C# cannot compete with other languages when it comes to printing or reading input, which is the heart of most `[code-golf]` problems, so don't worry about that. As a C# golfer, you're really competing against the language.

A few other things to keep in mind:

* Reduce all loops and `if` statements to a single line if possible in order to remove the brackets.
* If given the option between stdin and command line, always use command line!
> 28 votes

# Answer
Instead of

```
bool a = true;
bool b = false;

```

do

```
var a=0<1;
var b=1<0;

```

If you need multiple variables, use this (suggested by @VisualMelon)

```
bool a=0<1,b=!a;

```
> 26 votes

# Answer
When reading each character of a command line argument, rather than looping up to the string's length:

```
static void Main(string[]a){
    for(int i=0;i<a[0].Length;)Console.Write(a[0][i++]);
}

```

You can save a character by using a try/catch block to find the end:

```
static void Main(string[]a){
    try{for(int i=0;;)Console.Write(a[0][i++]);}catch{}
}

```

This applies to any array within an array such as:

* `string[]`
* `int[][]`
* `IList<IList<T>>`
> 23 votes

# Answer
If you need to use `Console.ReadLine()` multiple times in your code (min 3 times), you could do:

```
Func<string>r=Console.ReadLine;

```

and then just use

```
r()

```

instead
> 20 votes

# Answer
Favor the ternary operator over `if`..`else` blocks where appropriate.

For example:

```
if(i<1)
    j=1;
else
    j=0;

```

is more efficiently:

```
j=i<1?1:0;

```
> 18 votes

# Answer
## Effective use of using

You can replace `float` (which is an alias for `System.Single`) with `z` using `z=System.Single;`

Then replace `z=System.Single;` with `z=Single;` by placing the program in the namespace `System`. (As with Joey's answer)

This can be applied for other value types (use what they are an alias for), structs and classes
> 17 votes

# Answer
# LINQ

Instead of using:

```
Enumerable.Range(0,y).Select(i=>f(i))

```

to get an Enumerable with the result of function `f` for every `int` in `[0,y]` you can use

```
new int[y].Select((_,i)=>f(i))

```

if you need `string` or anything that implements `Enumerable` in your program you can use them too

```
var s="I need this anyway";
s.Select((_,i)=>f(i))

```
> 16 votes

# Answer
In C#, we are not allowed to do `if(n%2)` to check if `n` is a even number. If we do, we get a `cannot implicity convert int to bool`. A naive handling would be to do:

```
if(n%2==0)

```

A better way is to use:

```
if(n%2<1)

```

I used this to gain one byte here.

note that this only works for positive numbers, as `-1%2==-1`, it is considered even with this method.
> 15 votes

# Answer
# Use lambdas to define a function in C# 6

In C# 6, you can use a lambda to define a function:

```
int s(int a,int b)=>a+b;

```

This is shorter than defining a function like this:

```
int s(int a,int b){return a+b;}

```
> 14 votes

# Answer
Looping:

Variable declarations:

```
int max;
for(int i=1;i<max;i++){
}

```

become:

```
int max,i=1;
for(;i<max;i++){
}

```

And if you have a need to or work with the i variable only once, you could start at -1 (or 0 depending on the loop circumstance) and increment inline:

```
int max,i=1;
for(;i<max;i++){
  Console.WriteLine(i);
}

```

to

```
int max,i=1;
for(;i<max;){
  Console.WriteLine(++i);
}

```

And that reduces by one character, and slightly obfuscates the code as well. Only do that to the FIRST `i` reference, like thus: (granted one character optimizations aren't much, but they can help)

```
int max,i=1;
for(;i<max;i++){
  Console.WriteLine(i + " " + i);
}

```

to

```
int max,i=1;
for(;i<max;){
  Console.WriteLine(++i + " " + i);
}

```

---

when the loop does not have to increment `i` (reverse order loop):

```
for(int i=MAX;--i>0;){
      Console.WriteLine(i);
}

```
> 11 votes

# Answer
If you need to use a generic `Dictionary<TKey, TValue>` at least two times in your code, you could declare a dictionary class, like in this example:

```
class D:Dictionary<int,string>{}

```

and then just use

```
D d=new D{{1,"something"},{2,"something else"}};

```

instead of repeating `Dictionary<int,string>` for every instantiation.

I have used this technique in this answer
> 11 votes

# Answer
For one-line lambda expressions, you can skip the brackets and semicolon. For one-parameter expressions, you can skip the parentheses.

Instead of

```
SomeCall((x)=>{DoSomething();});

```

Use

```
SomeCall(x=>DoSomething);

```
> 10 votes

# Answer
You can use `float` and `double` literals to save a few bytes.

```
var x=2.0;
var y=2d;         // saves 1 byte

```

When you need some `int` arithmetic to return a `float` or `double` you can use the literals to force the conversion.

```
((float)a+b)/2;  // this is no good
(a+b)/2.0;       // better
(a+b)/2f;        // best

```

If you ever run into a situation where you have to to cast you can save a few bytes by using multiplication instead.

```
((double)x-y)/(x*y);
(x*1d-y)/(x*y);      // saves 5 bytes

```
> 10 votes

# Answer
Remember where private or public are inherent, such as the following:

```
class Default{static void Main()

```

as compared to

```
public class Default { public static void Main()

```
> 9 votes

# Answer
There are circumstances when an output parameter can save characters. Here's a *slightly* contrived example, a 10 pin bowling score algorithm.

With a return statement:

```
........10........20........30........40........50........60........70........80........90.......100.......110.......120.......130.......140.......150..
public double c(int[]b){int n,v,i=0,X=10;double t=0;while(i<19){n=b[i]+b[i+1];v=b[i+2];t+=(n<X)?n:X+v;if(b[i]>9)t+=b[i+(i>16|v!=X?3:4)];i+=2;}return t;}

```

And with an output parameter:

```
........10........20........30........40........50........60........70........80........90.......100.......110.......120.......130.......140.......
public void d(int[]b,out double t){int n,v,i=0,X=10;t=0;while(i<19){n=b[i]+b[i+1];v=b[i+2];t+=(n<X)?n:X+v;if(b[i]>9)t+=b[i+(i>16|v!=X?3:4)];i+=2;}}

```

The output parameter here saves a total of 5 characters.
> 9 votes

# Answer
# Avoid single-statement `foreach` loops

If the loop's statement returns a non-`int` (including `void`!) "value", it can be replaced with LINQ:

```
foreach(var x in a)Console.WriteLine(F(x));
a.Any(x=>Console.WriteLine(F(x))is int);

```

If the value happens to be an `int`, you can use a condition that will always be true or always be false (for example, `>0` or `<n`), a different type and/or `All` instead of `Any`.
> 9 votes

# Answer
# Use `dynamic` to group declarations

`dynamic` is a forgotten feature that literally performs dynamic typing in C#! It has limitations (doesn't support extension methods, is bad at inferring that you want to use it, ...), but can often save bytes by merging declarations of incompatible types. Compare the following:

```
var a=[something of type IEnumerable<int>];var b=[something of type string];int i=x+~y^z
dynamic a=[something of type IEnumerable<int>],b=[something of type string],i=x+~y^z

```

That's 4 bytes of savings!
> 9 votes

# Answer
# Use the weird kind of the `is` operator

`a is var b` *always* defines the variable `b` equal to `a` and returns `true`. It is unclear how have the humans who design C# come up with this (inline variable declarations that return `true` for some reason seem to be beyond Javascript to me), but it works. It can sometimes be used to shorten code (this is an oversimplified example; savings can often be smaller or zero):

```
a=>{var b=f(a);return g(b,b);}
a=>g(f(a)is var b?b:b,b)

```
> 8 votes

# Answer
## String Interpolation

A really simple space-saving improvement is interpolation. Instead of:

```
string.Format("The value is ({0})", (method >> 4) + 8)

```

just use `$` to inline expressions:

```
$"The value is ({(method >> 4) + 8})"

```

This, together with the new expression bodies in C#6.0 should make any simple string-calculation challenge pretty golfable in C#.
> 7 votes

# Answer
If you need to include multiple `using`s that all fall off of the same hierarchy it is often shorter to use the longest one as the `namespace`:

```
using System;
using System.Linq;
//Some code

```

vs:

```
namespace System.Linq
{
    //Some code
}

```
> 7 votes

# Answer
The `Compute` instance method of `System.Data.DataTable`, allows to evaluate a simple string expression, e.g. :

# C# (Visual C# Compiler), 166 bytes

```
namespace System.Data
{
    class P
    {
        static void Main()
        {
            Console.Write(new DataTable().Compute("30*2+50*5/4",""));
        }
    }
}

```

Try it online!

Not very "golfy" per se, but sometimes might be useful.
> 7 votes

# Answer
# Swapping two variables

Normally, to swap two variables, you have to declare a temporary variable to store the value. It would look like something along the lines of this:

```
var c=a;a=b;b=c;

```

That's 16 bytes! There are some other methods of swapping that are better.

```
//Using tuples
(a,b)=(b,a);
//Bitwise xoring
a=a^b^(b=a);
//Addition and subtraction
a=a+b-(b=a);
//Multiplication and division
a=a*b/(b=a);

```

The last three only work for numeric values, and as ASCII-only pointed out, the last two might result in an ArithmeticOverflow exception. All of the above are 12 bytes, a 4 byte saving compared to the first example.
> 7 votes

# Answer
Use C# lambda. Since PPCG allows lambda for input/output we should use them.

A classic C# methods looks like this:

```
bool Has(string s, char c)
{
    return s.Contains(c);
}

```

As a lambda, we will write

```
Func<string, char, bool> Has = (s, c) => s.Contains(c);

```

Anonymous lambda are allowed too:

```
(s, c) => s.Contains(c)

```

Remove all the noise and focus!

Update:

We can improve one step more with currying as @TheLethalCoder comment:

```
s => c => s.Contains(c);

```

Example of curring by @Felix Palmen: How compute WPA key?

It will be helpful when you have exactly 2 parameters, then a empty unused variable `_` will be better. See meta post about this. I use this trick here. You will have to change a bit the function. Example: Try it online!
> 6 votes

# Answer
# Use .NET 6 Top Level Statements, File-Scoped Namespaces, and target-typed new()

Upgrade to .net 6 and you can use single file programs with no boilerplate. You can also use file-scoped namespaces like so:

`namespace whatever;`

Also, when you instantiate an object, if it's type can be inferred by the compiler, you can use a target-typed `new()` constructor. e.g.,

```
class C {}
C c=new();

```

See (https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/top-level-statements)

See Also (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-10.0/file-scoped-namespaces)
> 6 votes

# Answer
Make classnames only one letter. Enhancing on Tips for code-golfing in C# we go from

```
class Default{static void Main()

```

to

```
class D{static void Main()

```

which knocks out another 6 chars in this case.
> 5 votes

# Answer
Using LinqPad will give you the possibility to remove all the program overhead as you can execute statements directly. (And it should be fully legal in codegolf... No one says you need an .exe)

Output is done using the `.Dump()` extension method.
> 4 votes

# Answer
Use the one character non-short-circuiting variants of logical operators where possible:

* `i>0||i<42`
* `i>0|i<42`

or

* `i>0&&i<42`
* `i>0&i<42`

The difference between the two are one byte (yeah!) and the short-circuit principle. In our first example if `i>0` is `true`, `i<42` wont be checked. We dont need it. With the bitwise, both will be evaluated.

example: Code golf to make logos for New Stack exchange sites

Learn more about them on MSDN.
> 4 votes

# Answer
Use `Action` like `Func` to set a function to a variable. `Action` returns nothing (`void`) so it is great for printing.

For example:

```
Action<string>w=Console.WriteLine;
w("Hello World");

```

This tips is inspired by @W0lf great example of use of `Func` with `ReadLine`.
> 4 votes

# Answer
# Declare empty/matching strings together

If you need to declare multiple empty/matching strings, you can save a few bytes with the following:

```
string a="";string b="";string c=""; // 36 bytes
var a="";var b="";var c="";          // 27 bytes
string a="",b="",c="";               // 22 bytes
string a="",b=a,c=a;                 // 20 bytes

```

Unfortunately `var a="",b=a,c=a;` is illegal, as `implicitly type variable cannot have multiple declarators`
> 4 votes

# Answer
*(A particular case of knowing your operator precedence!)*

Use `%` for tight-binding (somewhat) limited subtraction. This can save you a pair of parentheses around a subtraction, the result of which you want to multiply or divide by something; but be careful, it has serious limitations.

Instead of

```
char b='5'; // b is some ASCII input
int a=(b-48)*c; // we want to find the numerical value of b, and multiply it by something ('0'==48)

```

Consider

```
char b='5'; // b is some ASCII input
int a=b%48*c; // only good for ASCII within 48 of '0' (positive only)!

```

Examples:

```
'5'%'0'*2 -> 10
'5'%'0'*-1 -> -5
'5'%'0'/2 -> 2

```

I've only just discovered this, and I feel like it will be valuable thing to remember whenever working with ASCII in the future. (I'm currently golfing somewhere where I'm using ASCII for compact numeric representations, but needs to multiply by `1` or `-1` based on another condition, and this striped 2 bytes)
> 4 votes

# Answer
If you're already using Linq in your answer and need to check for a none empty collection use `Any()`. Compare it to the following:

```
Count()>0
Length>0
Count>0
Any()

```
> 4 votes

# Answer
# Use Ranges and indices (C# 8)

You can use the type Index, which can be used for indexing. You can create one from an int that counts from the beginning, or with a prefix ^ operator that counts from the end:

```
Index i1 = 3;  // number 3 from beginning
Index i2 = ^4; // number 4 from end
int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Console.WriteLine($"{a[i1]}, {a[i2]}"); // "3, 6"

```

You can also use a Range type, which consists of two Indexes, one for the start and one for the end, and can be written with a x..y range expression. You can then index with a Range in order to produce a slice:

```
var slice = a[i1..i2]; // { 3, 4, 5 }

```

source
> 4 votes

# Answer
# C# Interactive Window

AKA C# (Visual C# Interactive Compiler) on Try it Online

This is a REPL for the C# language that includes many advantages to code golfing over using the traditional C# compiler.

Currently, the shortest full program to print `Hello, World!` using the traditional C# compiler is 67 bytes:

```
class P{static void Main(){System.Console.Write("Hello, World!");}}

```

Using the C# Interactive Window, you can do the same thing in 22 bytes:

```
Write("Hello, World!")

```

And yes, I added my answer just for this post ;)

As you can see, ceremonial class definitions are not required. Also, a whole bunch of references are included by default. The current list is as follows:

* /r:System
* /r:System.Core
* /r:Microsoft.CSharp
* /u:System
* /u:System.IO
* /u:System.Collections.Generic
* /u:System.Console
* /u:System.Diagnostics
* /u:System.Dynamic
* /u:System.Linq
* /u:System.Linq.Expressions
* /u:System.Text
* /u:System.Threading.Tasks

The `System.Linq` namespace is particularly handy as it allows you to write functional style programming which often saves many bytes. Many of the older C# answers added 18 bytes or so for this advantage, simply to import the library `using System.Linq;`. There are other hacks where solutions created their class in the `System` namespace to more succinctly access the `Console` object. None of this is needed with the C# Interactive Window.
> 4 votes

# Answer
# Group statements via tuples

Let's assume the simplest case: you have two statements that return a value and would like to group them into one that returns the second value (perhaps the first one has useful side effects):

```
(s1,o:s2).o

```

This can be used along with inline variable declarations via `is`:

```
(s1 is var x,o:f(x,g(x))).o

```

It also works with the `void -> value` transformation via `is int` (although it doesn't always help):

```
(Print(x)is int,o:f(x)).o

```
> 4 votes

# Answer
Discovered tonight "in the trenches" while improving some golf code... if you have a class for your processing, you can do the work in the constructor to save declaring a method.

I discovered this while reducing a console application - as there was a `static void Main()`, all functions and variables had to be declared static. I created a nested class with member functions and variables, with the main work performed in the constructor. This also saves characters in the calling code.

e.g. Class with method:

```
class a
{
    public void b()
    {
        new c().d("input");
    }
}
class c
{
    public void d(string e)
    {
        System.Console.Write(e.Replace("in", "out"));
    }
}

```

Class with work in the constructor:

```
class a
{
    public void b()
    {
        new c("input");
    }
}
class c
{
    public c(string e)
    {
        System.Console.Write(e.Replace("in", "out"));
    }
}

```

This example saves 9 characters.
> 3 votes

# Answer
When to use a space and when you can remove it.

After `[]`

* `int[] f(char[] a){Console.Write('a');}`
* `int[]f(char[]a){Console.Write('a');}`

---

Before `$`

* `return $"{a}"`
* `return$"{a}"`

example: Code golf to make logos for New Stack exchange sites

---

(Add yours in comment I will edit)
> 3 votes

# Answer
When you want to join something to output a `string` without delimiter, you should use `string.Concat()`, instead of `string.Join("",)`;

* `string.Join("",)`
* `string.Concat()`

One byte free!

example: Code golf to make logos for New Stack exchange sites

Also `Concat()` has a lot more signatures than `Join`. Check them on MSDN: Concat and Join.
> 3 votes

# Answer
If you need to use an `enum` for a method it is often shorter to cast an `int` to it rather than using the value directly:

```
DayOfWeek.Sunday
(DayOfWeek)0;

```
> 3 votes

# Answer
Always use the alias for a type if you need to type as they are usually shorter than the full names. It also means you don't need to include

```
using System;

```

or fully qualify the type when you otherwise wouldn't need to.

For a full list of the aliases visit this SO answer:

```
object:  System.Object
string:  System.String
bool:    System.Boolean
byte:    System.Byte
sbyte:   System.SByte
short:   System.Int16
ushort:  System.UInt16
int:     System.Int32
uint:    System.UInt32
long:    System.Int64
ulong:   System.UInt64
float:   System.Single
double:  System.Double
decimal: System.Decimal
char:    System.Char

```

Note that you can also use the alias for calling static methods, consider:

```
System.String.Concat();

```

vs

```
string.Concat();

```
> 3 votes

# Answer
If you're already using Linq in your code and need to create a list use the following:

```
var l=new int[0].ToList();

```

Compared to:

```
var l=new System.Collections.Generic.List<int>();

```

You can even initialise the list with values like:

```
var l=new []{1,2,3,4}.ToList();

```
> 3 votes

# Answer
If you want to return multiple values from a function, use C# 7 style tuples instead of out parameters:

```
(int,int)d(int a,int b)=>(a/b,a%b);

```
> 3 votes

# Answer
Here are my 5 cents:

You can plain replace Math.Max and Math.Min, the following way, to gain 6 bytes:

```
Math.Max(a,b); // turns into:
a>b?a:b;       // saving 6 bytes

```

Another hint is a small way to use a loop, when you are given a variable with "n" times that won't be used anymore (as it will flatten your variable);

```
for (int i=0;i<n;i++) // turns into:
while (n-->0)         // saving 8 bytes

```

Method string.Split(' ') has default value whitespace, so if input string has the usual ' ' separation, instead of:

```
string.Split(' ');

```

Write:

```
string.Split() // gain 3 bytes

```
> 3 votes

# Answer
**Infinite Loops**

Default infinite loop provided in code golf is usually a **while** loop:

```
while(true){...}

```

This can be reduced (-1, as stated earlier) using an inequality:

```
while(1>0){...}

```

But it can be better reduced (-4) using a parameterless **for** command:

```
for(;;){...}

```
> 3 votes

# Answer
# Implicitly typed arrays

If you need an array (or IEnumerable) initialized with constant data, the most naive implementation might be like so:

```
new int[6]{23,16,278,0,2,44}

```

It's well known that arrays in C# can have implicit length:

```
new int[]{23,16,278,0,2,44}

```

However, for certain data types C# will also be able to determine the base type for the array from its values, making the same declaration even shorter:

```
new[]{23,16,278,0,2,44}

```

Here is an example demonstrating that all these options create the same array.

Additionally, specifically if you are creating an array for inline declaration, the `new[]` can be removed as long as the declared variable is not implicitly typed, which can save some bytes:

```
var a=new[]{"woah"};
string[]b={"woah"};

```
> 2 votes

# Answer
# Convert a `string` to an `IEnumerable<char>`

Common way would be to use `.ToCharArray()` (14 bytes) or even better `.ToList()` (11 bytes), but the best I found is to rely on `.Skip(0)` (8 bytes).

Most of the time you wont need anything and the string will be cast directly, but sometimes it matters:

```
string.Join("a","bb") // bb

```

vs

```
string.Join("a","bb".Skip(0)) // bab

```
> 2 votes

# Answer
# Tuple Deconstruction

It is possible to deconstruct a `Tuple` into variables using the following syntax:

```
var myTuple = (1, "red", new DateTime(2000, 1, 1));
var (i, c, d) = myTuple;

```

In a code-golf scenario, you could use this to pass a tuple into a function:

```
t=>{var(i,c,d)=t;Print(i);Print(c);Print(d);}

```

Try it online!

A more practical use of this is to decompose a list of tuples and iterate over them using `foreach`.

```
var myTuples = new[] {
    (1, "red", new DateTime(2000, 1, 1)),
    (2, "blue", new DateTime(2000, 1, 1))
};
foreach (var (i, c, d) in myTuples) {
    Print(i);
    Print(c);
    Print(d);
}

```

Or in a code-golf scenario:

```
t=>{foreach(var(i,c,d)in t){Print(i);Print(c);Print(d);}}

```

Try it online!
> 2 votes

# Answer
Use Range instead of Substring:

```
var s="abcdef";
Console.Write(s.Substring(2,2)); // "cd"
Console.Write(s[2..4]); // "cd"

```

It doesn't work if type is not known at compile time:

```
dynamic s="abcdef";
Console.Write(s[2..4]); // runtime error
Console.Write($"{s}"[2..4]); // "cd"

```
> 2 votes

# Answer
You can use the ternary operator to shorten complex `if..else` constructs even if you need to work on multiple or different variables in different branches. You can sometimes save some chars by doing all or part of the work in the 3rd part of a `for`. ...and also other "optimizations", you can find in this example, I submitted here (it increments all numbers in a string given as char array or StringBuilder):

```
for (int b=3, c, i=a.Length; i-->0;
    b=48>c|c>57
        ?7
        :b>2
            ?c>56?a[i]='0':++a[i]*0
            :b
) c=a[i];

```

In two of the branches, `b` isn't really set; in two branches, `a[i]` is set even though it says `b=` in the beginning; in one case `a[i]` and `b` are set simultaneously...

`c>56` is shorter than `c==57`

`i=a.Length; i-->0;` is a lot shorter than `i=a.Length-1; i>=0; i--`
> 1 votes

# Answer
One thing I just learned (which I didn't know but probably all of you do): You do not need a namespace at all. If it is a simple program which doesn't use many namespaces that you would need to shorten, just omit the `namespace` and start with `class Foo{...`.

Any objections to this or hints why I shouldn't do this are very welcome, as I'm just writing up my first "golfed" (as far as I got) answer in C# ;-)
> 1 votes

# Answer
Convert line endings from CRLF to LF before counting bytes ☺
> 1 votes

# Answer
## ReSharper tips

If you have used ReSharper to get to the initial working solution before golfing, note that it often generates

* `readonly` variables
* `static` methods, if they do not use any fields

If you have R#, you want to use the *inline method* refactoring for methods that are only called once, since they only need the additional method declaration.
> 1 votes

# Answer
Remember that C# uses unicode (which includes ascii). All `char` are `int` under the hood.

For example `'a'` is `97`.

* `n=>char.IsDigit(n)|char.IsUpper(n)`
* `n=>n>47&n<58|n>64&n<91` // note that I use a bitwise comparator see

example: Code golf to make logos for New Stack exchange sites

---

Since `char` are `int`, you can increment them:

* `for(int x=31;x<126;)Console.Write((char)++x);`
* `for(char x=' ';x<127;)Console.Write(x++);`

example: Print the ASCII printable character set

Use the unicode table for reference. Be careful one byte != one character.
> 1 votes

# Answer
# Using Command-Line Options

Command-line options are not included in the byte count of your program, so they are very useful. However, keep in mind that when you use a command-line option, you are not competing in C# anymore, you are competing in C# with `-yourflag`.

The syntax for them is to put a `-` or a `/` preceding the letter, and if there are any arguments, you use `:` to separate the option name from the argument.

There are 3 command-line options that I know of as of right now:

* `/u` or `-u` or `/using` or `-using`

+ Acts as a `using` statement. Example: `/u:System.Text.RegularExpressions`. You can do static imports with them by just adding the class name, like `/u:System.Text.RegularExpressions.Regex`. For example, if you have `/u:System.String` as an option, you can just use `Concat(yourString)` instead of `string.Concat(yourString)`. Sadly, aliasing doesn't seem to work. You can also put multiple imports on the same line with `;` as a delimiter like this: `/u:System.Math;System.CodeDom`.
* `/i` or `-i`, activates REPL mode. Code from the input box is also evaluated and printed.

+ Can be useful for situations where hard-coding is allowed, e.g. if input `insertRandomTermHere` output 3, if input `anotherRandomTerm` output 4, we can just do `int insertRandomTermHere=3,anotherRandomTerm=4;`. Try it online!
* `/r` or `-r`

+ Acts as an assembly reference. Allows you to use types like those in `System.Numerics` or `System.Drawing`. If you want to use `BigInteger`, an assembly reference is required.

Meanwhile, happy ing!
> 1 votes

# Answer
# Use `dynamic` instead of types with longer names in function declarations

For example, instead of
`DateTime f(int y)=>`
use
`dynamic f(int y)=>`
> 1 votes

# Answer
The first and third sections of `for` can contain multiple comma-separated *statement expressions*, including assignments (but not declarations) and method calls:

```
for(i=0,k=1;i<n;Console.WriteLine(k),k*=3)i++;

```
> 1 votes

---
Tags: code-golf, tips, c#
---


title: Elect the Doge of Venice

text:
# Question
Title: Elect the Doge of Venice
The Venetian election system was... complicated.

> The Great Council came together and put in an urn the ballots of all the councilors who were older than 30. The youngest councilor went to St Mark's Square and chose the first boy he met who drew from the urn a ballot for each councillor and only those 30 who got the word ‘elector' remained in the room. The 30 ballots were then placed back in the box and only 9 contained a ticket, so the 30 were reduced to 9, who gathered in a sort of conclave, during which, with the favourable vote of at least seven of them, they had to indicate the name of 40 councillors.
>
> With the system of ballots containing a ticket, the 40 were reduced to 12; these, with the favourable vote of at least 9 of them, elected 25 others, which were reduced again to 9 who would elect another 45 with at least 7 votes in favour. The 45, again at random, were reduced to 11, who with at least nine votes in favour elected another 41 that finally would be the real electors of Doge.
>
> These 41 gathered in a special room where each one cast a piece of paper into an urn with a name. One of them was extracted at random. Voters could then make their objections, if any, and charges against the chosen one, who was then called to respond and provide any justification. After listening to him, they preceded to a new election, if the candidate obtained the favourable vote of at least 25 votes out of 41, he was proclaimed Doge, if they were unable to obtain these votes a new extraction took place until the outcome was positive.

Venice is no longer an independent republic, but if they were, they would be dying to automate this system! (because we all know electronic voting is the future!) Time for you to step in. To streamline the democracy, I've made a few assumptions on voter preference, group sizes, picking logic, etc. Your program is to do the following.

* Here is the list of members of the Great Council (who are all older than 30). Take this as input, by perhaps reading it from a file, or whatever you prefer. The number of councillors varied over time, so your program should not depend on the number of people.
* Take the youngest member of the council. Because there are no ages given, you'll have to guess. Pick a person at random, and print their name.
* The boy at the square will pick thirty members from an urn. So, randomly choose 30 people from the list (not including the youngest councillor). Print all their names.
* Of those thirty, nine are randomly selected to go to the next round. So randomly choose 9 from that group, and print their names.
* Those nine electors have to choose forty different councillors. So, from the list of councillors, excluding the electors (but including the twenty-one people from the previous round of thirty who did not become electors), pick 40 members. Print their names.
* The forty were reduced to twelve by lot. Pick 12 from these members at random, print their names.
* The dozen elected twenty-five councillors. You know the rules by now: pick 25 councillors excluding the 12 (but including anyone not in the 12 who partook in previous rounds), and print their names.
* The twenty-five got reduced to nine again. Pick 9 random people from the 25 and print their names.
* Those nine selected forty-five councillors. Pick 45 people not in the 9, and print their names.
* The forty-five were reduced to eleven. Pick 11 random councillors from those 45, and print their names.
* The eleven picked forty-one councillors who would elect the doge. Pick 41 people not in the 11, print their names.
* Finally, these people will elect the Doge of Venice. Pick 1 person, randomly, from the 41. Then print their name. And then you can rest and watch the sun set on a democratic universe.

This horrendously complicated system was made to reduce corruption; so however you implement it, every member of the Great Council must have an equal chance of getting elected in the end.

In tabular form:

| Step | From | Pick | New group |
| --- | --- | --- | --- |
| 1 | All | 1 | A |
| 2 | All except A | 30 | B |
| 3 | B | 9 | C |
| 4 | All except C | 40 | D |
| 5 | D | 12 | E |
| 6 | All except E | 25 | F |
| 7 | F | 9 | G |
| 8 | All except G | 45 | H |
| 9 | H | 11 | I |
| 10 | All except I | 41 | J |
| 11 | J | 1 | Doge |

Other rules:

* Print the name(s) exactly as given, with the same capitalisation, etc. There's only going to be readable ascii characters, there's no Nicolò on the council.
* Print every new step of the algorithm on a new line.
* When printing a list of names, separate them in some fashion from one another (not with spaces as the names contain spaces). If you separate them with newlines, then add an extra newline between steps so those remain clearly separated as well.
* This is , so your score is the number of bytes in your code. Lowest score wins!

# Answer
# 05AB1E, 24 bytes

```
•10¢–‘Þ}Ò•46вvNÉiK}.ry£=

```

Print each intermediate result as a list on a separated line to STDOUT.

Try it online.

**Explanation:**

```
•10¢–‘Þ}Ò•       # Push compressed integer 70284432464563859
 46в             # Convert it to base-46 as list: [1,30,9,40,12,25,9,45,11,41,1]
    v            # Loop over each of these integers `y`:
     NÉi }       #  If the 0-based loop-index is odd:
        K        #   Remove all names of the current list from the (implicit) input-list
          .r     #  Shuffle the list of names
            y£   #  Only keep the first `y` amount of random names
              =  #  Print it with trailing newlines (without popping)

```

See this 05AB1E tip of mine (sections *How to compress large integers?* and *How to compress integer lists?*) to understand why `•10¢–‘Þ}Ò•` is `70284432464563859` and `•10¢–‘Þ}Ò•46в` is `[1,30,9,40,12,25,9,45,11,41,1]`.
> 8 votes

# Answer
# Python, ~~117 113 112 106~~ 105 bytes

```
from random import*
def f(l,i=1,x=()):
 for y in b"	(	-)":print(x:=sample(i*x or{*l}-{*x},y));i=1-i

```

Attempt This Online!

Port of Kevin Cruijssen's 05AB1E answer.

*-6 thanks to @CursorCoercer*
*Fixed thanks to @Neil*
> 5 votes

# Answer
# Vyxal `o`, 220 bits1, 27.5 bytes

```
»ac±†ġq⟑»₆τ2ẇ(Þ℅nhẎ…?$FÞ℅ntẎ…)℅

```

Try it Online!

Prints names in a list, except for the final doge. So wow. Much election. Such obvious joke.

## Explained (old)

```
»ac±†ġq⟑»₆τyZ(:Þ℅nhẎ…□$FÞ℅ntẎ…)℅
»ac±†ġq⟑»₆τ                      # The list ⟨ 1 | 30 | 9 | 40 | 12 | 25 | 9 | 45 | 11 | 41 ⟩ (26500992315347689 in base 64)
           yZ                    # uninterleaved and zipped (creates a list of [next_round, count_electors]) (the first choice - the youngest is technically a special case of next round picks)
             (                )  # for each pair n:
              :Þ℅                #   push a random permutation of the top of the stack
                 nhẎ…            #   take the first next_round names from that and print without popping
                     □$F         #   remove these names from the list of potential electors
                        Þ℅ntẎ…   #   take the first count_electors names from a random permutation of the remaining names, printing without popping
                               ℅ # choose a random name from the last pick of 41 and print it with the o flag. This last name is the doge.

```
> 4 votes

# Answer
# Charcoal, 49 bytes

```
ＷＳ⊞υιＦＩ⪪”)¶∨9⊘%ÀsＦ<¦Ｊ”²«≔⎇›ιＬω⁻υωωθ≔⟦⟧ωＦι⊞ω‽⁻θω⟦ω

```

Try it online! Link is to verbose version of code. Takes input as a list of newline-terminated strings. Explanation:

```
ＷＳ⊞υι

```

Input the names.

```
ＦＩ⪪”)¶∨9⊘%ÀsＦ<¦Ｊ”²«

```

Loop over the values `01`, `30`, `09`, `40`, `12`, `25`, `09`, `45`, `11`, `41` and `01`, extracted from a compressed string split into pairs of digits.

```
≔⎇›ιＬω⁻υωωθ

```

If there are more names needed than exist in the previously randomised group, choose them from all of the names not in the previous group instead. (Note that the first time around `ω` is actually the predefined empty string; its length is still zero and vectorised subtracting it from the list has no effect, so the initial name is effectively selected from the entire list.)

```
≔⟦⟧ωＦι⊞ω‽⁻θω

```

Create a new group with the desired number of names randomly selected from the list without replacement.

```
⟦ω

```

Output that group. (I have actually double-spaced the groups from each other to make the output easier to read at the cost of a byte.)
> 4 votes

# Answer
# JavaScript (Node.js), 131 bytes

Returns an array of string arrays.

Contains unprintable characters.

```
a=>[...Buffer("	(	-)")].map(n=>p=[...Array(n)].map(g=_=>p.includes(s=a[Math.random()*a.length|0])+n/25&!g[s]?g[s]=s:g()),p=a)

```

Try it online!

### Commented

```
a =>                  // a[] = input array
[...Buffer("...")]    // list of group sizes
.map(n =>             // for each size n:
  p =                 //   update p[] to
  [...Array(n)]       //   an array of size n where each entry is
  .map(g = _ =>       //   the result of the recursive function g:
    p.includes(       //     test whether p[] includes:
      s =             //       the string s
      a[              //       picked from a[]
        Math.random() //       at a random location
        * a.length    //       (with uniform distribution)
        | 0           //
      ]               //     we invert the parity of the result if ...
    ) + n / 25        //     ... the group size is ≥ 25
    & !g[s]           //     make sure that s was not already selected
    ?                 //     if this is a valid selection:
      g[s] = s        //       return s and mark it as selected
    :                 //     else:
      g()             //       try again
  ),                  //   end of inner map()
  p = a               //   start with p[] = a[]
)                     // end of outer map()

```
> 4 votes

# Answer
# Jelly, 27? 28 bytes

27 if we may write a function that produces a list of lists of names:

```
¹©W;“ċ pr⁻Ṛṫ’ḃ45¤¹®ḟ$ƭẊḣɗ\Ḋ

```

Try it online!

---

```
45“ċ pr⁻Ṛṫ’ḃ¹³ḟ$ƭẊḣY;⁷ṄȧƲʋƒḟ

```

A full program that accepts a list of strings and prints the results with newline and double newline separators.

**Try it online!**

### How?

```
45“ċ pr⁻Ṛṫ’ḃ¹³ḟ$ƭẊḣY;⁷ṄȧƲʋƒḟ - Main Link: list of strings, Councilors
  “ċ pr⁻Ṛṫ’                  - base 250 integer = 56917435399420996
45         ḃ                 - bijective base 45 -> [1,30,9,40,12,25,9,45,11,41,1]
                          ƒ  - starting with current=Councilors reduce that by:
                         ʋ   -   last four links as a dyad - f(current, n):
                ƭ            -     alternate between:
            ¹                -       a) no-op -> current
               $             -       b) last two links as a monad - f(current):
             ³               -            program input -> Councilors (i.e. "all")
              ḟ              -            filter discard (current) -> all except current
                 Ẋ           -     shuffle           }
                  ḣ          -     head to index (n) } choose n of them
                        Ʋ    -     last four links as a monad - f(chosen)
                   Y         -       join with newlines
                    ;⁷       -       concatenate a newline
                      Ṅ      -       print that plus a newline, and yield the result
                       ȧ     -       logical AND (chosen) -> chosen
                           ḟ - filter discard all -- avoids printing the Doge again

```
> 4 votes

# Answer
# Wolfram Language (Mathematica), 113 bytes

```
x:=#1~RandomChoice~#2&
c:=l~Complement~%
l~x~1
l~x~30
%~x~9
c~x~40
%~x~12
c~x~25
%~x~9
c~x~45
%~x~11
c~x~41
%~x~1

```

Now, unfortunately, *Try It Online* does not have the same implementation of the Mathematica Global Loop as a Mathematica notebook does, so the built-in `%` operator, which yields the output of the previous line, does not work. But, you can download the Mathematica notebook online.
> 4 votes

# Answer
# Pyth, 33 bytes

```
Ou
<.S-Q
<.SGhHeHc5jC"m£*’OŸ"46Q

```

Try it online!

### Explanation

```
                               # implicitly assign Q = eval(input())
                  C"..."       # convert string to int using base 256 and codepoints, gives us 1527922444881823
                 j      46     # convert int to list of ints using base 46, gives us [1, 30, 9, 40, 12, 25, 9, 45, 11, 41]
               c5              # chop into five pieces of equal size
 u                        Q    # reduce this list on lambda GH, starting with Q
        .SG                    #   shuffle G
       <   hH                  #   first n elements of, where n is the first value in the pair H
                               #   print this
     -Q                        #   complement in Q
   .S                          #   shuffle
  <          eH                #   first n elements of, where n is the second value in the pair H
                               #   print this
O                              # print a random element of the result

```
> 3 votes

# Answer
# , 88 bytes

*Edit: +6 bytes and change of approach to fix bug in previous version (below)*

```
\(m){g=o=seq(m);for(i in utf8ToInt("!>)H,9)M+I!")-32)show(m[g<-sample(o[g*-(T=-T)],i)])}

```

Attempt This Online!

Function that prints a vector of names for each step of the algorithm; outputted vectors are separated by newlines.

---

Previous approach (now fixed at a cost of +7 bytes):

# , 89 bytes

```
\(m){s=1;g=o=seq(m);Map(\(i)m[g<<-sample(o[g*-(s<<--s)],i)],utf8ToInt("!>)H,9)M+I!")-32)}

```

Attempt This Online!

Function that returns a list with each element containing a vector of the names from one step of the algorithm.
> 3 votes

# Answer
# Desmos, 306 bytes

Desmos doesn't have strings, so I hope this answer's valid! (Also, I only pasted half the people into it, but copying and pasting was DRIVING ME INSANE, so I just did half.)

```
C=[1...L]
Y=floor(Lrandom())
A=s(C,30,Y)
B=s(A,9,0)
D=r(40,B)
E=s(D,9,0)
F=r(25,e)
G=s(F,9,0)
H=r(45,G)
I=s(H,11,0)
J=r(41,I)
l(n,a)=shuffle(a)[[1...n]]
r(b,c)=l(b,C[[max({C[i]=c,0})fori=[1...L]]=0])
s(a,b,c)=l(b,a[{a<c,0}+{a>c,0}>0])
Z=[0,0,0]
R=join(Y,Z,A,Z,B,Z,C,Z,D,Z,E,Z,F,Z,G,Z,H,Z,I,Z,J,Z,l(1,J)[1])

```

(Pasting it in will not work, as `[` is not defined normally without typing.)

The graph contains some extra interface formatting. I only counted the stuff outside the Interface folder, as Desmos doesn't have strings and I felt that it was fair.

`l` returns `n` random elements from the list `a`. `s` is designed to remove an element of value `c` if it exists (for the first case), and `r` removes elements in a list. Then, both `c` and `r` return `b` random elements.

Click the button to the right of the plus sign to randomize it again.
> 3 votes

---
Tags: code-golf, random, algorithm
---


title: Reverse-ish a string!

text:
# Question
Title: Reverse-ish a string!
Your task: write a program/function that when given a string containing only ASCII characters, outputs/returns the string in reverse-ish.

**Example:**

1) Input

```
Hello, World!

```

2) Number unique characters in input. (Input string separated by pipes (`|`) for readability)

```
H|e|l|l|o|,| |W|o|r|l|d|!
1 2 3   4 5 6 7   8   9 10

```

3) For duplicate characters, find the first occurrence of that character and number the duplicate character with the same number as the first.

```
H|e|l|l|o|,| |W|o|r|l|d|!
1 2 3 3 4 5 6 7 4 8 3 9 10

```

4) Reverse the string, but not the numbers.

```
!|d|l|r|o|W| |,|o|l|l|e|H
1 2 3 3 4 5 6 7 4 8 3 9 10

```

5) Delete the characters above repeat numbers. (Deleted characters represented with an asterisk.)

```
!|d|l|*|o|W| |,|*|l|*|e|H
1 2 3 3 4 5 6 7 4 8 3 9 10

```

6) Replace the deleted characters with the character that appears over the first occurrence of the number that the deleted character is over.

```
!|d|l|l|o|W| |,|o|l|l|e|H
1 2 3 3 4 5 6 7 4 8 3 9 10

```

7) Output

```
!dlloW ,olleH

```

**Test cases:**

```
Input -> Output
"Hello, World!" -> "!dlloW ,olleH"
"18464399" -> "99343488"
"Code Golf" -> "floG eloC"
"abcdefgABCDEFG" -> "GFEDCBAgfedcba"
"Mmm, marshmallows" -> "swwllwmhsrwm  mms"
"15147" -> "74751"

```

# Answer
> 21 votes
# Pyth, 1 byte

```
X

```

**Verify all the test cases.**

Pyth has wonderful built-ins :-)

---

# Pyth,  ~~8~~  7 bytes

```
sm@_QxQ

```

**Verify all the test cases.**

### How it works

This is the more interesting non-built-in approach.

```
sm@_QxQ  - Full program.

 m       - Map over the input.
  @_Q    - Get the index in the reversed input.
     xQ  - Of the first index of each character in the String.
s        - Join the list.

```

# Answer
> 6 votes
# Python 2, ~~46~~ 41 bytes

<sup>-5 bytes thanks to Artyer</sup>

```
lambda x:''.join(x[~x.find(n)]for n in x)

```

Try it online!

# Answer
> 5 votes
# Jelly, 5 bytes

```
iÐ€ịṚ

```

Try it online!

# Answer
> 5 votes
## CJam, 7 bytes

```
q__W%er

```

Try it online!

### Explanation

```
q   e# Read all input.
__  e# Make two copies.
W%  e# Reverse the third copy.
er  e# Transliterate the input, mapping the input to its own reverse. Due
    e# to the way transliteration works in CJam, if a character in the source
    e# of the mapping is repeated, all but the first occurrence of that
    e# character are ignored.

```

# Answer
> 5 votes
# MATL, 6 bytes

```
PGt&m)

```

Try it online!

```
           implicit input
P          flip
 Gt        paste input back to stack and dup
   &m      alternate ismember, returns duplicated indices
     )     apply indices to the reversed char array
           implicit output, print as char

```

# Answer
> 5 votes
# 05AB1E, 2 bytes

```
R‡

```

Try it online!

Explanation:

```
R‡
R  Reverse input
 ‡ Transliterate the input with itself and its reverse (as above) (it only keeps first occurrences)

```

# Answer
> 3 votes
## Alice, 17 bytes

```
/?.R?y.@
\i.!yDo/

```

Try it online!

### Explanation

```
/...@
\.../

```

This is just the usual template for linear code in Ordinal mode. If we unfold this, the actual program simply becomes:

```
i.!?D.?.Ryyo

```

The idea here is similar to that of my CJam answer. Since Alice has no easy way of indexing into strings with integers, it's easiest to replicate this behaviour with transliteration (`y` in Alice). However, Alice's transliteration semantics are a lot more general than CJam's, which means that Alice doesn't just disregard repeated mappings. For example, if we just wanted to transliterate `Mmm, marshmallows` to its reverse, this would represent the following list of mappings:

```
M -> s
m -> w
m -> o
, -> l
  -> l
m -> a
a -> m
r -> h
s -> s
h -> r
m -> a
a -> m
l ->
l -> ,
o -> m
w -> m
s -> M

```

Note that we've got, for example, `m -> w`, `m -> o`, `m -> a` and `m -> a`. CJam would just discard all except the first mapping, but Alice would instead cycle through these. So the first `m` would be mapped to `w`, the second to `o`, the fifth again to `w` and so on. In this case that isn't helpful, because in general if we perform `y` on `AAB` (for some strings `A` and `B`) as we did in CJam, we'll always just get `B` in Alice.

So how do we compute a mapping that works for `y` (i.e. how do we discard the repeated mappings manually)? Of course, by using another transliteration. :)

The source of the mapping we want has to be the nub of the input (i.e. the deduplicated input). If we apply the above mapping to the nub, then each character only appears once, so we're only making use of the first of each of the repeated mappings. So by transliterating the nub with the input and its reverse, we're effectively simply discarding the duplicated mappings. We can then use the nub and this new result as a mapping for the original input. I'm sure that made sense to someone...

So the code:

```
i   Read input.                   ["Mmm, marshmallows"]
.!  Store a copy on the tape.
?D  Push the nub of the input.    ["Mmm, marshmallows" "Mm, arshlow"]
.   Duplicate.                    ["Mmm, marshmallows" "Mm, arshlow" "Mm, arshlow"]
?   Retrieve input.               ["Mmm, marshmallows" "Mm, arshlow" "Mm, arshlow" "Mmm, marshmallows"]
.R  Push its reverse.             ["Mmm, marshmallows" "Mm, arshlow" "Mm, arshlow" "Mmm, marshmallows" "swollamhsram ,mmM"]
y   Transliterate.                ["Mmm, marshmallows" "Mm, arshlow" "swllmhsr mm"]]
y   Transliterate.                ["swwllwmhsrwm  mms"]
o   Output.                       []

```

# Answer
> 3 votes
# JavaScript ES6 50 bytes

3 bytes saved thanks to Justin Mariner

```
s=>[...s].map(x=>s.slice(~s.indexOf(x))[0]).join``

```

### Test it:

```
f=s=>s.split``.map(x=>s.slice(~s.indexOf(x))[0]).join``

let inp = document.getElementById("inp");
let out = document.getElementById("out");

function change() {
  out.innerText = f(inp.value);
}

change();
```

```
<input id="inp" type="text" oninput="change()" value="Hello, World!" /><br>
<p id="out"></p>
```

# Answer
> 3 votes
# Pyke, 7 bytes

```
L@Q_M@s

```

Try it here!

```
L@      - Get the index of the first index of each character.
  Q     - Push the input to the stack.
   _    - Reverse it.
    M@  - Get the element at (each) position in ^^^ in ^.
      s - Join.

```

# Answer
> 3 votes
# Perl 5, 23 + 1 (`-p`) = 24 bytes

```
eval"y/$_/".reverse."/"

```

Try it online!

*Thanks to @MartinEnder's Alice entry for the transliteration idea*

# Answer
> 2 votes
# , ~~68~~ 65 bytes

```
function(s)chartr(paste(rev(el(strsplit(s,''))),collapse=''),s,s)

```

Verify test cases!

Ports Erik's 05AB1E method for 3 bytes less. It wasn't the first, but it was the first one I saw.

## old version:

```
function(s)paste(rev(s<-el(strsplit(s,'')))[match(s,s)],collapse='')

```

Verify all test cases -- prints out the vector with the input as names and the output in quotes below.

A fairly naive implementation, but I don't think this gets shorter in R (and I look forward to being wrong about that). It's essentially an R port of Rod's python answer but it was developed independently.

Ungolfed explanation:

```
function(s){
 s <- el(strsplit(s,''))      # string to characters
 r <- rev(s)                  # reverse s
 idx <- match(s,s)            # indices of first matches
 r <- r[idx]                  # do the replacement of duplicates
 paste(r, collapse = "")      # characters to string
}                             # implicit return of last evaluated statement

```

# Answer
> 2 votes
# C (gcc), 98 bytes

```
i,n,a[256];char*f(char*c){n=strlen(c);for(i=n;i>0;i--)a[c[i-1]]=c[n-i];for(;i<n;i++)c[i]=a[c[i]];}

```

Try it online!

Argument must be a modifiable string; string is modified in-place.

# Answer
> 2 votes
# Java 10, ~~100~~ ~~99~~ 97 bytes

```
s->{var a=new char[256];int l=s.length,i=l;for(;i>0;a[s[--i]]=s[l+~i]);for(;i<l;s[i]=a[s[i++]]);}

```

Port of @LeakyNun's C answer. I doubt it can be done shorter without doing something similar in Java.
-1 byte thanks to *@ceilingcat*.

Input as `char[]` (character-array), and modifies this input instead of returning a new one to save bytes.

Try it here.

# Answer
> 2 votes
# Vyxal, 3 bytes

```
Ṙ$Ŀ

```

Try it Online!

# Answer
> 1 votes
# Röda, 27 bytes

```
f x{x|[x[-1-indexOf(_,x)]]}

```

Try it online!

This takes a list of characters as input and returns a stream of characters.

Using string datatype (40 bytes):

```
f x{x=x/""x|[x[-1-indexOf(_,x)]]|concat}

```

Try it online!

# Answer
> 1 votes
# Arturo, 39 bytes

```
$->s->map s'n->s\[dec-size s index s n]

```

Try it

# Answer
> 0 votes
# Scala, 61 bytes

Try it online!

```
def f(x:String)=x.map(c=>x(x.length-1-x.indexOf(c))).mkString

```

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


# Question
Title: Am I divisible by double the sum of my digits?
Given a *positive* integer as input, your task is to output a truthy value if the number is divisible by the double of the sum of its digits, and a falsy value otherwise (OEIS A134516). In other words:

```
(sum_of_digits)*2 | number

```
* Instead of truthy / falsy values for the true and false cases, you may instead specify any finite set of values for the true/false case, and their complement the other values. For a simple example, you may use `0` for the true case and all other numbers for the false case (or vice versa, if you like).
* Standard input and output rules apply. Default Loopholes also apply.
* You can take input as an integer or as the string representation of that integer.
* This is , hence the shortest code in bytes wins!
* I am new to PPCG, so I would like you to post an explanation if it's possible.

---

# Test Cases

```
Input - Output - (Reason)

80  - Truthy - (16 divides 80)
100 - Truthy - (2 divides 100)
60  - Truthy - (12 divides 60)
18 - Truthy - (18 divides 18)
12 - Truthy - (6 divides 12)

4 - Falsy - (8 does not divide 4)
8 - Falsy - (16 does not divide 8)
16  - Falsy  - (14 does not divide 16)
21 - Falsy - (6 does not divide 21)
78  - Falsy  - (30 does not divide 78)
110 - Falsy - (4 does not dide 110)
111 - Falsy - (6 does not divide 111)
390 - Falsy  - (24 does not divide 390)

```

# Answer
# Neim, 3 bytes

Explanation:

```
      Implicitly convert to int array and sum the digits
 ᚫ     Double
     Is it a divisor of the input?

```

Try it online!

Detailed version
> 9 votes

# Answer
## JavaScript (ES6), ~~31~~ ~~29~~ 27 bytes

Takes input as a string. Returns zero for truthy and non-zero for falsy.

```
n=>n%eval([...n+n].join`+`)

```

### Commented

```
n => n % eval([...n + n].join`+`)
n =>                                   // take input string n  -> e.g. "80"
                  n + n                // double the input     -> "8080"
              [...     ]               // split                -> ["8", "0", "8", "0"]
                        .join`+`       // join with '+'        -> "8+0+8+0"
         eval(                  )      // evaluate as JS       -> 16
     n %                               // compute n % result   -> 80 % 16 -> 0

```

### Test cases

```
let f =

n=>n%eval([...n+n].join`+`)

console.log('[Truthy]');
console.log(f("80"))
console.log(f("100"))
console.log(f("60"))
console.log(f("18"))
console.log(f("12"))

console.log('[Falsy]');
console.log(f("4"))
console.log(f("8"))
console.log(f("16"))
console.log(f("21"))
console.log(f("78"))
console.log(f("110"))
console.log(f("111"))
console.log(f("390"))
```
> 15 votes

# Answer
# C#, 46 bytes

```
using System.Linq;n=>n%(n+"").Sum(c=>c-48)*2<1

```

Full/Formatted version:

```
using System;
using System.Linq;

class P
{
    static void Main()
    {
        Func<int, bool> f = n => n % (n + "").Sum(c => c - 48) * 2 < 1;

        Console.WriteLine(f(80));
        Console.WriteLine(f(100));
        Console.WriteLine(f(60));

        Console.WriteLine();

        Console.WriteLine(f(16));
        Console.WriteLine(f(78));
        Console.WriteLine(f(390));

        Console.ReadLine();
    }
}

```
> 7 votes

# Answer
# Retina, ~~38~~ 27 bytes

-11 bytes and fixed an error with the code thanks to @MartinEnder

```
$
$_¶$_
.+$|.
$*
^(.+)¶\1+$

```

Try it online!

Prints 1 if divisible, 0 otherwise

### Explanation (hope I got this right)

```
$
$_¶$_

```

Appends the entire input, plus a newline, plus the input again

```
.+$|.
$*

```

Converts each match to unary (either the entire second line which is the original input, or each digit in the first line)

```
^(.+)¶\1+$

```

Check if the first line (the doubled digit sum) is a divisor of the second line
> 5 votes

# Answer
# x86-64 Machine Code, 24 bytes

```
6A 0A 5E 31 C9 89 F8 99 F7 F6 01 D1 85 C0 75 F7 8D 04 09 99 F7 F7 92 C3

```

The above code defines a function in 64-bit x86 machine code that determines whether the input value is divisible by double the sum of its digits. The function conforms to the System V AMD64 calling convention, so that it is callable from virtually any language, just as if it were a C function.

It takes a single parameter as input via the `EDI` register, as per the calling convention, which is the integer to test. (This is assumed to be a *positive* integer, consistent with the challenge rules, and is required for the `CDQ` instruction we use to work correctly.)

It returns its result in the `EAX` register, again, as per the calling convention. The result will be 0 if the input value *was* divisible by the sum of its digits, and non-zero otherwise. (Basically, an inverse Boolean, exactly like the example given in the challenge rules.)

Its C prototype would be:

```
int DivisibleByDoubleSumOfDigits(int value);

```

Here are the ungolfed assembly language instructions, annotated with a brief explanation of the purpose of each instruction:

```
; EDI == input value
DivisibleByDoubleSumOfDigits:
   push 10
   pop  rsi             ; ESI <= 10
   xor  ecx, ecx        ; ECX <= 0
   mov  eax, edi        ; EAX <= EDI (make copy of input)

SumDigits:
   cdq                  ; EDX <= 0
   div  esi             ; EDX:EAX / 10
   add  ecx, edx        ; ECX += remainder (EDX)
   test eax, eax
   jnz  SumDigits       ; loop while EAX != 0

   lea  eax, [rcx+rcx]  ; EAX <= (ECX * 2)
   cdq                  ; EDX <= 0
   div  edi             ; EDX:EAX / input
   xchg edx, eax        ; put remainder (EDX) in EAX
   ret                  ; return, with result in EAX

```

In the first block, we do some preliminary initialization of registers:

* `PUSH`+`POP` instructions are used as a slow but short way to initialize `ESI` to 10. This is necessary because the `DIV` instruction on x86 requires a register operand. (There is no form that divides by an immediate value of, say, 10.)
* `XOR` is used as a short and fast way to clear the `ECX` register. This register will serve as the "accumulator" inside of the upcoming loop.
* Finally, a copy of the input value (from `EDI`) is made, and stored in `EAX`, which will be clobbered as we go through the loop.

Then, we start looping and summing the digits in the input value. This is based on the x86 `DIV` instruction, which divides `EDX:EAX` by its operand, and returns the quotient in `EAX` and the remainder in `EDX`. What we'll do here is divide the input value by 10, such that the remainder is the digit in the last place (which we'll add to our accumulator register, `ECX`), and the quotient is the remaining digits.

* The `CDQ` instruction is a short way of setting `EDX` to 0. It actually *sign-extends* the value in `EAX` to `EDX:EAX`, which is what `DIV` uses as the dividend. We don't actually need sign-extension here, because the input value is unsigned, but `CDQ` is 1 byte, as opposed to using `XOR` to clear `EDX`, which would be 2 bytes.
* Then we `DIV`ide `EDX:EAX` by `ESI` (10).
* The remainder (`EDX`) is added to the accumulator (`ECX`).
* The `EAX` register (the quotient) is tested to see if it is equal to 0. If so, we have made it through all of the digits and we fall through. If not, we still have more digits to sum, so we go back to the top of the loop.

Finally, after the loop is finished, we implement `number % ((sum_of_digits)*2)`:

* The `LEA` instruction is used as a short way to multiply `ECX` by 2 (or, equivalently, add `ECX` to itself), and store the result in a different register (in this case, `EAX`).

(We could also have done `add ecx, ecx`+`xchg ecx, eax`; both are 3 bytes, but the `LEA` instruction is faster and more typical.)
* Then, we do a `CDQ` again to prepare for division. Because `EAX` will be positive (i.e., unsigned), this has the effect of zeroing `EDX`, just as before.
* Next is the division, this time dividing `EDX:EAX` by the input value (an unmolested copy of which still resides in `EDI`). This is equivalent to modulo, with the remainder in `EDX`. (The quotient is also put in `EAX`, but we don't need it.)
* Finally, we `XCHG` (exchange) the contents of `EAX` and `EDX`. Normally, you would do a `MOV` here, but `XCHG` is only 1 byte (albeit slower). Because `EDX` contains the remainder after the division, it will be 0 if the value was evenly divisible or non-zero otherwise. Thus, when we `RET`urn, `EAX` (the result) is 0 if the input value was divisible by double the sum of its digits, or non-zero otherwise.

Hopefully that suffices for an explanation.
This isn't the shortest entry, but hey, it looks like it beats almost all of the non-golfing languages! :-)
> 5 votes

# Answer
# 05AB1E, ~~5~~ 4 bytes

-1 byte thanks to Okx

```
SO·Ö

```

Try it online!

You can also remove the last Ö to get 0 for truthy and something else for falsy resulting in only 3 bytes but to me that just doesn't seem to appropriately fit the definition.

### Explanation

```
SO·Ö
SO    # Separate the digits and sum them
  ·   # Multiply the result by two
   Ö  # Is the input divisible by the result?

```
> 4 votes

# Answer
# MATL, 7 bytes

```
tV!UsE\

```

Outputs `0` if divisible, positive integer otherwise. Specifically, it outputs the remainder of dividing the number by twice the sum of its digits.

**Try it online!**

### Explanation

```
t   % Implicit input. Duplicate
V!U % Convert to string, transpose, convert to number: gives column vector of digits
s   % Sum
E   % Times 2
\   % Modulus. Implicit display

```
> 4 votes

# Answer
# K (ngn/k), ~~15~~ 14 bytes

```
{(2*+/10\x)!x}

```

Try it online!

---

0 is truthy
> 4 votes

# Answer
# Japt, ~~7~~ 4 bytes

Takes input as a string. Outputs `0` for `true` or a number greater than `0` for `false`, which, from other solutions, would appear to be valid. If not, let me know and I'll rollback.

```
%²¬x

```

Test it

---

## Explanation

Implicit input of string `U`.
`"390"`

```
²

```

Repeat `U` twice.
`"390390"`

```
¬

```

Split to array of individual characters.
`["3","9","0","3","9","0"]`

```
x

```

Reduce by summing, automatically casting each character to an integer in the process.
`24`

```
%

```

Get the remainder of dividing `U` by the result, also automatically casting `U` to an integer in the process. Implicitly output the resulting integer.
`6 (=false)`
> 3 votes

# Answer
# C89, 55 53 bytes

(Thanks to Steadybox!

```
s,t;f(x){for(t=x,s=0;t;t/=10)s+=t%10;return x%(s*2);}

```

It takes a single input, `x`, which is the value to test. It returns 0 if `x` is evenly divisible by double the sum of its digits, or non-zero otherwise.

Try it online!

**Ungolfed:**

```
/* int */ s, t;
/*int */ f(/* int */ x)
{
    for (t = x, s = 0; t /* != 0 */; t /= 10)
        s += (t % 10);
    return x % (s * 2);
}

```

As you can see, this takes advantage of C89's implicit-int rules. The global variables `s` and `t` are implicitly declared as `int`s. (They're also implicitly initialized to 0 because they are globals, but we can't take advantage of this if we want the function to be callable multiple times.)

Similarly, the function, `f`, takes a single parameter, `x,` which is implicitly an `int`, and it returns an `int`.

The code inside of the function is fairly straightforward, although the `for` loop will look awfully strange if you're unfamiliar with the syntax. Basically, a `for` loop header in C contains three parts:

```
for (initialization; loop condition; increment)

```

In the "initialization" section, we've initialized our global variables. This will run once, before the loop is entered.

In the "loop condition" section, we've specified on what condition the loop should continue. This much should be obvious.

In the "increment" section, we've basically put arbitrary code, since this will run at the end of every loop.

The larger purpose of the loop is to iterate through each digit in the input value, adding them to `s`. Finally, after the loop has finished, `s` is doubled and taken modulo `x` to see if it is evenly divisible. (A better, more detailed explanation of the logic here can be found in my other answer, on which this one is based.)

**Human-readable version:**

```
int f(int x)
{
    int temp = x;
    int sum  = 0;
    while (temp > 0)
    {
        sum  += temp % 10;
        temp /= 10;
    }
    return x % (sum * 2);
}

```
> 3 votes

# Answer
# APL, 13 bytes

```
{⍵|⍨2×+/⍎¨⍕⍵}

```

Outputs `0` as a truthy value, and any other as falsy.
> 3 votes

# Answer
# Brachylog, 8 bytes

```
ẹ+×₂;I×?

```

Try it online!

### Explanation

```
ẹ+           Sum the digits
  ×₂         Double
    ;I×?     There is an integer I such that I×(double of the sum) = Input

```
> 2 votes

# Answer
# Python 2, ~~34~~ 32 bytes

*-2 bytes thanks to @Rod*

```
lambda n:n%sum(map(int,`n`)*2)<1

```

Try it online!
> 2 votes

# Answer
## Mathematica, 26 bytes

```
(2Tr@IntegerDigits@#)∣#&

```

No clue why  has a higher precedence than multiplication...
> 2 votes

# Answer
# PHP, 41 bytes

prints zero if divisible, positive integer otherwise.

```
<?=$argn%(2*array_sum(str_split($argn)));

```

Try it online!
> 2 votes

# Answer
# Excel, 63 bytes

```
=MOD(A1,2*SUMPRODUCT(--MID(A1,ROW(OFFSET(A$1,,,LEN(A1))),1)))=0

```

Summing digits is the lengthy bit.
> 2 votes

# Answer
# Perl 6, 19 bytes

```
{$_%%(2*.comb.sum)}

```

Try it online!
> 2 votes

# Answer
## Husk, ~~9~~ 8 bytes

*Thanks to Leo for saving 1 byte.*

```
Ṡ¦ȯ*2ṁis

```

Try it online!

### Explanation

```
Ṡ¦ȯ         Test whether f(x) divides x, where f is the function obtained by
            composing the next 4 functions.
       s    Convert x to a string.
     ṁi     Convert each character to an integer and sum the result.
   *2       Double the result.

```
> 2 votes

# Answer
## Haskell, ~~38~~ ~~37~~ 42 bytes

*Thanks to Zgarb for golfing off 1 byte*

```
f x=read x`mod`foldr((+).(*2).read.pure)0x

```

Try it online!

Takes input as a string; returns 0 if divisible and nonzero otherwise.
> 2 votes

# Answer
# TI-BASIC, ~~27~~ ~~26~~ 21 bytes

-5 thanks to @Oki

```
:fPart(Ans/sum(2int(10fPart(Ans10^(~randIntNoRep(1,1+int(log(Ans

```

This is made trickier by the fact that there is no concise way to sum integer digits in **TI-BASIC**. Returns `0` for `True`, and a different number for `False`.

Explanation:

```
:fPart(Ans/sum(2int(10fPart(Ans10^(-randIntNoRep(1,1+int(log(Ans
                               10^(-randIntNoRep(1,1+int(log(Ans #Create a list of negative powers of ten, based off the length of the input, i.e. {1,0.1,0.01}
                            Ans                                  #Scalar multiply the input into the list
                    10fPart(                                     #Remove everything left of the decimal point and multiply by 10
               2int(                                             #Remove everything right of the decimal point and multiply by 2
           sum(                                                  #Sum the resulting list
       Ans/                                                      #Divide the input by the sum
:fPart(                                                          #Remove everything left of the decimal, implicit print

```
> 2 votes

# Answer
## Python 3, 35 bytes

```
lambda a:a%(sum(map(int,str(a)))*2)

```
> 2 votes

# Answer
# Java (OpenJDK 8), 40 bytes

```
i->i%(i+"").chars().map(k->k*2-96).sum()

```

Try it online!

Returns 0 as truthy value and a value greater than 0 as falsy value.
> 2 votes

# Answer
# Add++, 11 bytes

```
L,EDEs;A@%!

```

Try it online!

First time I've used either a `L`ambda or `;` in an Add++ answer

## How it works

```
L,   - Create a lambda function. Example argument; 172
  ED - Push the digits;   STACK = [[1 7 2]]
  Es - Stack-clean sum;   STACK = [10]
  ;  - Double;            STACK = [20]
  A  - Push the argument; STACK = [20 172]
  @% - Modulo;            STACK = [12]
  !  - Logical NOT;       STACK = [0]

```
> 2 votes

# Answer
# Husk, ~~6~~ 5 bytes

```
¦DΣd¹

```

Try it online!

-1 byte from Dominic Van Essen.

The existing answer doesn't use enough builtins, and Martin Ender is inactive, so I decided to post this.
> 2 votes

# Answer
# Zsh, 37 bytes

```
for ((;i++<19;a+=2*s[i]))s=$1;((s%a))

```

Try it online!

Outputs by exit code - 0 is falsey, 1 is truthy.

Explanation:

```
for ((;i++<19;a+=2*s[i]))s=$1;((s%a))    # i implicitly starts at 0
                         s=$1;           # set s to the input
for ((;                ))                # loop
          <19;                           #  while i is less than 19 (*)
       i++                               #  increment i
                   s[i]                  #  take the i'th character of s
                 2*                      #  doubled
              a+=                        #  add to a
                                s%a      # remainder of s divided by a
                              ((   ))    # output 0 if it's non-zero, 1 if it's zero

```

*(\*19 is the length of the maximum integer zsh can handle)*
> 2 votes

# Answer
# Swift, ~~53~~ 46 bytes

Takes in a `String` or `Substring` representing an integer in \[1, 255\].

```
{UInt8($0)!%($0.utf8.reduce(0){$0+$1-48}*2)<1}

```

Try it online!

Type information not included, since it could be either:

```
let f: (String) -> Bool = {UInt8($0)!%($0.utf8.reduce(0){$0+$1-48}*2)<1}
let g: (Substring) -> Bool = {UInt8($0)!%($0.utf8.reduce(0){$0+$1-48}*2)<1}

```

Swift `Character` is... weird. It's not a single byte, like in C (that's `CChar`), but it's also not a single Unicode codepoint (that's `Unicode.Scalar`). Rather, it represents an extended grapheme cluster. This makes certain oprations substantially more painful, but others substantially easier. For this reason, I access the string's `utf8` property (which is a collection of `UInt8`).

`String` and `Substring` are collections of `Character`; however, they also have a lot more shared functionality than e.g. `[Character]` because they conform to `StringProtocol`, and are in fact the only types that conform to it. I thought `StringProtocol` would work as the input type, but then the type checker times out.

For 49 bytes, here's a version that accepts integers in \[1, 2^31 - 1\] or \[1, 2^63 - 1\] depending on the machine:

```
{Int($0)!%($0.utf8.reduce(0){$0+Int($1)-48}*2)<1}

```

### Explanation/Ungolfed

```
{ (number: String) -> Bool in
    return
        UInt8(number)! // Convert String to UInt8, force-unwrap optional
            % (
                number.utf8 // Convert String to byte array
                    .reduce(0) { (prevResult: UInt8, nextChar: Character) -> UInt8 in
                        return prevResult + nextChar - 48
                        // Convert ASCII to number by subtracting 48; sum the results
                    } * 2
            ) == 0 // convert number to boolean
}

```
> 2 votes

# Answer
# Braingolf, ~~13~~ 12 bytes

```
VR.Mvd&+2*c%

```

Try it online!

Outputs 0 for truthy, any other number for falsey.

## Explanation

```
VR.Mvd&+2*c%  Implicit input from command-line args
VR            Create stack2, return to stack1
  .M          Duplicate input to stack2
    vd        Switch to stack2, split into digits
      &+      Sum up all digits
        2*    Double
          c   Collapse stack2 back into stack1
           %  Modulus
              Implicit output of last item on stack

```
> 1 votes

# Answer
# Java, 66 bytes

-1 byte thanks to Olivier

```
a->{int i=0;for(int b:(""+a).getBytes())i+=b-48;return a%(i*2)<1;}

```

Ungolfed & explanation:

```
a -> {
    int i = 0;

    for(int b : (""+a).getBytes()) { // Loop through each byte of the input converted to a string
        i += b-48; // Subtract 48 from the byte and add it to i
    }

    return a % (i*2) < 1 // Check if a % (i*2) is equal to one
    // I use <1 here for golfing, as the result of a modulus operation should never be less than 0
}

```
> 1 votes

# Answer
# Japt, 7 bytes

```
vUì x*2

```

Returns `1` for `true`, `0` for `false`

Try it online!

## Explanation

```
vUì x*2
v        // Return 1 if the input is divisible by:
 Uì      //   Input split into a base-10 array
    x    //   Sum the array
     *2  //   While mapped by *2

```
> 1 votes

# Answer
# Haskell, 49 Bytes

```
f x=(==) 0.mod x.(*)2.sum.map(read.return).show$x

```

**Usage**

```
f 80

```

Try it online!
> 1 votes

# Answer
# J, 15 bytes

0 indicates truthy, nonzero indicates falsy.

```
|~[:+/2#"."0@":

```

Explanation

```
        "."0@":  convert to list of digits
  [:+/2#         sum 2 copies of the list ([: forces monadic phrase)
|~               residue of sum divided by argument?

```
> 1 votes

# Answer
# Ohm, 5 bytes

```
D}Σd¥

```

Try it online!
> 1 votes

# Answer
# tcl, 45

```
puts [expr 1>$n%(2*([join [split $n ""] +]))]

```

# demo
> 1 votes

# Answer
## PowerShell, 39 bytes

```
($a="$args")%($a*2-replace'\B','+'|iex)

```

0 as Truthy output, any other number as Falsey.

```
PS D:\> D:\t.ps1 80
0

PS D:\> D:\t.ps1 81
9

```

It takes the args array as a string, does string multiplication to double all the digits, regex-replaces non-word-boundaries to make '8+0+8+0', eval's that to get the sum, and calculates a remainder of original/sum.
> 1 votes

# Answer
# Haskell, 35 34 bytes

```
f x=mod x$2*sum[read[c]|c<-show x]

```

Try it online!

Returns '0' in the true case, the remainder otherwise.

# Haskell, pointfree edition by nimi, 34 bytes

```
mod<*>(2*).sum.map(read.pure).show

```

Try it online!
> 1 votes

# Answer
# Mini-Flak, ~~296~~ 292 bytes

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

```

Try it online!

The TIO link have more comments from me, so it is partially easier to read.

Truthy/Falsey: Truthy (divisible) if the second number is equal to the third number, falsy otherwise. So both the truthy and falsy set are infinite, but I suppose that should be allowed. +10 byte if that is not.

Note: Leading/trailing newlines/whitespaces are not allowed in input.
> 1 votes

# Answer
# Java (OpenJDK 8), ~~55~~ 53 bytes

```
a->{int i=0,x=a;for(;x>0;x/=10)i+=x%10*2;return a%i;}

```

Try it online!

A return value of `0` means truthy, anything else means falsy.

Since my comment in Okx's answer made no ripple, I deleted it and posted it as this answer, golfed even a bit more.

Further golfing thanks to @KrzysztofCichocki and @Laikoni who rightfully showed me I needn't answer a truthy/falsy value, but any value as long as I describe the result.
> 1 votes

# Answer
# PHP, 44 bytes

```
for(;~$d=$argn[$i++];)$t+=2*$d;echo$argn%$t;

```

Run like this:

```
echo 80 | php -nR 'for(;~$d=$argn[$i++];)$t+=2*$d;echo$argn%$t;'

```

# Explanation

Iterates over the digits to compute the total, then outputs the modulo like most answers.
> 1 votes

# Answer
# C# (.NET Core), 51 bytes

```
n=>{int l=n,k=0;for(;l>0;l/=10)k+=l%10;return n%k;}

```

Try it online!

0 for truthy, anything else for falsey.
> 1 votes

# Answer
# Perl 5, 21 + 1 (-p) = 22 bytes

```
$_%=eval s/./+2*$&/rg

```

Try it online!
> 1 votes

# Answer
# Ly, 10 bytes

```
nsS&+2*lf%

```

Try it online!

Ly is lucky enough to have a splitting built-in.

Returns 0 for truthy and a number greater than 0 for falsy.
> 1 votes

# Answer
# Pyth - 12 Bytes

```
%sZ*2ssMscZ1

```

Explanation:

```
%       - implicitly print modulus of
 s      - parse int
  Z     - input
 *      - two times
  s    - sum of
   M   - map
    s  - parse int to
    c  - substrings
     Z - of input
     1 - of length 1

```
> 1 votes

# Answer
# Befunge-93, 34 bytes

```
p&::v>0g2*%.@
+19:_^#:/+91p00+g00%

```

Try it online!

Prints 0 for truthy, a different integer for falsey.
> 1 votes

# Answer
# Brachylog, 7 bytes

```
f.&ẹj+∈

```

Try it online!

The predicate succeeds if the input is divisible by twice the sum of its digits, and fails otherwise. Run as a program, success prints `true.` and failure prints `false.`.

This started off as a minor edit to Fatalize's answer, golfing a byte off by replacing `+×₂` with `j+`, but as I was testing it I noticed that one or another of the updates he's made to the language in the last year and a half seems to have broken his solution on the case of 18, with `I` apparently being unable to assume the value of 1, so I ended up having to restructure it somewhat (fortunately without changing the byte count).

```
f.         The output variable is a list of the input's factors.
  &        And,
   ẹ       the digits of the input,
    j      all duplicated,
     +     sum up to
      ∈    a member of the output variable.

```
> 1 votes

# Answer
# Runic Enchantments, 11 bytes

```
i:'+A2*%0=@

```

Try it online!

### Explanation

```
i:             Read input, duplicate it
  '+A          Sum its digits
     2*        Multiply by 2
       %       Modulo input with digit sum
        0=     Compare to 0
          @    Print and terminate

```
> 1 votes

# Answer
# Forth (gforth), 58 bytes

```
: f 0 over begin 10 /mod >r + r> ?dup 0= until 2* mod 0= ;

```

Try it online!

### Code Explanation

```
: f           \ start a new word definition
  0 over      \ create an accumulator and copy the input above it on the stack
  begin       \ start an indefinite loop
    10 /mod   \ divide by 10 and get quotient and remainder
    >r + r>   \ add remainder to accumulator
    ?dup      \ duplicate the quotient if it's greater than 0
    0=        \ check if quotient is 0
  until       \ end the indefinite loop if it is
  2* mod      \ multiply result by 2, then modulo with input number
  0=          \ check if result is 0 (input is divisible by result)
;             \ end word definition

```
> 1 votes

# Answer
## Keg+Reg, 11 bytes

Boring algorithm.

```
¿:;9%1+2*%

```

Finds the digital root of the top of the stack and then finds the remainder.

0 is a truthy value, any value that is not 0 is a falsy value. (Including ASCII characters)

## Explanation (Syntactically invalid)

```
¿#         Integer input
 :#        Duplicate
  ;9%1+#   Digital Root Formula (1+(n-1)mod 9)
       2*%#Multiply by 2 and find the remainder

```

I believe everyone here used repetition/reduction but not an existing formula.
> 1 votes

# Answer
# Vyxal, 3 bytes

```
∑dœ

```

Try it Online!

Compiles as:

```
stack.push(summate(stack.pop()))
stack.push(stack.pop() * 2)
lhs, rhs = stack.pop(2); stack.push(int((rhs % lhs) == 0))

```

## Explained

```
∑dœ
∑   # Push the sum of the integers of the input
 d  # Double that sum
  œ # And push ((sum(input) * 2) % input) == 0

```
> 1 votes

# Answer
# MathGolf, 3 bytes

```
Σ∞÷

```

Try it online.

**Explanation:**

```
Σ    # Get the digit-sum of the (implicit) input-integer
 ∞   # Double it
  ÷  # Check if the (implicit) input-integer is divisible by this value
     # (after which the entire stack is output implicitly as result)

```
> 1 votes

# Answer
# Whitespace, 103 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input][N
S S N
_Create_Label_LOOP][S N
S _Duplicate][N
T   S S N
_If_0_Jump_to_Label_DONE][S N
S _Duplicate][S S S T   S T S N
_Push_10][T S T T   _Modulo][S T    S S T   S N
_Copy_0-based_2nd][T    S S S _Add][S N
T   _Swap_top_two][S S S T  S T S N
_Push_10][T S T S _Integer_divide][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_DONE][T   T   T   _Retrieve_input][S N
T   _Swap_top_two][S S S T  S N
_Push_2][T  S S N
_Multiply]{T    S T T   _Modulo][T  N
S T _Print_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Outputs `0` as truthy or a positive integer as falsey.

**Try it online** (with raw spaces, tabs and new-lines only).

To output two distinct values (`0` for truthy; `1` for falsey) it would be **128 bytes** instead: try it online.

**Explanation in pseudo-code:**

```
Integer sum = 0
Integer input = STDIN as integer
Integer n = input
Start LOOP:
  If(n == 0):
    Jump to Label DONE
  Integer t = n modulo-10
  sum = sum + t
  n = n integer-divided by 10
  Go to next iteration of LOOP

DONE:
  sum = sum * 2
  Integer result = input % sum
  Print result as integer to STDOUT

```
> 1 votes

# Answer
# Factor \+ `math.text.utils math.unicode`, 37 bytes

```
[ dup 1 digit-groups Σ 2 * mod 0 = ]

```

Try it online!

## Explanation

```
                ! 12
dup             ! 12 12
1 digit-groups  ! 12 { 2 1 }
Σ               ! 12 3
2 *             ! 12 6
mod             ! 0
0 =             ! t

```
> 1 votes

# Answer
# Vyxal, 3 bytes

```
∑dḊ

```

Try it Online!
> 1 votes

# Answer
# C++, 121 bytes

```
#include<iostream>
main(){std::string n;int m=0;std::cin>>n;for(char i:n){m+=i-48;};std::cout<<((stoi(n)%(m*2)==0)?0:1);}

```

Try it online!

# Explanation

```
#include<iostream>
main(){
  std::string n; int m = 0; // Initialize `n` (input) and `m` (sum)
  std::cin >> n; // Get input
  for(char i:n) // Loop through input to calculate the sum of digits
  {
    m+=i-48;
  };
  std::cout<<((stoi(n)%(m*2)==0)?0:1); // Output `0` if double the sum of digits is divisible by the number, else return `1`
}

```
> 1 votes

# Answer
# Desmos, 62 bytes

```
f(n)=0^{mod(n,2mod(floor(n/10^{[0...floor(logn)]}),10).total)}

```

Try It Online!

Try It Online! - Prettified
> 1 votes

# Answer
# Knight, 39 bytes

```
;=n!=p=sE P;Ws;=n+*2%s 10n=s/s 10O!%p n

```

Try it online!

Test Suite
> 1 votes

# Answer
# Arturo, 21 bytes

```
$->n->n%2*∑digits n

```

Try it

Returns 0 for true or any other number for false.
> 1 votes

# Answer
# Thunno 2, 3 bytes

```
SḌḊ

```

#### Explanation

```
SḌḊ   # implicit input
S     # sum the digits
 Ḍ    # double this number
  Ḋ   # input is divisible by this?
      # implicit output

```

#### Screenshot
> 1 votes

# Answer
# Lua, 47 bytes

```
n=...a=0n:gsub('.',load'a=2*...+a')print(n%a<1)

```

Try it online!
> 1 votes

# Answer
# Jelly, 4 bytes

```
DSḤḍ

```

Try it online!

Explanation:

```
DSḤḍ Takes an integer as input.
D    Get digits (convert to base 10)
 S   Sum
  Ḥ  Unhalve (double)
   ḍ Check if y (the input itself) is divisible by x

```
> 0 votes

# Answer
# Pari/GP, 24 bytes

```
n->!(n%(2*sumdigits(n)))

```

Try it online!
> 0 votes

# Answer
# jq, 37 characters

```
.%(tostring/""|map(tonumber)|add*2)<1

```

Sample run:

```
bash-4.4$ jq '.%(tostring/""|map(tonumber)|add*2)<1' <<< '60'
true

bash-4.4$ jq '.%(tostring/""|map(tonumber)|add*2)<1' <<< '390'
false

```

Try on jp‣play
> 0 votes

# Answer
# CJam, ~~11~~ 10 bytes

*1 byte saved thanks to @Challenger5*

```
{_Ab:+2*%}

```

Anonymous block that takes the input from the stack and replaces it by the output, which is `0` if divisible or a positive integer otherwise.

Try it online! Or verify all test cases.

### Explanation

```
{        }   e# Block
 _           e# Duplicate
  Ab         e# Convert to base 10. Gives an array of digits
    :+       e# Fold addition over array
      2*     e# Multiply by 2
        %    e# Modulus

```
> 0 votes

# Answer
# Bash + coreutils + bc, 46 bytes

```
yes $1%\(0`echo $1|sed 's/\(.\)/+\1*2/g'`\)|bc

```

Input via command line. 0 is truthy.

First I tried to loop through the characters of the input string, but bash loops are to big. I ended up using sed to replace each character with an addition and multiplication, which then goes to bc. I saved a byte using yes instead of echo.
> 0 votes

# Answer
# Perl 5, 27 bytes

```
$_%(2*eval join'+',split//)

```

Returns 0 for Truthy and non-zero for Falsy
> 0 votes

# Answer
# Ruby, 25 bytes

```
->x{x%(x.digits.sum*2)<1}

```

Try it online!
> 0 votes

# Answer
## LOGO, 24 bytes

```
[modulo ? 2*reduce "+ ?]

```

~~Try it online!~~
Only FMSLogo and its older version (MSWLogo) support `?` in template-list; and only FMSLogo supports `apply` for infix operator `+`.

That is a template-list (equivalent of lambda function in other languages). Return 0 for truthy and other values for falsy.

Usage:

```
pr invoke [modulo ? 2*reduce "+ ?] 100

```

(`invoke` calls the function, `pr` prints the result)

Explanation:

There is only one points need explaining: `reduce`. That is similar to `fold` in some other languages: `reduce "f [1 2 3 4]` calculate `(f (f (f 1 2) 3) 4)`. In this case, `reduce "+ ?` calculate total of elements of digits in `?`.

Numbers in LOGO is represented by word, so `reduce`, a library function can receive a word as its second parameter (while `apply` can't)
> 0 votes

# Answer
## Alice, 16 bytes

```
/o. &
\i@h /+.+F

```

Try it online!

Prints twice the digit sum as the truthy result and `0` otherwise.

The code looks so painfully suboptimal with the two spaces and the repeated `.` and `+`, but I just can't figure out a more compact layout.

### Explanation

```
/    Switch to Ordinal mode.
i    Read all input as a string.
.    Duplicate.
h    Split off the first character.
&    Fold the next command over the remaining characters (i.e. push each character
     in turn and then execute the command).
/    Switch back to Cardinal mode (not a command).
+    Add. This is folded over the characters, which implicitly converts them
     to the integer value they represent and adds them to the leading digit.
.+   Duplicate and add, to double the digit sum.
F    Test for divisibility. Gives 0 if the input is not divisible by twice its
     digit sum and the (positive/truthy) divisor otherwise.
\    Switch to Ordinal mode.
o    Implicitly convert the result to a string and print it.
@    Terminate the program.

```
> 0 votes

# Answer
# Java 7, ~~197~~ ~~133~~ 126 bytes

~~First try~~ Second try, fixed it, -9 characters on variable name, and changing it into function for the other subtraction with help of Olivier Grégoire

Changed boolean to int, now return 0 for true values, other number for falsy

```
int b(String a){int t=0;for(int i=0;i<a.length();i++){t+=Integer.parseInt(""+a.charAt(i));}return(Integer.parseInt(a)%(t*2));}

```
~~```
boolean a(String a){int t=0;for(int i=0;i<a.length();i++){t+=Integer.parseInt(""+a.charAt(i));}return(Integer.parseInt(a)%(t*2)==0);}

```~~

Ungolfed

```
int b(String a){
int t=0;for(int i=0;i<a.length();i++){
t+=Integer.parseInt(""+a.charAt(i));
}
return(Integer.parseInt(a)%(t*2));}

```
> 0 votes

# Answer
# Pyth, 7 bytes

```
%QyssM`

```

Test it online! It returns 0 for truthy, a non null positive integer for falsy.

**Explanations**

```
       Q    # Implicit input Q
      `     # Convert the input to a string
    sM      # For each character in Q, convert to integer
   s        # Sum the resulting list
  y         # Multiply by two
%Q          # Perform the modulo with the input

```
> 0 votes

# Answer
# Java, 53 bytes

```
a->{int i=0,c=a;for(;c>0;c/=10)i+=c%10*2;return a%i;}

```

> 0 true
>
> \>0 false
> 0 votes

# Answer
# R, 71 bytes

```
f=function(x)`if`(x%%(sum(floor(x/10^(0:(nchar(x)-1)))%%10)*2)==0,T,F)

```

Using `floor(x/10^(0:(nchar(x)-1)))%%10` saves the usual hassle of converting to character and back.

```
> f(1)
[1] FALSE
> f(12)
[1] TRUE
> f(123456789)
[1] FALSE

```
> 0 votes

# Answer
## R, 58 bytes

```
(a<-scan())%%(2*sum(strtoi(el(strsplit(paste(a),"")))))<1

```

`a <- scan()` stores user's input in variable `a`.

This variable is of type `numeric`. The `paste` function converts it into `character` for the `strsplit` function to separate its digits. `el` permits to use only the first element of the `list` created by `strsplit`.

The `strtoi` function converts then the digits back into `numeric`, for the function `sum` to, well, sum, before doubling the result.

To finish, divisibility of `a` with the double sum of its digits is tested by the `... %% ... < 1` part, outputing `TRUE` or `FALSE`.
> 0 votes

# Answer
# \>\<\>, 26 bytes

```
000\~2*%n;
0(?\c%:{a*+}+i:

```

Try it online!

Output is 0 for truthy, non-0 for falsey.
> 0 votes

# Answer
# Excel VBA, 72 Bytes

Anonymous VBE immediate window function that takes input from cell `[A1]` and outputs to the VBE immediate window

```
For i=1To[Len(A1)]:s=s+Int(Mid([A1],i,1)):Next:s=s*2:?Int([A1]/s)=[A1]/s

```
> 0 votes

# Answer
# Element, 29 bytes

Here goes my first "real" codegolf attempt...

```
_2:x;2:$'0 z;[(z~+z;]x~z~2*%`

```

Outputs "0" if true, anything else if false.

Try it online!

Explanation:

```
_             push input into main stack
2:            pop number and push it twice
x;            store one of them as x
2:            pop again and push twice
$'            pop and get length, push it to control stack
0 z;          initiate accumulator "z" with value zero
[             for length of input number (loop start),
(             pop off first digit,
z~            retrieve "z",
+             add popped digit to it,
z;            store "z"  again
]             (end of looped statement)
x~            retrieve "x" (copy of original number)
z~            retrieve "z" (accumulated digit sum)
2*            double accumulated digit sum
%             modulus the digit sum and original number
`             pop result to output.

```
> 0 votes

# Answer
# Julia, 30 29 bytes

```
f(x)=x/2sum(digits(x)) in 0:x

```

saved a byte thanks to caird-coinheringaahing
> 0 votes

# Answer
# K (oK), 14 bytes

**Solution:**

```
(2*+/48!$x)!x:

```

Try it online!

**Examples:**

```
  (2*+/48!$x)!x:18
0
  (2*+/48!$x)!x:123
3
  (2*+/48!$x)!x:390
6

```

**Explanation:**

Evaluation is performed right-to-left, unfortunately modulo is `b!a` rather than `a!b` hence the need for brackets. Returns `0` for truthy, positive integer for falsey per spec.

```
(2*+/48!$x)!x: / the solution
            x: / store input in variable x
           !   / modulo right by the left ( e.g. 3!10 => 1, aka 10 mod 3 )
(         )    / the left
        $x     / string ($) input, 123 => "123"
     48!       / modulo with 48, "123" => 1 2 3
   +/          / sum over, +/1 2 3 => 6
 2*            / double, 6 => 12

```

**Notes:**

* Prepend solution with `~` (not) to give a true/false result.
> 0 votes

# Answer
# \>\<\>, 36 Bytes

Unlike the other \>\<\> response, this takes the number itself as input as opposed to the digits. Of course, because of that it's a bit longer longer.

```
:&>:a%:}-\1-?\2*&$%n;
  \?)0:,a/l +<

```

### Explanation:

```
:&

```

Duplicates input, stores a copy in the register.

```
  >:a%:}-\
  \?)0:,a/

```

Converts the number into its digits.

```
         \1-?\
         /l +<

```

Sum the digits

```
              2*&$%n;

```

Multiplies the digit sum by 2, and prints the original number modulo that sum. Output is, then, 0 for truthy and something else otherwise.
> 0 votes

# Answer
# Deorst, 16 bytes

```
iE"E|miEH:+zE|%N

```

Try it online!

## How it works

Implicitly inputs and outputs, example: `172`

```
iE"              - To string;  STACK = ['172']
   E|            - Splat;      STACK = ['1' '7' '2']
     mi          - To integer; STACK = [1 7 2]
       EH        - Sum;        STACK = [10]
         :+      - Double;     STACK = [20]
           zE|   - Push input; STACK = [20 172]
              %N - Divides?    STACK = [0]

```
> 0 votes

# Answer
# ARBLE, 33 bytes

```
nt(a%(sum(explode(""..a,"."))*2))

```

Try it online!
> 0 votes

# Answer
# Clojure, 59 bytes

```
(fn[n](= 0(rem n(* 2(apply +(map #(-(int %)48)(str n)))))))

```

---

```
(defn sum-of-digits? [n]
  (let [ds (map #(- (int %) 48) (str n)) ; Stringify n, and parse each digit char of the string
        d-sum (* 2 (apply + ds))] ; Get the doubled sum
    (= 0 (rem n d-sum)))) ; Check if the remainder of (/ n sum) is 0

```
> 0 votes

# Answer
# Scala, ~~54~~ 32 bytes

Saved 22 bytes thanks to the comment of @user

---

Try it online!

```
n=>n.toInt%(n+n:\0)(_.asDigit+_)

```
> 0 votes

---
Tags: code-golf, number, number-theory, decision-problem, division
---


title: Rotating Spirals

text:
# Question
Title: Rotating Spirals
Given a square of text representing a spiral of characters, rotate it!

The spiral starts at the center and moves *counterclockwise* to the outer edge, starting to the left of center:

```
987
216
345

```

This translates to the string `123456789`. Rotation is done *to the left*, so if you rotate it one position, it will be `234567891`. This is represented by:

```
198
327
456

```

### Input

Input consists of the spiral and the distance to rotate it.

Distance will always be a positive integer or zero, and can be capped at your language's data type limit.

The spiral should be taken as a string, with a line delimiter of your choice (including no delimiter). It will always be a square, not including delimiters, and have an odd side length.

Assume all characters are alphanumeric \[A-Za-z0-9\].

### Output

Output is the rotated spiral. It should be a square on multiple lines (whether printed or returned).

### Examples

Input

```
3
tne
atd
bin

```

Output

```
bat
nit
den

```

Input

```
18
efilr
naepo
umshf
tootr
butte

```

Output

```
rettu
omseb
oofft
trliu
hpean

```

This is code golf, with score counted in bytes as usual.

# Answer
> 8 votes
# CJam, ~~45~~ 44 bytes

```
]]l~LqN/{(W%@+\zW%}h;m<{1$,/(W%a@W%z+\s}h;N*

```

Test it here.

## Explanation

The lazy solution: unwrap the spiral, use CJam's built-in array rotation, roll the spiral up again.

```
]]       e# Push [""]. We'll later use this to roll up the spiral.
l~       e# Read the integer and evaluate it.
L        e# Push an empty string: we'll unroll the input into this.
qN/      e# Read the spiral and split it into lines.
{        e# While the top of the stack is truthy...
  (W%    e#   Pull the first line off the spiral and reverse it.
  @+     e#   Pull up the string we've built so far and prepend the reversed line.
  \zW%   e#   Swap with the remaining spiral, and rotate the spiral.
}h       e# This terminates when the centre character has been added to the string and
         e# the spiral becomes an empty array.
;        e# Discard the empty array.
         e# Note that we've unrolled the spiral from outside in, but we've also built up
         e# the string in reverse, which gives us the string from inside out.
m<       e# Rotate to the left by the given number of characters.
{        e# While the top of the stack is truthy...
  1$,    e#   Copy the spiral so far and get the number of lines.
  /      e#   Split the string into chunks of that size.
  (W%a   e#   Pull off the first chunk, reverse it and wrap it in an array.
  @zW%   e#   Pull up the spiral so far, rotate it.
  +      e#   Prepend the chunk to the spiral as a line.
  \s     e#   Swap with the other chunks and flatten them into a string again.
}h       e# This terminates when the string has been used up completely.
;        e# Discard the empty string.
N*       e# Join the lines with linefeed characters.

```

# Answer
> 1 votes
# Haskell, 188 bytes

```
import Data.List;r=reverse;t=transpose;f=take;g=drop
u[[c]]=[c];u(a:b)=a++u(r.t$b)
w k[]=k;w[](a:b)=w[[a]]b;w k l=w((r.f h$l):(t.r$k))$g h l where h=length k
s n=w[].(\s->g n s++f n s).r.u

```

Try it online!

# Answer
> 1 votes
# Python3, 336 bytes:

```
R=range
def S(N):
 x,y=N//2,N//2;r=[(x,y)]
 for i in R(2,N,2):
  y-=1;F=0;r+=[(x,y)]
  for X,Y in[(1,0),(0,1),(-1,0),(0,-1)]:
   for _ in R(i):
    if F:x+=X;y+=Y;r+=[(x,y)]
    F=1
 return r
def f(n,s):
 s=[[*i]for i in s.split('\n')];T=[s[x][y]for x,y in S(len(s[0]))];T=T[n:]+T[:n]
 for x,y in S(len(s[0])):s[x][y]=T.pop(0)
 return s

```

Try it online!

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