title: A Fragile Quine

text:
# Question
Title: A Fragile Quine
# A Fragile Quine

A fragile quine is a quine that satisfies the property of having each substring made by removing a single character, when evaluated, produces an error.

For example. If your program `asdf` is a quine, then for it to be fragile, the following programs must error:

```
sdf
adf
asf
asd

```

Your program (and all of its substrings) must be fully deterministic, and must be in the same language. A program falling into an infinite loop (that is, failing to terminate), even if not eventually producing an error is considered to "produce an error" for the purposes of this challenge.

Standard loopholes apply, including the usual quine restrictions (e.g. not able to read own source code).

For example, `print("foo")` is not fragile. All these substrings must error:

```
rint("foo")
pint("foo")
prnt("foo")
prit("foo")
prin("foo")
print"foo")
print(foo")
print("oo")
print("fo")
print("fo")
print("foo)
print("foo"

```

The ones that don't error are:

```
print("oo")
print("fo")
print("fo")

```

So it is not fragile.

## An important note on quines

By consensus, any possible quine must satisfy this:

> > It must be possible to identify a section of the program which encodes a different part of the program. ("Different" meaning that the two parts appear in different positions.)
> >
> > Furthermore, a quine must not access its own source, directly or indirectly.

## Example

Since I consider JavaScript's function#toString to be "reading it's own source code", I am disallowing it. However, if I weren't to bar it, here is a fragile quine in JavaScript:

```
f=(n=b=`f=${f}`)=>(a=(n)==`f=${f}`,n=0,a)&(n!=b)?b:q

```

## Tester

Here is a program that, given the source code of your program, generates all programs that must error.

```
let f = (s) =>
  [...Array(s.length).keys()].map(i =>
    s.slice(0, i) + s.slice(i + 1)).join("\n");

let update = () => {
  output.innerHTML = "";
  output.appendChild(document.createTextNode(f(input.value)));
};

input.addEventListener("change", update);

update();
```

```
#output {
  white-space: pre;
}

#input, #output {
  font-family: Consolas, monospace;
}
```

```
<input id="input" value="print('foo')">
<div id="output"></div>
```

# Answer
## Burlesque, ~~32~~ ~~28~~ 25 bytes

```
{3SHWD{Je!}.+{Sh}\msh}Je!

```

Try it here.

So most instructions in Burlesque are 2 characters. And it is much easier to write a quine in Burlesque than in Marbelous. `Je!` or `^^e!` means `_~` in CJam.
> 6 votes

# Answer
# Python 3, 45 bytes

```
c='print(end="c=%r;exec(c"%c+c[8*4])';exec(c)

```

Switching to Python 3 so that the trailing newline can be easily removed.

I started out with a stupid structure that had 2 variables instead of 1, but switching to 1 variable only made it 4 bytes shorter.

-(4 + 3) bytes by Dennis.
> 11 votes

# Answer
# Python, ~~91/92~~ 67 bytes

This was fun!

Now I know about assert:

```
s='s=%r;assert len(s)==34;print(s%%s)';assert len(s)==34;print(s%s)

```

If a char from string is removed, assert error. I would have done this sooner had I known of this feature, assert.
> 7 votes

# Answer
# Python 2, ~~51~~ ~~50~~ 46 bytes

```
lambda s='lambda s=%r:s[22:]%%s%%s':s[22:]%s%s

```

Verify it on Ideone.
> 7 votes

# Answer
# JavaScript, 90 bytes

```
a="a=%s;a[44]!=')'?x:console.log(a,uneval(''+a))";a[44]!=')'?x:console.log(a,uneval(''+a))

```

Works in the console of Firefox 48, and should work in any other environment with `uneval` and `console.log`. Breakdown of errors:

```
a="                                             "; [  ]!=' '?x:           (a       (''+a))   // SyntaxError
   a=%s;a[44]!=')'?x:console.log(a,uneval(''+a))  a 44    )                                  // ReferenceError from calling `x`
                                                               console.     ,uneval          // ReferenceError from calling `onsole.log`, `auneval`, etc.
                                                                       log                   // TypeError from calling `console.og`, etc.

```
> 3 votes

# Answer
# C#, 145 bytes

```
_=>{var@s="_=>{{var@s={1}{0}{1};for(;79!=s.Length;){{}}System.Console.Write(s,s,'{1}');}};";for(;79!=s.Length;){}System.Console.Write(s,s,'"');};

```

I've not written a quine in C# before, but higher scores are better in golf, right? :)

Infinite loop if a char is removed from the string or a digit from the magic const 79. Removing any other char results in a compile error.

Ungolfed:

```
/* Action<object> Quine = */ _ => // unused parameter
{
    // String of the function (well, mostly).
    // {0} placeholder for s, so the output contains the function and string.
    // {1} placeholder for " since it requires escaping.
    var@s = "_=>{{var@s={1}{0}{1};for(;79!=s.Length;){{}}System.Console.Write(s,s,'{1}');}};";

    // Infinite loop if a char is removed from the above string or if the 7 or 9 is removed.
    for(;79!=s.Length;){}

    // Print the quine.
    System.Console.Write(s,s,'"');
};

```
> 3 votes

# Answer
# Python 2, 59 bytes

```
x='x=%r;1/(len(x)==30);print x%%x';1/(len(x)==30);print x%x

```

This throws a `ZeroDivisionError` if a 0, a 3, or a character is removed from the string. Removing a different character results in a `NameError` or a `SyntaxError`.
> 2 votes

# Answer
# A Pear Tree, 50 bytes

```
a="print('a='.repr(a).';eval(a)');#f+QF>";eval(a)

```

Try it online!

Not the shortest answer, but a fairly comprehensive one; any character deletion from this program causes it to fail to checksum, thus the A Pear Tree interpreter won't even attempt to run it. (For example, you get an error if you delete the trailing newline.) The `;#f+QF>` is used to ensure that the program as a whole has a CRC-32 of 0 (and `f+QF>` is one of three possible 5-byte strings that could be placed in the comment to achieve that while staying in ASCII; using ASCII is important here because `repr` would fail to round-trip it correctly otherwise).
> 2 votes

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


title: Generating an adequate password

text:
# Question
Title: Generating an adequate password
# Story

I need to remember a lot of passwords and don't want to use the same one for multiple websites so I came up with a rule, but the rule shouldn't be transparent so what I do is:

* Think of a long word or concept such as `breadpudding`.
* Replace the first letter with the site we are logging into. If we are logging into `google`, our word becomes `greadpudding`.
* Make the first letter uppercase.
* Change the second letter to an `@` sign.
* If the password starts with a non-consonant, add a certain number (such as `1234`); otherwise, add another number (such as `4321`).

Ta da, you now have an adequate password.

This process is arduous though so I need a program to generate this for me based on the following:

# Problem

Given input:

* `a` : the initial word, which is a string and is always lowercase, and is guaranteed to be longer than 3 characters.
* `b` : the site we are logging into, which is a string and is always lowercase, and is guaranteed to be non-empty.
* `c` : the number for non-consonants, which is a positive integer that may have leading zeroes.
* `d` : the number for consonants, which is a positive integer that may have leading zeroes.

Output a string based on above criteria.

# Test cases

Input `a="volvo", b="gmail", c=5555, d="0001"`

`G@lvo0001`

Input `a="sherlock", b="9gag", c=31415926535, d=3`

`9@erlock31415926535`

Input `a="flourishing", b="+google", c=11111, d=2222`

`+@ourishing11111`

# Rules

* `y` is a consonant.
* If you decide `c` or `d` is an integer, you may parse it as such, and leading zeroes can be ignored (`0091` gets treated as `91`).
* Trailing whitespace and newlines are allowed.
* You may output the result to STDOUT or return the result in a function.
* Characters allowed in `a` and `b` are `[a-z0-9!@#$%^&*()_+=-]`.
* You may accept the 4 inputs in any consistent order.

This is . Shortest code in bytes wins.

# Answer
> 2 votes
# Jelly, 17 bytes

```
Ḣ©Œu;”@o;⁶⁵®eØC¤?

```

A full program, taking the arguments in the order `b`, `a`, `c`, `d`.

**Try it online!**

### How?

The main link is dyadic, taking `b` and `a`, the program inputs are then `b`, `a`, `c`, and `d` (the 3rd through sixth command line arguments), so `c` and `d` are accessed as such.

```
Ḣ©Œu;”@o;⁶⁵®eØC¤?  Main link: b, a           e.g. "gmail", "volvo" (c="5555" and d="0001")
Ḣ                  head b                         'g'
 ©                 copy to register and yield     'g'
  Œu               convert to uppercase           "G"
     ”@            literal '@' character          '@'
    ;              concatenate                    "G@"
       o           logical or with a (vectorises) "G@lvo"
                ?  if:
               ¤     nilad followed by link(s) as a nilad:
           ®           recall value from register  'g'
             ØC        yield consonants            "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"
            e          exists in?                  1
         ⁶         ...then: 6th arg = 4th in = d   "0001"
          ⁵        ...else: 5th arg = 3rd in = c   "5555"
        ;          concatenate                     "G@lvo0001"
                   implicit print

```

# Answer
> 3 votes
# Python 3, 69 bytes

```
lambda a,b,*c:b[0].upper()+"@"+a[2:]+c[b[0]in"bcdfghjklmnpqrstvwxyz"]

```

Try it online!

# Answer
> 2 votes
# 05AB1E, ~~22~~ ~~20~~ 18 bytes

```
н©u'@I¦¦žN®åiI\}IJ

```

Input taken as `b,a,c,d`

Try it online!

**Explanation** (outdated)

```
¦                     # remove the first char of a
 s                    # swap b to the top of the stack
  н©                  # push the head of b and store a copy in register
    uì                # convert the head to upper case and prepend to a
      U               # store in variable X
       žN®åi          # if the head of b is a consonant
            \}        # discard c
              X«      # concatenate X with c or d
                '@1ǝ  # insert an "@" at character position 1

```

used in the link as `н` isn't pulled to TIO yet.

# Answer
> 2 votes
# C, 441 286 139 Bytes

```
#define o(c)*a[1]==0xc
int main(int b,char** a){printf("%c@%s%s",*a[1],a[2]+2,(*a[1]>97&*a[1]<128)
&!(o(65)|o(69)|o(6F)|o(75))?a[4]:a[3]);}

```

# Answer
> 2 votes
# Javascript ES6, 87 bytes

```
(a,b,c,d)=>b[0].toUpperCase()+'@'+a.slice(2)+(/[bcdfghjklmnpqrstvwxyz]/.test(b[0])?d:c)

```

## Demo

```
f=
(a,b,c,d)=>b[0].toUpperCase()+'@'+a.slice(2)+(/[bcdfghjklmnpqrstvwxyz]/.test(b[0])?d:c)

console.log(f("volvo","gmail", 5555, "0001")); //G@lvo0001
console.log(f("sherlock","9gag", 31415926535, 3)); //9@erlock31415926535
console.log(f("flourishing","+google", 11111, "2222")); //+@ourishing11111
```

# Answer
> 2 votes
# Retina, ~~80~~ 75 bytes

```
^..(.*)¶(.).*
$2@$1
^([ -_aeiou].*)¶(.*)¶.*
$1$2
(.*)¶.*¶(.*)
$1$2
T`l`L`^.

```

Try it online!

Trying out a new language here, takes inputs in the order given in the question

### Explanation:

```
^..(.*)¶(.).*
$2@$1

```

Create a word which is second word first letter, @ sign, first word from the 3rd character on.

```
^([ -_aeiou].*)¶(.*)¶.*
$1$2

```

If the word starts with a non-consonant, append the first number

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

```

If there are still 3 lines left (no substitution in the last step, so it starts with a consonant), append the second number

```
T`l`L`^.

```

Uppercase the first letter

# Answer
> 2 votes
# , ~~105~~ 103 bytes

```
pryr::f({m=substr(b,0,1);paste0(toupper(m),'@',substring(a,3),'if'(grepl("[b-df-hj-np-tv-z]",m),d,c))})

```

Anonymous function. Evaluates to

```
function (a, b, c, d)
{
    m = substr(b, 0, 1)                      #first letter of website
    paste0(toupper(m),                       #concatenate that letter, capitalized,
           "@",                              #an '@',
           substring(a, 3),                  #the rest of the long string,
           if(                               #and
           grepl("[b-df-hj-np-tv-z]", m)),   #if the first letter is a consonant,
           d                                 #the consonant string/num,
           else c)                           #else the other one
}

```

which is what's on TIO. Please help me golf that regex because I'm terrible at them.

Saved 2 bytes from Giuseppe.

Try it online!

# Answer
> 1 votes
# QBIC, 81 bytes

```
G=ucase$(_s;,1|)+@@`+_s;,3,_lC||~instr(@bcdfghjklmnpqrstvwxyz`,_sC,1|)|?G+;\?G+;

```

## Explanation

```
Parameters are Website(A$), base word(C$), consonant-number(E$), and nonsonant-number(F$)
G=                           SET G$ to
 ucase$(      )              the upper-case version of (also works for '9gag', '+google')
        _s;,1|                  the first char of the website A$ read from cmd line
 +@@`                        plus a literal @ (B$)
 +_s;,3,_lC||                plus all characters from base word C$ from 3rd char onwards
~instr(                      IF the second arg to INSTR is in the first
 @bcdfghjklmnpqrstvwxyz`,      with all consonants in the first arg
 _sC,1|                        and the first char of the base word C$ in the second
 )
|?G+;                        THEN print G$ plus the consonant addition
\?G+;                        ELSE print G$ plus the other addition

```

Note that the last two lines appear the same, but the interpreter changes the behaviour slightly on each `;`: Whenever it sees the `;` instruction, it creates a new variable (in this case, the vars È$`and`F$\` are the first available after reading all other literals and cmd line arguments) and assigns the first not-yet-assigned cmd line paraeter to that variable.

# Answer
> 1 votes
# Java 8, ~~112~~ ~~99~~ ~~92~~ 87 bytes

```
(a,b,c,d)->b.toUpperCase().charAt(0)+"@"+a.substring(2)+(b.matches("[a-z&&[^aeiou]].*")?d:c)

```

-13 bytes by taking parameter `b` last instead of second.
-1 byte by removing `y`
-7 bytes thanks to *@OlivierGrégoire* (and parameters are in order again)
-5 bytes thanks to *@PunPun1000*

**Explanation:**

Try it here.

```
(a,b,c,d)->                     // Method with 4 String parameters and String return-type
  b.toUpperCase().charAt(0)     //  First character of B capitalized
  +"@"                          //  + literal "@"
  +a.substring(2)               //  + A excluding first two characters
  +(b.matches("[ -_aeiou].*")?  //  If B starts with a consonant:
    d                           //   + D
   :                            //  Else:
    c)                          //   + C
                                // End of method (implicit / lambda with single return)

```

# Answer
> 1 votes
# JavaScript (ES6), 76 bytes

```
(a,b,c,d)=>b[0].toUpperCase()+'@'+a.slice(2)+(/[aeiou\d_\W]/.test(b[0])?c:d)

```

I would have added this as a suggestion as an improvement to Weedoze's solution, but it seems like I can't comment on it since I mostly lurk

# Answer
> 1 votes
# C#, 111 bytes

```
(a,b,c,d)=>Char.ToUpper(b[0])+"@"+a.Substring(2)+(b.IndexOfAny("bcdfghjklmnpqrstvwxyz".ToCharArray()==0)?d:c);

```

Checking the consonant is particularly expensive with no direct regex capability on the `string` type.

# Answer
> 1 votes
# F#, 157 bytes

```
let f(a:string)(b:string)c d=System.Char.ToUpper(b.[0]).ToString()+"@"+a.[2..]+(if((Seq.except['e';'i';'o';'u']['b'..'z'])|>Seq.contains b.[0])then d else c)

```

F# is still very new to me so there are probably better approaches to this.

# Answer
> 0 votes
# , 25 bytes

```
ldvjr@Ç^[aeiou]ü^Á/j

DÍî

```

Try it online!

Takes arguments in the buffer in order:

```
website
word/phrase
consonant number
non-consonant number

```

# Answer
> 0 votes
# Bash 4, 76 bytes

```
g(){
a=${2:0:1}
c=$4
[[ "aeiou[0-9]" =~ .*$a.* ]]&&c=$3
p="${a^}@${1:2}$c"
}

```

Works in Bash 4:

```
g volvo gmail 5555 0001; echo $p
g sherlock 9gag 31415926535 3; echo $p
g flourishing +google 11111 2222; echo $p

```

# Answer
> 0 votes
# Ruby, 73 bytes

```
->a,b,c,d{a.sub(/..(.*)/){b[0].upcase+"@#$1#{b[0]=~/[aeiou_\d\W]/?c:d}"}}

```

Try it online!

# Answer
> 0 votes
# JavaScript (ES6), 69 bytes

```
(a,b,c,d)=>e=a[0].toUpperCase()+"@"+a.slice(2)+/[AEIOU]/.test(e)?c:d

```

Pretty simple, probably can be golfed

---
Tags: code-golf
---


title: Print a Variable's Name

text:
# Question
Title: Print a Variable's Name
Write a function (not a full program), so that if the function is called with a single global variable (or your language's closest equivalent) as its argument, it outputs (i.e. prints or returns) the name of that variable. If the argument is not a variable, output a falsey value instead. (You don't have to handle the case where the argument is a variable, but not global.)

There must not be a compile-time connection between the function call and function definition (notably, the function definition cannot be a macro or similar construct that receives arguments in the form of a literal fragment of source code, neither in text nor abstract syntax tree form). That is: in languages which support separate compilation, the program must work even if the function call is compiled first (with no knowledge of the function definition but possibly a type signature or equivalent), then the function definition is compiled afterwards. If the language doesn't have separate compilation, you must nonetheless aim for a similar separation between the call and definition.

If using a compiled language, you may read the compiled form of the complete program from disk, and may assume that the program was compiled with debug information. (Thus, solutions that work by attaching a debugger from a program to itself are allowed.)

Note that this task may not be possible in every language.

## Examples:

```
var apple = "Hello"
p(apple) // apple

var nil = "Nothing"
p(nil) // nil

var SOMETHING = 69
p(SOMETHING) // SOMETHING

function foo(){}
p(foo) // foo

p(3.14159) // false

p(function foo(){}) // false

```

# Answer
> 32 votes
# Java

```
String getParamName(String param) throws Exception {
    StackTraceElement[] strace = new Exception().getStackTrace();
    String methodName = strace[0].getMethodName();
    int lineNum = strace[1].getLineNumber();

    String className = strace[1].getClassName().replaceAll(".{5}$", "");
    String classPath = Class.forName(className).getProtectionDomain().getCodeSource().getLocation().getPath() + className + ".class";

    StringWriter javapOut = new StringWriter();
    com.sun.tools.javap.Main.run(new String[] {"-l", "-c", classPath}, new PrintWriter(javapOut));
    List<String> javapLines = Arrays.asList(javapOut.toString().split("\\r?\\n"));
    int byteCodeStart = -1;
    Map<Integer, Integer> byteCodePointerToJavaPLine = new HashMap<Integer, Integer>();
    Pattern byteCodeIndexPattern = Pattern.compile("^\\s*(\\d+): ");
    for (int n = 0;n < javapLines.size();n++) {
        String javapLine = javapLines.get(n);
        if (byteCodeStart > -1 && (javapLine == null || "".equals(javapLine))) {
            break;
        }
        Matcher byteCodeIndexMatcher = byteCodeIndexPattern.matcher(javapLine);
        if (byteCodeIndexMatcher.find()) {
            byteCodePointerToJavaPLine.put(Integer.parseInt(byteCodeIndexMatcher.group(1)), n);
        } else if (javapLine.contains("line " + lineNum + ":")) {
            byteCodeStart = Integer.parseInt(javapLine.substring(javapLine.indexOf(": ") + 2));
        }
    }

    int varLoadIndex = -1;
    int varTableIndex = -1;
    for (int i = byteCodePointerToJavaPLine.get(byteCodeStart) + 1;i < javapLines.size();i++) {
        if (varLoadIndex < 0 && javapLines.get(i).contains("Method " + methodName + ":")) {
            varLoadIndex = i;
            continue;
        }

        if (varLoadIndex > -1 && javapLines.get(i).contains("LocalVariableTable:")) {
            varTableIndex = i;
            break;
        }
    }

    String loadLine = javapLines.get(varLoadIndex - 1).trim();
    int varNumber;
    try {
        varNumber = Integer.parseInt(loadLine.substring(loadLine.indexOf("aload") + 6).trim());
    } catch (NumberFormatException e) {
        return null;
    }
    int j = varTableIndex + 2;
    while(!"".equals(javapLines.get(j))) {
        Matcher varName = Pattern.compile("\\s*" + varNumber + "\\s*([a-zA-Z_][a-zA-Z0-9_]*)").matcher(javapLines.get(j));
        if (varName.find()) {
            return varName.group(1);
        }
        j++;
    }
    return null;
}

```

This currently works with a few gotchas:

1. If you use an IDE to compile this it might not work unless it is run as Admin (depending on where the temporary class files are saved)
2. You must compile using `javac` with the `-g` flag. This generates all debugging information including local variable names in the compiled class file.
3. This uses an internal Java API `com.sun.tools.javap` which parses the bytecode of a classfile and produces a human readable result. This API is only accessible in the JDK libraries so you must either use the JDK java runtime or add tools.jar to your classpath.

This should now work even if the method is called multiple times in the program. Unfortunately it does not yet work if you have multiple invocations on a single line. (For one that does, see below)

Try it online!

---

### Explanation

```
StackTraceElement[] strace = new Exception().getStackTrace();
String methodName = strace[0].getMethodName();
int lineNum = strace[1].getLineNumber();

String className = strace[1].getClassName().replaceAll(".{5}$", "");
String classPath = Class.forName(className).getProtectionDomain().getCodeSource().getLocation().getPath() + className + ".class";

```

This first part gets some general information about what class we're in and what the name of the function is. This is accomplished by creating an exception and parsing the first 2 entries of the stack trace.

```
java.lang.Exception
    at E.getParamName(E.java:28)
    at E.main(E.java:17)

```

The first entry is the line that the exception is thrown on which we can grab the methodName from and the second entry is where the function was called from.

```
StringWriter javapOut = new StringWriter();
com.sun.tools.javap.Main.run(new String[] {"-l", "-c", classPath}, new PrintWriter(javapOut));

```

In this line we are executing the javap executable that comes with the JDK. This program parses the class file (bytecode) and presents a human-readable result. We'll use this for rudimentary "parsing".

```
List<String> javapLines = Arrays.asList(javapOut.toString().split("\\r?\\n"));
int byteCodeStart = -1;
Map<Integer, Integer> byteCodePointerToJavaPLine = new HashMap<Integer, Integer>();
Pattern byteCodeIndexPattern = Pattern.compile("^\\s*(\\d+): ");
for (int n = 0;n < javapLines.size();n++) {
    String javapLine = javapLines.get(n);
    if (byteCodeStart > -1 && (javapLine == null || "".equals(javapLine))) {
        break;
    }
    Matcher byteCodeIndexMatcher = byteCodeIndexPattern.matcher(javapLine);
    if (byteCodeIndexMatcher.find()) {
        byteCodePointerToJavaPLine.put(Integer.parseInt(byteCodeIndexMatcher.group(1)), n);
    } else if (javapLine.contains("line " + lineNum + ":")) {
        byteCodeStart = Integer.parseInt(javapLine.substring(javapLine.indexOf(": ") + 2));
    }
}

```

We're doing a couple different things here. First, we are reading the javap output line by line into a list. Second we are creating a map of bytecode line indexes to javap line indexes. This helps us later to determine which method invocation we want to analyze. Finally we are using the known line number from the stack trace to determine which bytecode line index we want to be looking at.

```
int varLoadIndex = -1;
int varTableIndex = -1;
for (int i = byteCodePointerToJavaPLine.get(byteCodeStart) + 1;i < javapLines.size();i++) {
    if (varLoadIndex < 0 && javapLines.get(i).contains("Method " + methodName + ":")) {
        varLoadIndex = i;
        continue;
    }

    if (varLoadIndex > -1 && javapLines.get(i).contains("LocalVariableTable:")) {
        varTableIndex = i;
        break;
    }
}

```

Here we are iterating over the javap lines one more time in order to find the spot where our method is being invoked and where the Local Variable Table starts. We need the line where the method is invoked because the line before it contains the call to load the variable and identifies which variable (by index) to load. The Local Variable Table helps us actually look up the name of the variable based on the index we grabbed.

```
String loadLine = javapLines.get(varLoadIndex - 1).trim();
int varNumber;
try {
    varNumber = Integer.parseInt(loadLine.substring(loadLine.indexOf("aload") + 6).trim());
} catch (NumberFormatException e) {
    return null;
}

```

This part is actually parsing the load call to get the variable index. This can throw an exception if the function isn't actually called with a variable so we can return null here.

```
int j = varTableIndex + 2;
while(!"".equals(javapLines.get(j))) {
    Matcher varName = Pattern.compile("\\s*" + varNumber + "\\s*([a-zA-Z_][a-zA-Z0-9_]*)").matcher(javapLines.get(j));
    if (varName.find()) {
        return varName.group(1);
    }
    j++;
}
return null;

```

Finally we parse out the name of the variable from the line in the Local Variable Table. Return null if it isn't found although I've seen no reason why this should happen.

### Putting it all together

```
 public static void main(java.lang.String[]);
    Code:
...
      18: getstatic     #19                 // Field java/lang/System.out:Ljava/io/PrintStream;
      21: aload_1
      22: aload_2
      23: invokevirtual #25                 // Method getParamName:(Ljava/lang/String;)Ljava/lang/String;
...
    LineNumberTable:
...
      line 17: 18
      line 18: 29
      line 19: 40
...
    LocalVariableTable:
      Start  Length  Slot  Name   Signature
          0      83     0  args   [Ljava/lang/String;
          8      75     1     e   LE;
         11      72     2   str   Ljava/lang/String;
         14      69     3  str2   Ljava/lang/String;
         18      65     4  str4   Ljava/lang/String;
         77       5     5    e1   Ljava/lang/Exception;

```

This is basically what we're looking at. In the example code the first invocation is line 17. line 17 in the LineNumberTable shows that the beginning of that line is bytecode line index 18. That is the `System.out` load. Then we have `aload_2` right before the method call so we look for the variable in slot 2 of the LocalVariableTable which is `str` in this case.

---

For fun, here's one which handles multiple function calls on the same line. This causes the function to not be idempotent but that's kind of the point. Try it online!

# Answer
> 14 votes
# Python 2

This is about the most dirty code I've written but it works. ¯\\\_(ツ)\_/¯ Throws an error on a non-existent variable as Python will immediately dislike you for calling the function with one. Also throws an error on non-variables but this can be fixed with a try/except if needed.

```
import inspect
import re

def name_of(var):
    for i in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
        return re.search(r'\bname_of\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', i).groups()[0]

```

Try it online!

If we're allowed to take the argument as a string, this satisfies the requirements of outputting a falsy value on an invalid input.

```
import inspect
import re

def name_of(var):
    # return var :P

    try:
        eval(var)
    except NameError:
        return False

    for i in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
        try:
            return re.search(r'\bname_of\s*\(\s*[\'"]([A-Za-z_][A-Za-z0-9_]*)[\'"]\s*\)', i).groups()[0]
        except AttributeError:
            return False

```

Try it online!

# Answer
> 12 votes
## Mathematica

```
f[x_] := ValueQ @ x && ToString @ HoldForm @ x
SetAttributes[f, HoldFirst]

```

The `HoldFirst` attribute prevents `f` from evaluating its argument before invoking the function. `ValueQ @ x` then checks whether the given argument is a variable that has been given a value. If not we just return `False` due to short-circuiting. Otherwise, we obtain the variable name with `ToString @ HoldForm @ x`.

# Answer
> 7 votes
# Mathematica

```
f~SetAttributes~HoldAll;
f[_] = False;
f[x_Symbol?ValueQ] := SymbolName@Unevaluated@x;

```

Mathematica likes to evaluate **everything**, so to make it stop, we have to fight against it. In its own language.

## How?

```
f~SetAttributes~HoldAll;

```

Tells Mathematica that whenever function `f` is called, its arguments shouldn't be evaluated (i.e. held).

---

```
f[_] = False;

```

When `f` is called with an argument, output `False`. (?!)

---

```
f[x_Symbol?ValueQ] := SymbolName@Unevaluated@x;

```

When `f` is called with a defined Symbol (which has a value), output the symbol name of the input.

The previous line does not take precedence, despite being defined earlier, because this definition is more specific. As the Wolfram Documentation states: Mathematica "tries to put specific definitions before more general definitions."

Mathematica is very stubborn and keeps trying to evaluate variables whenever possible. The extra `Unevaluated` takes care of that.

# Answer
> 7 votes
# C#

```
string n<T>(Expression<Func<T>>m) =>
    (m.Body as MemberExpression)?.Member?.Name ?? null;

```

Full/Formatted version:

```
using System;
using System.Linq.Expressions;

class P
{
    static void Main()
    {
        var apple = "Hello";
        var nil = "Nothing";
        var SOMETHING = 69;

        Console.WriteLine(n(() => apple));
        Console.WriteLine(n(() => nil));
        Console.WriteLine(n(() => SOMETHING));
        Console.WriteLine(n(() => 3.14159));

        Console.ReadLine();
    }

    static string n<T>(Expression<Func<T>>m)
        => (m.Body as MemberExpression)?.Member?.Name ?? null;
}

```

---

Another way to do this is by reflecting on the type like so:

```
public static string GetParameterName<T>(T item)
{
    var properties = typeof(T).GetProperties();

    return properties.Length > 0 ? properties[0].Name : null;
}

```

However, you have to call it like:

```
GetParameterName(new { apple });

```

It then also fails for `3.14159` by returning `Length` and for that you also have to call it like the following instead:

```
GetParameterName(new double[]{ 3.14159 });

```

---

In C# 6.0 we also have:

```
nameof

```

But this won't compile if you pass it something that isn't a variable e.g. `3.14159`. I believe it also evaluates the input at compile time so it seems like it fails that requirement as well.

# Answer
> 6 votes
# MATLAB

```
varname = @(x) inputname(1);

```

Within a function there are a few preset variables like `varargin` or `nargin`, among those we also have `inputname`.

stolen from here

# Answer
> 6 votes
## R

```
function(x) if (identical(substitute(x), x)) FALSE else substitute(x)

```

`substitute` returns the parse tree for an unevaluated expression. The `identical` conditional makes sure that this unevaluated expression isn't identical to the expression itself; i.e. that the passed in parameter isn't a literal.

# Answer
> 5 votes
## Python 2

Some research has been done. And it seems to be possible in python, but I still expect some troubles to be found.
Solution is not perfect, as it assumes some structure of the code. Yet I didn't break it still.

```
import inspect
import re

def get_name(var):
    called = inspect.getouterframes(inspect.currentframe())[1][4][0]
    return re.search('(?<=get_name\().*(?=\))', called).group().lstrip().rstrip()

```

This uses inspect to look at surround scope and find where function `get_name` is called. For example `inspect...[1]` will return

> `(< frame object at 0x01E29030>, 'C:/Users/---/PycharmProjects/CodeGolf/Name_var.py', 14, '< module>', ['print get_name( a )\n'], 0)`

And `inspect...[1][4]` will show us list with code, where function is called:

> `['print get_name( a )\n']`

After that I used regex to retrieve name of the argument

```
re.search('(?<=get_name\().*(?=\))', called).group()

```

And `.lstrip().rstrip()` to remove all whitespaces that may be placed into bracets.

Example with some tricky input

# Answer
> 4 votes
# PHP

Needs that the variable value is unique in the array of the global variables

```
function v($i){echo"$".array_search($i,$GLOBALS);}

```

Try it online!

# PHP, 96 bytes

```
function v($i){
echo($i==end($g=$GLOBALS))?"$".key(array_slice($g,-1)):0;
}
$hello=4;
v($hello);

```

Try it online!

Needs that the variable is initialized directly to the function call.

Checks if the last global variable is equal surrendering variable

# Answer
> 4 votes
## PowerShell

```
function t($t){(variable($MyInvocation.Line.Split(' $'))[-1]-ea si).Name}

$apple = 'hi'
t $apple
apple

t 3.141

```

But it doesn't work reliably, it's rudimentary.

# Answer
> 4 votes
# JavaScript (ES6)

For all property names in `window` (`Object.getOwnPropertyNames(w)`), attempt to define a getter for that property that returns the property name.

Then, add an entry to a Map `M` where the key is the (possibly overridden) value of the property, and the value is the name of the property.

The function `f` simply takes a variable (i.e. a property of `window`) and returns the entry in `M` for that value.

```
let
    w = window,
    M = new Map(),
    L = console.log,
    P = Object.getOwnPropertyNames(w),
    D = Object.defineProperty

for(const p of P){
    try {
        D(w, p, {
            get(){
                return p
            }
        })
    } catch(e){ L(e) }

    try {
        M.set(w[p], p)
    } catch(e){ L(e) }
}

let f = v => M.get(v)

```

This works for all built-in global variables except `window` itself, as there is no way to distinguish it from `top` (unless run in a frame):

```
L( P.filter(p => p !== f(w[p])) )
// -> ['window']

```

# Answer
> 3 votes
# Perl 5 + Devel::Caller

```
use 5.010;
use Devel::Caller qw/caller_vars/;
use Scalar::Util qw/refaddr/;

sub v {
   # find all operands used in the call, formatted as variable names
   my @varsused = caller_vars(0,1);
   scalar @varsused == 1 or return; # exactly one operand, or return false
   $varsused[0] =~ s/^\$// or return; # the operand actually is a variable
   # it's possible we were given an expression like "~$test" which has only
   # one operand, but is not a variable in its own right; compare memory
   # addresses to work this out
   refaddr \ ($_[0]) == refaddr \ (${$varsused[0]}) or return;
   return '$' . $varsused[0];
}

# some test code

our $test = 1;
our $test2 = 2;
our $test3 = 3;

say v($test2);
say v(2);
say v(~$test3);
say v($test);
say v($test + 1);
say v(++$test);
say v($test3);

```

We use Devel::Caller (a debugger-like module) to walk the call stack, looking for the call to the function, and return all the operands within the argument, returning them as variable names. If there's more (or less) than one operand, we weren't called with a variable. If the operand wasn't a variable, it won't have a name and we can detect that too.

The trickiest case is if we get a one-operand expression involving a variable, such as `~$x`. We can figure out if this has occurred by taking a reference to the variable directly from the symbol table (using the `${…}` symbolic reference syntax) and comparing its memory address to the value we were passed as an argument (which is, conveniently, passed by reference). If they're different, we have an expression rather than a lone variable.

Note that if we call this function with a preincrement or predecrement expression on a single variable, as in `v(--$x)`, we get `$x` returned. This is because it's actually the variable itself that's being passed to the function in this case; it just gets incremented or decremented beforehand. I hope this doesn't disqualify the answer. (In a way, it makes it better, because it shows that we're checking the argument itself rather than just reading the source code.)

# Answer
> 3 votes
## PHP

While the other PHP submissions only test if the given value matches a value of a global, this version works by taking a reference to the value:

```
// take a reference to the global variable
function f(&$i){
  foreach(array_reverse($GLOBALS) as $key => $value)
    if($key != 'GLOBALS') {
      // Set the value of each global to its name
      $GLOBALS[$key] = $key;
    }

  foreach($GLOBALS as $key => $value)
    if($key != 'GLOBALS' && $key != $value) {
      // The values mismatch so it had a reference to another value
      // we delete it
      unset($GLOBALS[$key]);
      // and update the value to its name again
      $GLOBALS[$key] = $key;
    }

  echo '$', is_array($i) ? 'GLOBALS' : $i, "\n";
}

```

This should now work even if the global variable is a reference to another value at the time of calling.

Test it here.

# Answer
> 3 votes
# Röda

```
f(&a...) {
	a() | name(_) | for str do
		false if [ "<" in str ] else [str]
	done
}

```

Try it online!

Röda has a builtin function for this – `name`. Unfortunately, though, it doesn't return a falsy value when not given a variable.

This code abuses several features of reference semantics. Explanation line by line:

`f(&a...) {`

The function takes a variable number of reference arguments (`&a...`). This is the only way in Röda to create a list of references.

`a() | name(_) | for str do`

At the second line the elements of `a` are pushed to the stream (`a()`). These elements are references if the function was given variables and normal values otherwise.

The elements are iterated using an underscore loop. The underscore syntax is syntax sugar for `for` loops, so `name(_)` is equivalent to `name(var) for var`. The name of the variable used in the `for` loop is of form `<sfvN>` where N varies. (Ie. "`name(<sfv1>) for <sfv1>`") It is illegal for a user-defined variable to contain `<` or `>`, so the generated names don't collide with existing variable names.

The `name()` function returns the name of the given variable. If the element in `a` being iterated is a reference, then it is the variable given to `name`. Otherwise, if the element was a normal value, the variable given to `name` is the underscore variable `<sfvN>`. This is due to the semantics of references in Röda: if a function accepts a reference and the function is passed a reference variable, the passed value does not point to the reference variable but to the variable the reference variable points to.

`false if [ "<" in str ] else [str]`

At the third line we examine if the variable name in the stream contains a `<` character. If so, it is an underscore variable and the value passed to `f` was not a reference. Otherwise we output the name of the reference.

This solution does not work if the variable given to the function is a reference or an underscore variable. However, the question specifies that only global variables must be handled, and they can't be references or underscore variables in Röda.

# Answer
> 1 votes
# PHP

```
function f($v){foreach($GLOBALS as$n=>$x)$x!=$v?:die($n);}

```

if value is found, print variable name and exit. print nothing and don´t exit else.

**61 bytes** to return variable name or `NULL`:

```
function f($v){foreach($GLOBALS as$n=>$x)if($x==$v)return$n;}

```

It will not find named functions, only those assigned to variables.
And a PHP function cannot detect wether a parameter was provided by reference or by value. The function will just return the first name where the value matches the function parameter value.

Test it online

# Answer
> 1 votes
# Ruby, 46 bytes

Feels like the dirtiest code I've ever written for Ruby.

Requires that the global variables you call has a unique value that isn't on any other global variable, because the only way to do this challenge in Ruby is to do an search on all global variables and return the first match. OP says it's ok, and is free to judge if my solution is valid.

Note that global variables start with `$` in Ruby, for if you want to add extra test case stuff.

```
->v{global_variables.find{|n|eval(n.to_s)==v}}

```

Try it online!

# Answer
> 1 votes
## PowerShell

New version but works starting from PowerShell 3.0

```
function p{[scriptblock]::create($myinvocation.line).ast.findall({$args[0]-is[Management.Automation.Language.VariableExpressionAst]},0)[0]|% v*h|% u*|%{($_,!1)[!$_]}}

```

Try It Online!

**Previous version**

```
function p{$t=[management.automation.psparser]::tokenize($myinvocation.line,[ref]@())|? type -match '^[cv]'|? start|% content;($t,!1)[!$t]}

```

Try It Online!

# Answer
> 0 votes
# JavaScript (ES6)

Requires that the value of the variable passed to the function is unique to that variable. Returns `undefined` if a variable wasn't passed.

```
arg=>{
    for(key in this)
        if(this[key]===arg)
            return key
}

```

---

## Try it

For some reason, it throws a cross-origin error in a Snippet when a "literal" is passed.

```
var fn=
    arg=>{
        for(key in this)
            if(this[key]===arg)
                return key
    },
str="string",
int=8,
arr=[1,2,3],
obj={a:1}
console.log(fn(fn))
console.log(fn(str))
console.log(fn(int))
console.log(fn(arr))
console.log(fn(obj))
```

---

## Explanation

Loop through all the entries in the global object (`this`), checking if the value of each one is strictly equal to the value of the argument passed to the function. If a matching entry is found then its key (name) is returned, exiting the function.

---

## Alternative

With the same requirements as above

```
arg=>
    [...Object.keys(this)].filter(key=>
        this[key]==arg
    ).pop()

```

# Answer
> 0 votes
# tcl

```
proc p a {puts [subst $a]}

```

## demo

---
Tags: popularity-contest
---


title: Print the Russian Cyrillic alphabet

text:
# Question
Title: Print the Russian Cyrillic alphabet
Apparently, we really like printing the alphabet in different languages.

How about the Russian Cyrillic alphabet?

Print/output/return this exact text (trailing whitespace is permitted)

```
АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя

```

This is the Russian Cyrillic alphabet with upper and lower case interleaved (eg `AaBbCc...`)

This is so crunch those bytes folks!

# Answer
> 21 votes
# Рапира (Rapira), ~~172~~ 142 bytes

```
ВЫВОД: "АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя"

```

Try it online!

Just for fun, given the challenge. It may not be golfed; I'm not really familiar with the language.

# Answer
> 15 votes
# Mathematica, ~~43~~ 42 bytes

`Alphabet` is a built-in function.

-1 byte from Martin.

```
ToUpperCase@#<>#&/@Alphabet@"Russian"<>""&

```

This may not work on some older versions of Mathematica, but it does work on Wolfram sandbox and Try it online!.

---

Another version without builtin `Alphabet` or `ToUpperCase`:

# Mathematica, ~~82~~ 66 bytes (64 chars)

```
Insert[FromCharacterCode@{#,#+32}&/@(1039+Range@32),"Ёё",6]<>""&

```

or

```
Insert[FromCharacterCode@{#,#+32}&/@1040~Range~1071,"Ёё",6]<>""&

```

Unfortunately Martin's trick (use `a<>b` instead of `{a,b}`) doesn't work here.

Try it online!

# Answer
> 13 votes
# Jelly, 18 bytes

```
40r71s6j25Q+ȷỌżŒl$

```

A full program. Pretty similar in nature to an existing answer by Erik the Outgolfer, but I *think* it's different enough.

**Try it online!**

### How?

```
40r71s6j25Q+ȷỌżŒl$  Main link: no arguments
40r71               inclusive range from 40 to 71: [40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71]
     s6             split into sixes: [[40,41,42,43,44,45],[46,47,48,49,50,51],[52,53,54,55,56,57],[58,59,60,61,62,63],[64,65,66,67,68,69],[70,71]]
       j25          join with 25s: [40,41,42,43,44,45,25,46,47,48,49,50,51,25,52,53,54,55,56,57,25,58,59,60,61,62,63,25,64,65,66,67,68,69,25,70,71]
          Q         de-duplicate: [40,41,42,43,44,45,25,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71]
            ȷ       literal 1000
           +        addition: [1040,1041,1042,1043,1044,1045,1025,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,1057,1058,1059,1060,1061,1062,1063,1064,1065,1066,1067,1068,1069,1070,1071]
             Ọ      cast to characters: "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"
                 $  last two links as a monad:
               Œl     lowercase: "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
              ż       zip: ["Аа","Бб","Вв","Гг","Дд","Ее","Ёё","Жж","Зз","Ии","Йй","Кк","Лл","Мм","Нн","Оо","Пп","Рр","Сс","Тт","Уу","Фф","Хх","Цц","Чч","Шш","Щщ","Ъъ","Ыы","Ьь","Ээ","Юю","Яя"]
                    implicit print: АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя

```

# Answer
> 7 votes
# C#, Java, Javascript 137 bytes

Note: Java is only valid if you replace `=>` with `->`

```
s=>"АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя"

```

Ahhhh!!! Found a shorter way for

# C#, 102 99 bytes

```
a=>string.Concat(new string[32].Select((x,i)=>(x=(char)(i+1040)+"")+x.ToLower())).Insert(12,"Ёё")

```

Shortened it by using a different approach

Try it Online!

# Answer
> 6 votes
# Japt, ~~75~~ ~~38~~ ~~32~~ ~~24~~ ~~23~~ 22 bytes

```
;Bi";<=>?@," c+981 ®+v

```

Test it

* 1 byte saved thanks to ETHproductions.

---

## Explanation

```
;B        :The uppercase alphabet
i         :Prepend ...
";<=>?@," :  this string
c         :Map over the charcodes of each character in the string...
+981      :  and increment them by 981
®         :Map over each character in the string, replacing them with themselves...
+Zv       :   and their lowercase selfs
          :Implicit output of resulting string

```

---

## History

75 bytes, 38 bytes, 32 bytes, 24 bytes

# Answer
> 5 votes
# Jelly, ~~20~~ 19 bytes

```
71r40s26j25+ȷṚỌżŒl$

```

Try it online!

Thanks to Jonathan Allan for posting his answer (even though he outgolfs me) for -1 :)

# Answer
> 5 votes
## PHP, ~~68~~ 66

```
for(;$i++<33;)echo$c=ڀ^"
".chr($i-7?16+$j++:1),mb_strtolower($c);

```

slight improvement over the previous attempt by xoring instead of appending. `ڀ^"\n"` constructs the necessary `"\0xd0\128"` and xors in the lower 7 bit.

# Answer
> 3 votes
# Pyth, 26 bytes

```
X12ssmCM+B+1040d32U32"Ёё

```

```
                  U32     generate the range [0, 1, 2, ..., 30, 31]
     m         d          for each element in the range,
          +1040           add 1040, giving the uppercase cyrillic letter
        +B      32        bifurcate over adding 32, giving [upper, lower]
      CM                  convert each into a character
   ss                     join into a single string
X12                  "Ёё  insert this string at index 12

```

Try it here.

# Answer
> 3 votes
## JavaScript (ES6), 106 bytes

```
f=
_=>"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ".replace(/./g,c=>c+c.toLowerCase())
console.log(f())
```

# Answer
> 3 votes
# 05AB1E, 22 bytes

```
žv47ŸžB+çJ6т‚£'ЁýDløJ

```

Try it online!

**Explanation**

```
žv47Ÿ                    # push range [16 ... 47]
     žB+                 # add 1024 to each
        çJ               # convert to a string of characters with those code points
          6т‚£           # split into 2 pieces, the first being 6 chars long
              'Ёý        # merge the 2 strings on "Ё"
                 Dlø     # zip with a lower case copy
                    J    # join to a string

```

# Answer
> 3 votes
# 05AB1E, 20 bytes = 18 bytes + 2 UTF-8 bytes

```
T„(GÇ«ŸçJ„ЁЖ6ǝDløJ

```

Try it online!

---

Credit to Emigna for the `lowercase` trick and for  isntead of `3Tm`.

---

# How?

```
T                  # Push 10.               | [10]
 „(G               # Push "(G"              | [10, "(G"]
    Ç              # Convert to ASCII.      | [10, [40, 71]]
     «             # Concatenate.           | [[1040, 1071]]
      Ÿ            # Range.                 | [[1040, ..., 1071]
       çJ          # Convert to char, join. | ["А..Я"]
         „ЁЖ       # Push "ЁЖ"              | ["А..Я", "ЁЖ"]
            6ǝ     # Replace "Ж" w/ "ЁЖ"    | ["А.Ё.Я"]
              Dl   # Duplicate, lowercase.  | ["А..Ё..Я", "а..ё..я"]
                øJ # Zip together and join. | ["АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя"]

```

---

Alternate 20 byte version (no UTF-8): `T„(GÇŸ„.Ç6ǝ˜«çJDløJ`

Even more random 20 byte nonsense: `T„(GÇŸ„.Ç6ǝ˜«vyçDlJ`

(The key takeaway is that I don't think I'm getting below 20 here).

# Answer
> 2 votes
# Braingolf, 58 bytes

```
"ABCDEF2GHIJKLMNOPQRSTUVWXYZ[\\]^_`"{#Ϗ+..#Ёe#P:# |+}>&@

```

Try it online!

Woo!

## Explanation

Adds `Ϗ` (975) to each character in ABCDEF2GHIJKLMNOPQRSTUVWXYZ\[\\\]^\_\` Then duplicates and adds space (32), unless the character is `Ё`, in which case it adds P (80)

# Answer
> 2 votes
# Java, 93 bytes

```
s->"АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя"

```

Source file should be saved in `Windows-1251` encoding so the source makes for 71 bytes, plus flag to compiler `-encoding WINDOWS-1251` for 22 bytes more.

# Answer
> 2 votes
# Python 3,  ~~69~~  66 bytes

-3 bytes using the form (using `'%c'` to directly apply `chr()`) from totallyhuman's answer, do go give some credit!

```
v=32
while v:print('Ёё'*(v==26),end='%c%c'%(1072-v,1104-v));v-=1

```

A full program (two double-byte characters used, `Ё` and `ё`).

**Try it online!**

# Answer
> 2 votes
# Dyalog APL, ~~55~~ 47 bytes

*8 bytes saved thanks to @Zacharý*

```
⎕UCS 66⍴⍉2 33⍴1025+(14+⍳6),0,(20+⍳32),80,52+⍳26

```

Try it online!

# Answer
> 1 votes
# 05AB1E, ~~64~~ ~~47~~ 46 bytes

```
5ÝD1040+s1072+‚øžB>D80+‚«25ÝD1046+s1078+‚ø)˜çJ

```

Try it online!

# Answer
> 1 votes
# Pyth, 71 bytes

```
."Ёё    kdâ¿Ããä©ÃòçÅD´fjÃØÜr
ÔE®8CðÒº[£÷6ÓþC0"

```

Try it online!

# Answer
> 1 votes
# Python 3, ~~96~~ 92 bytes

* *@Mayube suggested this to save 2 bytes, and succeeded to golf it down by 1 byte by declaring `chr(i)`.*
* *@Rod golfed 4 bytes by removing `chr(i)`.*

```
for i in[chr(ord(i)+975)for i in"ABCDEF2GHIJKLMNOPQRSTUVWXYZ[\\]^_`"]:print(end=i+i.lower())

```

Try it online!

---

# Python 3, ~~104~~ 99 bytes

Any suggestions are welcome.

```
for i in"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ":print(end=i+i.lower())

```

Try it online!

# Answer
> 1 votes
# C# (.NET Core), 94 93 90 bytes

```
_=>{var r="";for(var i='А';i<='Я';)r+=""+i+(char)(i+32)+(i++=='Е'?"Ёё":"");return r;}

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 29 bytes

```
1040ÐU5+ŸžB>X6+D25+Ÿ)˜çDl)ø˜J

```

Try it online!

Uses the lowercase / uppercase trick from the python answer

### Explanation

```
1040ÐU5+ŸžB>X6+D25+Ÿ)˜çDl)ø˜J
1040                          # Push 1040
    Ð                         # Triplicate top of stack
     U                        # Saves top of stack in X
      5+Ÿ                     # Push range [1040, ..., 1045]
         žB>                  # Push 1025
            X                 # Push X (1040)
             6+D25+Ÿ          # Push range [1046, ..., 1071]
                    )         # Wrap stack to array
                     ˜        # Flatten array
                      ç       # Convert to character
                       Dl     # Create a lowercase copy
                         )ø   # Zip both together
                           ˜J # Flatten and join
                              # Implicit output

```

# Answer
> 1 votes
# PHP\>=7.0, 77 Bytes

```
for($t=IntlChar;$i++<33;)echo$c=$t::chr($i-7?1040+$j++:1025),$t::tolower($c);

```

IntlChar Class

# PHP, 136 Bytes

```
for(;$i<mb_strlen($r=АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ);)echo$m=mb_substr($r,$i++,1),mb_strtolower($m);

```

PHP Sandbox Online

# PHP, 136 bytes

```
<?=АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя;

```

Try it online!

# Answer
> 1 votes
# Bash+coreutils, ~~101~~ ~~100~~ ~~93~~ ~~92~~ 74 bytes

```
printf %b\\n \\u04{51,{3,4}{{0..9},{a..f}}}|sort|sed 's/./\u&&/'|tr -d \\n

```

This requires a UTF-8 locale such as `ru_RU.utf8` (English UTF-8 locales also sort correctly). I've not added any score for this, as per the consensus on meta.

# Answer
> 1 votes
# Python 3, 66 bytes

```
for i in range(32):print(end='%c%c'%(i+1040,i+1072)+'Ёё'*(i==5))

```

Try it online!

# Answer
> 1 votes
# Ruby, ~~59 56 55 54~~ 51 bytes

```
32.times{|x|$><<((x==6?"Ёё":"")<<x+1040<<x+1072)}

```

Thanks to manatwork for at least 4 bytes.

Try it online!

# Answer
> 1 votes
# Japt, ~~26~~ 24 bytes

22 bytes of code (encoded in UTF-8), +2 for the `-P` flag.

```
#h0o#k2_dÃi'Ё6
®+Zv

```

Similar to the below method, except instead of pairing two arrays, I join each capital letter with itself, lower-cased.

Try it Online!

## 26 byte solution:

I had some help from @Shaggy, who discovered that `Ё` wasn't in the `[1040...1071]` char range.

```
#h0o#k2_dÃi'Ё6
íUmv)c

```

## Explanation:

```
#h0o#k2_dÃi'Ё6
íUmv)c
                   // Implicit U =
   o               //   Range
#h0                //     [1040...
    #k2            //             1071]
       _           //   Map; At each char,
         d         //     Get the char-code
          Ã        //   End mapping;
           i'Ё6    //   Insert "Ё" into index 6;
í                  // U paired with:
 Um                //   U, where each char:
   v               //   Converted to lowercase
     c             // Flatten
-P                 // Join into a string

```

Try it online!

# Answer
> 1 votes
# Ruby, 60 bytes

```
u=?Џ
l=?Я
32.times{$><<u.next!+l.next!+(l==?е?"Ёё":"")}

```

(Just a demonstration of `String#next!`, the multibyte literals ruin the 55 characters score.)

Sample run:

```
bash-4.4$ ruby -e 'u=?Џ;l=?Я;32.times{$><<u.next!+l.next!+(l==?е?"Ёё":"")}'
АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпРрСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя

```

Try it online!

# Answer
> 1 votes
# Charcoal, ~~45~~ ~~44~~ 26 bytes

```
ＦＥ⮌⪫⪪…⮌…γ⁷²¦³²Ｌαi℅⁺℅ιφ⁺↥ιι

```

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

```
ＦＥ⮌⪫⪪…⮌…γ⁷²¦³²Ｌαi

```

Take the first 72 printable ASCII characters, reverse them, then take the first 32 of those (this is actually shorter than slicing and reversing, although slicing didn't exist at original time of posting anyway), then insert the `i` after the `N`, then reverse again. The resulting characters happen to have ASCII codes that are exactly 1000 less than the desired Russian lower case letters.

```
  ℅⁺℅ιφ

```

Calculate the Russian lower case letter by adding the predefined variable `φ` (`f`) which has the value 1000.

```
    ⁺↥ιι

```

Print the upper and lower case letters. (`«↥ιι` would probably also work.)

# Answer
> 0 votes
# Java (OpenJDK 8), ~~91~~ 88 bytes

```
()->{String s="";for(char i=0,u=1039,l=1071;i<33;)s=i++==6?s+"Ёё":s+ ++u+ ++l;return s;}

```

Try it online!

Encoded in Windows-1251. Must use a default Russian Windows installation.

# Answer
> 0 votes
## Alice, 31 bytes

```
gr'v6R,' &w'ѷ~-.O' +'С'ёSOk@

```

Try it online!

### Explanation

```
g       Read the first character of the source code. That's g itself, with
        code point 103, so this pushes 103. The exact value is irrelevant
        but we need something greater than 31.
r       Range. Turns 103 into 0, 1, 2, ..., 103.
'v      Push 118.
6R,     Move it down the stack by 6 elements, so the top of the stack is
        ..., 96, 97, 118, 98, 99, 100, 101, 102, 103.
' &w    Push the current IP address to the return address stack 32 times,
        which will cause the following part to be executed 33 times.

  'ѷ~-    Subtract the value on top of the stack from 1143, which gives the
          33 code points of the upper case letters.
  .O      Print a copy of this value as a character.
  ' +     Add 32. This turns the upper case letters in the main range to their
          lower case counterparts. However, this doesn't work for Ё/ё, where
          we obtain C instead.
  'C'ёS   Replace the divisor 1057 with 1105. The only value among the 33 which
          is divisible by 1057 is 1057 (C) itself, so that it simply gets turned into
          1105 (ё).
  O       Output the lower case character.

k       Jump back to the w as long as there's a copy on the return address stack.
@       Terminate the program.

```

# Answer
> 0 votes
## Alice, 33 bytes

```
/ZАе"е"ёяSr@
\"'Я"rЁа""o/

```

Try it online!

My other Alice solution was entirely in Cardinal mode, this one is entirely in Ordinal mode. It's conceptually much simpler, but unfortunately two byte longer.

### Explanation

Ignoring the Ordinal template, the program is entirely linear:

```
"АЯ"r"ая"rZ'е"еЁё"So@

```

Alice does have a built-in to convert between lower and upper case, but unfortunately in the Ruby interpreter it only works on ASCII letters, so we still have to get both ranges separately.

```
"АЯ"r     Push "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ".
"ая"r     Push "абвгдежзийклмнопрстуфхцчшщъыьэюя".
Z         Zip. Interleave the two strings.
'е"еЁё"S  Replace "е" with "еЁё".
o@        Print the result and terminate the program.

```

# Answer
> 0 votes
# AWK, 79 bytes

```
BEGIN{for(x=1039;++i<33;){f="%c%c";f=i==6?f f:f;printf f,i+x,i+32+x,1025,1105}}

```

Try it online!

This works on TIO, not sure if it's dependent on installed char-set.

# Answer
> 0 votes
# Haskell, 80 bytes

```
import Data.Char;f=putStr$(\x->[x,toLower x])=<<['А'..'Е']++'Ё':['Ж'..'Я']

```

# Answer
> 0 votes
# Perl, 37 bytes

```
print map{chr.chr($_+32)}(1040..1071)

```

It's annoying that Perl's character autoincrement only works for the Latin alphabet. I could save so many characters if it worked outside that range.

---
Tags: code-golf, string, kolmogorov-complexity, alphabet
---


# Question
Title: Check if a string is the anagram of another
# Skat

I'm a fan of anagrams, so given two strings `s1` and `s2` write a program or function that outputs a truthy value if `s2` is an anagram of `s1`, and a falsey value otherwise (not accounting for spaces and capital letters).

For example:

Input: `s1 = "Anagram"; s2 = "Nag a ram"`

```
true

```

Input: `s1 = "stack overflow"; s2 = "fewer kool cats"`

```
false

```

Input: `s1 = "apple rocks"; s2 = "paler spock"`

```
true

```

# Rules

* Program and function allowed.
* Shortest code in bytes wins.

Duck logo!

# Answer
# 05AB1E, 8 bytes

```
lðδKJ€{Ë

```

Try it online!
> 2 votes

# Answer
# Jelly, 8 bytes

```
ŒlḟṢ¥€⁶E

```

Try it online!
> 0 votes

# Answer
# Python 3, 74 bytes

```
def f(a,b):print(g(a)==g(b))
g=lambda a:sorted(a.upper().replace(" ", ""))

```

Try it online!
> 0 votes

# Answer
# Japt, 13 bytes

```
v rS á øVv rS

```

Test it
> 0 votes

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