title: Compare two numbers given as strings

text:
# Question
Title: Compare two numbers given as strings
I have a problem at work. I need to compare two numbers that come as strings from two different databases. The numbers may come with leading zeroes and/or leading/trailing spaces. So I may have `"0001 "` from one database and `" 1 "` from the other one.

I solved the problem in C# with the following code:

> `Func<string, string, bool> f = (a,b) => int.Parse(a.Trim()) == int.Parse(b.Trim())`

**The challenge**

This is a really simple challenge, suitable for beginners and any kind of esoteric languages. Given two numbers as strings that may come with leading zeroes and/or leading/trailing spaces, write the shortest code that checks if the two strings represent the same number.

* The inputs need to be two strings or the equivalent in your language (a char array is OK), and they will always represent integer values greater than zero.
* The output must be any two consistent values that represent a truthy value and a falsey value.

**Examples**

```
A          B          Result
----------------------------
"0001"     "1    "    true
"1450"     "1450 "    true
"0010001 " " 10001  " true
"0010000"  "  10  "   false
"101023"   "101024"   false

```

This is , so may the shortest code for each language win!

# Answer
# Javascript, 11 bytes

```
a=>b=>+a==b

```

Abusing Javascript's casting rules a bit; `+a` coerces `a` into a numeric type.

*-6 bytes* thanks to Shaggy and Martin Ender♦

Also a cool take by LiefdeWen:

```
a=>b=>~~a==~~b

```
> 22 votes

# Answer
# 05AB1E, 1 byte

```
Q

```

Try it online!

**Explanation**

Comparison for equality `Q` will automatically try to evaluate strings as ints before comparing.
> 20 votes

# Answer
# Operation Flashpoint scripting language, 33 bytes

```
f={call format(["%1==%2"]+_this)}

```

**Call with:**

```
hint format["%1\n%2\n%3\n%4\n%5",
    ["0001", "1    "] call f,
    ["1450", "1450 "] call f,
    ["0010001 ", " 10001  "] call f,
    ["0010000", "  10  "] call f,
    ["101023", "101024"] call f]

```

**Output:**

## Alternative version (41 bytes):

```
f={{t=call _x;r=t==s;s=t}forEach _this;r}

```

Still 5 bytes shorter than the more straightforward `f={t=_this;call(t select 0)==call(t select 1)}`

**39 bytes:**

```
f={{t=call _x;r=t==s;s=t}count _this;r}

```

`count` (which returns the size of an array) works instead of `forEach`, because you can give it a "lambda" that is used as a condition to count only the array elements that meet that condition. The "condition" used in this case is not a valid condition, but it doesn't matter here because it doesn't cause an error and the return value of the `count` is not needed.
> 20 votes

# Answer
# Taxi, 488 bytes

```
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Equal's Corner.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:n 1 l 1 l 1 l.Switch to plan "b" if no one is waiting.'1' is waiting at Writer's Depot.[b]'0' is waiting at Writer's Depot.Go to Writer's Depot:n 1 l 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l.

```

Try it online!

Ungolfed:

```
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Equal's Corner.
Pickup a passenger going to Equal's Corner.
Go to Equal's Corner: north 1st left 1st left 1st left.
Switch to plan "b" if no one is waiting.
'1' is waiting at Writer's Depot.
[b]
'0' is waiting at Writer's Depot.
Go to Writer's Depot: north 1st left 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st right 2nd right 1st left.

```

Taxi is (relatively) well-suited to this challenge because strings are the only input or output type allowed. `The Babelfishery` is what converts strings to number (and vice versa) and it handles stripping all the spaces and leading zeroes. It will also handle negative numbers if the `-` is immediately before the first digit. After that, `Equal's Corner` checks the two values against each other and `Writer's Depot` provides the output in string format. Output is `1` for truthy and `0` for falsey.
> 13 votes

# Answer
# C (gcc), 27 bytes

```
f(s,t){s=atoi(s)==atoi(t);}

```

With `-O0` (which is the default setting).

Try it online!

# C, 32 bytes

```
f(s,t){return atoi(s)==atoi(t);}

```

Try it online!
> 10 votes

# Answer
# , 4 bytes

```
=&do

```

Compare `=` after `&` evaluating `do`. Can also be `=&".` Try it online!
> 8 votes

# Answer
## Retina, 11 bytes

```
.+
$*
D`
¶$

```

Try it online!

Input is linefeed separated, but the test suite uses comma separation for convenience. Prints `1` for equality and `0` for inequality.

### Explanation

```
.+
$*

```

Convert each line to unary. This ignores leading zeros and spaces.

```
D`

```

Deduplicate: clear the second line if both are the same.

```
¶$

```

Check that the string now ends in a linefeed.
> 7 votes

# Answer
# Brain-Flak, 22 bytes

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

```

Try it online!

Saved 4 bytes thanks to Jo King.
> 4 votes

# Answer
# Python 3, 25 bytes

```
lambda a,b:int(a)==int(b)

```

Try it online!
> 4 votes

# Answer
# Triangularity, 17 bytes

```
..)..
.Ii).
@Ii=.

```

Try it online!

Triangularity is, for once, competitive!

### How it works

Triangularity requires the code to have a triangular distribution of the dots. That is, the length of each row must be equal the number of rows multiplied by 2 and decremented, and each row must have (on each side) a number of dots equal to its position in the program (the bottom row is row 0, the one above it is row 1 and so forth). Keeping this in mind, let's analyse how the code works:

```
..).. || Push a 0 onto the stack.
.Ii   || Get the 0th input and cast it to an integer.
   ). || Push another 0 onto the stack.
@I    || Increment the ToS => 1. Get the first input.
  i=. || Then cast it to an integer and compare their equality.

```
> 3 votes

# Answer
# APL (Dyalog), 4 bytes

*3 bytes saved thanks to @Adám*

```
=/⍎¨

```

Try it online!
> 3 votes

# Answer
# Japt, 3 bytes

```
¥Vn

```

Try it

Converts the second input to an integer and compares equality with the first.
> 3 votes

# Answer
## Alice, 7 bytes

```
X/n
o@i

```

Try it online!

Any non-digit separator works. Prints `1` for equality and `0` otherwise.

### Explanation

```
X   XOR, does nothing.
/   Switch to Ordinal mode.
i   Read all input as a string.
/   Switch to Cardinal mode.
X   XOR. Implicitly finds all integers in the string and pushes them separately
    onto the stack. The XOR gives 0 if the values are identical.
n   Logical NOT. Gives 1 for equal inputs and 9 otherwise.
/   Switch to Ordinal.
o   Print the 0 or 1 as a string.
/   Switch to Cardinal.
@   Terminate the program.

```
> 3 votes

# Answer
# jq, 24 characters

```
map(tonumber)|.[0]==.[1]

```

The 2 strings are passed as items of an array.

Sample run:

```
bash-4.4$ jq 'map(tonumber)|.[0]==.[1]' <<< '["0010001 ", " 10001  "]'
true

bash-4.4$ jq 'map(tonumber)|.[0]==.[1]' <<< '["0010000", "  10  "]'
false

```

Try it online! (All test cases)
> 3 votes

# Answer
# Excel VBA, 27 16 Bytes

-9 Thanks to @Nayrb and @TaylorScott

```
[C1]=[A1]-[B1]=0

```

Where you input the values on the Cells with `'string`.

Where `x` and `y` are the input Strings and `z` is a Boolean output.

If CInt(x)=CInt(y) Then z=1

Using CInt
> 3 votes

# Answer
# Husk, 3 bytes

```
¤=r

```

Try it online!

### Explanation

```
¤    -- combine both arguments of ..
 =   -- .. equality ..
  r  -- .. with read

```
> 3 votes

# Answer
# PowerShell, 20 bytes

```
param($a,$b)+$a-eq$b

```

Similar to the JavaScript answer, just longer because PowerShell doesn't have currying. Uses `+` to cast the first string to integer, and then the `-eq`uals automatically casts the second string to integer. Output is True/False.

Try it online!
> 3 votes

# Answer
# T-SQL, 35 bytes

Per our standards, data is input via pre-existing table `t` with `varchar` fields `a` and `b`.

```
    SELECT IIF(ABS(a)=ABS(b),1,0)FROM t

```

Returns `1` if they match, `0` if they don't.

A few of SQL's mathematical functions (including `ABS`, `FLOOR` and `CEILING`) will do an implicit conversion to numeric if given string parameters, this is shorter than an explicit `CAST(a AS INT)` or `CONVERT(INT,b)`, and works in this case since we know the input values are always positive.

`IIF` is specific to MS SQL 2012 and above, so no guarantee about other implementations.
> 3 votes

# Answer
# Jelly, 8 bytes

```
t€⁶V€€ḌE

```

Try it online! or see the **test suite**

35 answers, and no Jelly submission? Takes the argument as a list (`["0001", "1 "]` for the first example)

## How it works

```
t€⁶V€€ḌE - Main link. Argument: list       e.g.    ["0001", "1    "]
 €       - For €ach element...                     ["0001", "1"]
t        -   trim from both sides...
  ⁶      -   spaces
     €   - For €ach element...
   V€    -   evaluate €ach character               [[0, 0, 0, 1], [1]]
      Ḍ  - Convert from digits                     [1, 1]
       E - Are they equal?                         1

```
> 3 votes

# Answer
# Excel, 8 bytes

```
=A1-B1=0

```

Excel does the string to num conversion for us.

(To input as string, prefix values with `'`.)
> 3 votes

# Answer
# Q (Kdb+), 13 bytes

```
=/["J"$(x;y)]

```

## Explanation

(x;y) : a list of the two inputs.

"J"$ : casting each input to a long (7j) type from string (10c), which can correctly interpret
white space and leading 0s.

=/ : checks equality over elements in a list (each subsequent pair).
As there is only one pair, returns single boolian 0b/1b.
> 3 votes

# Answer
# PowerShell, 19 bytes

```
$args-join'-eq'|iex

```

Try it online!

`-join` the argument array (`$args`) with the string representation of the comparison operator (`-eq`) then evaluate the expression with `Invoke-Expression` (`iex`).
> 3 votes

# Answer
# , ~~28~~ 27 bytes

```
!diff(as.double(scan(,'')))

```

Reads numbers as strings, converts them to doubles and checks if their difference is not zero.

Try it online!

*−1 byte thanks to Giuseppe*
> 3 votes

# Answer
# Haskell, 20 bytes

*-11 bytes thanks to Laikoni. -2 bytes thanks to Zgarb.*

```
a#b=0+read a==read b

```

Try it online!
> 2 votes

# Answer
# Lua, 20 bytes

```
print(...-arg[2]==0)

```

Try it online!
> 2 votes

# Answer
# Sinclair ZX81/Timex TS1000/1500 BASIC, ~29 tokenized BASIC bytes

New solution thanks to Neil (thanks for the tip).

```
 1 INPUT A$
 2 INPUT B$
 3 PRINT VAL A$=VAL B$

```

This solution requires user input, so enter in two strings with white spaces and/or leading zeros, or enter two strings of non-equal numeric value; `0` is false and `1` is true once line three has compared the value of each string entered.

### Old solution: Sinclair ZX81/Timex TS1000/1500 BASIC, ~46 tokenized BASIC bytes

```
 1 LET A$=" 001 "
 2 LET B$="1"
 3 PRINT (VAL A$=VAL B$)

```

The actual check is done in line three, which is only ~16 tokenized BASIC bytes; so entering each test case pair using direct mode will save ~30 bytes from the listing. Note that this byte count does not include the `var stack`.
> 2 votes

# Answer
# Gema, 21 characters

```
*\n*=@cmpn{*;*;0;1;0}

```

No boolean in Gema. As the `@get-switch{}`/`@set-switch{}` functions use 0 and 1 to represent switch statuses, also used 0 and 1.

The 2 strings are passed on separate input lines.

Sample run:

```
bash-4.4$ gema '*\n*=@cmpn{*;*;0;1;0}' <<< $'0010001\n10001  '
1

bash-4.4$ gema '*\n*=@cmpn{*;*;0;1;0}' <<< $'0010000\n  10  '
0

```
> 2 votes

# Answer
# Perl 5, 9 + 1 (`-p`) = 10 bytes

```
$_=$_==<>

```

try it online
> 2 votes

# Answer
# Stacked, 8 bytes

```
[#~\#~=]

```

Try it online!

## Explanation

```
[#~\#~=]   anonymous function
 #~        eval TOS
   \       swap top two
    #~     eval TOS
      =    push equality of top two

```
> 2 votes

# Answer
# Swift, 80 79 78 bytes

```
import Foundation;func r(g:[NSString])->Bool{return g[0].intValue==g[1].intValue}

```

Try it online!
> 2 votes

# Answer
# Attache, 11 bytes

```
Same@Map&:N

```

Try it online!

This takes an array of strings, such as `V["0001", "1 "]`. Simply stated, `Map&:N` is a function that maps `N` over its argument, and `Same` checks that the array contains only equal members. (Fun fact: this function works for more than 2 string arguments.)
> 2 votes

# Answer
# AWK, 12 bytes

```
{$0=$1==$2}1

```

Try it online!

# AWK, 9 bytes

```
$0=$1==$2

```

Alternate version: outputs `1` on match, otherwise outputs nothing

Try it online!
> 2 votes

# Answer
# SNOBOL4 (CSNOBOL4), 42 bytes

```
	OUTPUT =EQ(EVAL(INPUT),EVAL(INPUT)) 1
END

```

Try it online!

Outputs 1 for truthy, nothing for falsey. Since  (space) is the concatenation operator in SNOBOL, `EVAL`ing a number with leading/trailing spaces yields the number itself, and it also neatly takes care of any leading zeroes. `EQ` tests for numerical equality, conditionally setting `OUTPUT` to 1 on `Success`.
> 2 votes

# Answer
# Java 8, ~~58~~ 51 bytes

### 7 bytes thanks to Kevin

```
b->c->new Long(b.trim()).equals(new Long(c.trim()))

```

Try it online!

## Explanation

Trims off spaces, casting to Long removes leading zeros, and then returns boolean value if they are equal or not.
> 2 votes

# Answer
# APL (NARS2000), 7 bytes

```
=⍥⍎

```

Well, yes, I do know NARS2000 can't compete over Dyalog here since it uses Unicode, but I thought I'd rather show off  (called **Composition** in NARS2000, even though it's actually unrelated to function composition), something Dyalog doesn't have as a built-in and I haven't ever seen used here. In Dyalog, it has to be implemented as `{(⍵⍵⍺)⍺⍺⍵⍵ ⍵}`. What it does is call the right operand monadic function on both the left and right argument, and then call the left operand dyadic function on the results.

Here, the right operand is  (**Execute**, i.e. eval) and the left operand is `=` (**Equal To**, i.e. check if its arguments are equal).
> 2 votes

# Answer
# , ~~37~~ 35 bytes

```
pryr::f(as.double(x)==as.double(y))

```

There's probably some cleverer way to coerce strings to numerics but I haven't figured it out yet.

Try it online!
> 2 votes

# Answer
# \>\<\>, 2 + 3 = 5 bytes

```
=n

```

Try it online!

Uses the `-v` flag to pass the values into the program. This automatically converts them to numbers, removing the spaces and leading 0s. It then outputs if the two are equal, and exits with an error as it tries to compare an empty stack.
> 2 votes

# Answer
# dc, 9 bytes

```
[1p]sQ?=Q

```

Outputs 1 if the numbers are equal, or nothing if unequal. The input numbers are separated by ',', and this gives a warning since data is code in dc. I wasn't sure if space was allowed as delimiter, so I chose one that doesn't stop the program.

Try it online!
> 2 votes

# Answer
## Batch, 89 bytes

```
@call:c %1
@set e=%errorlevel%
@call:c %2
@if %e%==%errorlevel% echo 1
:c
@exit/b%~1

```

Prints `1` if the two numbers are the same. Explanation: Batch's numeric processing usually uses leading zeros to indicate an octal number, however `exit/b` always takes a decimal number. The `~` removes any quotes that would be needed to pass leading or trailing spaces in the parameter.
> 2 votes

# Answer
# Ruby, 23 bytes

```
s=->x,y{x.to_i==y.to_i}

```
> 2 votes

# Answer
# Tcl, 45 bytes

```
proc x a\ b {expr [scan $a %d]==[scan $b %d]}

```

Try it online!
> 2 votes

# Answer
# Perl 6, 4 bytes

```
*==*

```

Test it

The `==` operator converts to Numeric which ignores leading and trailing whitespace, and leading `0`'s get ignored just the same. (`0o127` is how you write an octal)

The two `*` are just there to turn it into a lambda that takes two arguments.
> 2 votes

# Answer
# Julia 1.0, 26 bytes

```
~x=parse(Int,x);a%b=~a==~b

```

Try it online!
> 2 votes

# Answer
# Julia 1.0, 30 bytes

```
a%b=eval(Meta.parse("$a==$b"))

```

Try it online!

Some meta programming fun, not the shortest solution though
> 2 votes

# Answer
# Pyth, 4 bytes

```
qFsM

```

Try it online!

Int-parse each element of the input list with `sM(Q)`, then `F`old over e`q`uality.
> 1 votes

# Answer
# Wolfram Language, 27 bytes

```
ToExpression[#1<>"=="<>#2]&

```

Test cases:

```
In[1]:= ToExpression[#1 <> "==" <> #2] &["0001", "1"]
Out[1]= True

In[2]:= ToExpression[#1 <> "==" <> #2] &["1450", "1450 "]
Out[2]= True

In[3]:= ToExpression[#1 <> "==" <> #2] &["0010001", " 10001"]
Out[3]= True

In[4]:= ToExpression[#1 <> "==" <> #2] &["0010000", "  10  "]
Out[4]= False

In[5]:= ToExpression[#1 <> "==" <> #2] &["101023", "101024"]
Out[5]= False

```
> 1 votes

# Answer
# Clean, 52 bytes

```
import StdEnv
$n=toInt{#c\\c<-n|c>' '}
?n=(==)($n)o$

```

Try it online!
> 1 votes

# Answer
# C++ (gcc), 65 bytes

```
#include<cstdlib>
auto a(auto b,auto c){return atoi(b)==atoi(c);}

```

Try it online!

I initially tried used a lambda expression, but `auto a=[]` is three more characters, and less one more for no trailing semicolon. On the other hand, since `atoi` is not referenced until the lambda is instantiated, could I delete the `#include` and put that in the test harness footer instead?
> 1 votes

# Answer
# Javascript, 6 bytes

Pretty standard stuff, but using Javascript's auto type casting

```
!(a-b)

```

Or if we don't need it as a function (19 bytes)

```
let f=(a,b)=>!(a-b)

```

Try it online! https://jsfiddle.net/pgz4ctLy/2/
> 1 votes

# Answer
## PHP 5.6+, 16 (42 when callable) bytes

The minimum code that meets the puzzle's requirements (16 bytes):

```
(int)$a==(int)$b

```

In callable form (42 bytes):

```
function f($a,$b){return(int)$a==(int)$b;}

```

Try it online, with tests

# Explanation

Declare a regular function with a single-character name `f` with two, otherwise undetermined parameters. It returns the result of comparing both arguments after casting each to integers, which safely removed the padding and whitespace. The code could have been made 2 bytes shorter by converting the function to a closure, but then the closure would not be assigned (which takes another 3 bytes), and therefore not callable.
> 1 votes

# Answer
## Mumps, 7 bytes

```
W +X=+Y

```

In Mumps, all data are strings, the '+' operator evaluates the string to a numeric value. There is no implicit output function, so the 'W' (Write) function provides the output.
> 1 votes

# Answer
# K (oK), 5 bytes

**Solution:**

```
=/.:'

```

Try it online!

**Examples:**

```
=/.:'("0001";"1    ")
1
=/.:'("1450";"1450 ")
1
=/.:'("0010001";" 10001  ")
1
=/.:'("0010000";"  10  ")
0
=/.:'("101023";"101024")
0

```

**Explanation:**

Convert each input to an integer, and then check for equality.

```
=/.:' / the solution
  .:' / value (.:) each ('), converts char list to integer
=/    / equality (=) over (/)

```
> 1 votes

# Answer
# Implicit, 5 bytes

```
'ì'ì=

```

Try it online!

```
'ì'ì=
'      «read string, push to stack                  »;
 ì     «swap type (integer/string) of top of stack  »;
  'ì   «do it again for the second integer string   »;
    =  «compare for equality                        »;

```
> 1 votes

# Answer
## C# (32 bytes)

```
a=>b=>int.Parse(a)==int.Parse(b)

```

Try it online

as already mentioned in the comments, you can do it shorter than the C# provided in the question. I wrote this thinking I was clever before reading the reply to the comments by the OP. :)
> 1 votes

# Answer
**R, 55 bytes**

```
V<-strtoi(gsub(" ","",c(A,B),fixed=T),base=9)
V[1]==V[2]

```

This is my first attempt at codegolf; gave it my best try. Suggestions welcome!

Assumptions:

1. The inputs are given as strings A and B
2. The integers contained are less than 1888888888. Larger values will cause strtoi() to return NA.
> 1 votes

# Answer
# Vyxal, 3 bytes

```
"⌊≈

```

Try it Online!

### Explained

```
"⌊≈
"   # pair both inputs into list
 ⌊  # floor
  ≈ # all items equal?

```
> 1 votes

# Answer
# J-uby, 9 bytes

```
:*&Z|+:==

```

Attempt This Online!

## Explanation

```
:* & Z |       # Map with to_i (Z), then
         +:==  # Compare

```

I think this would be 7 bytes with J-uby’s `**` operator:

```
Z**+:==

```

…but it’s broken or removed in the current version.
> 1 votes

# Answer
# nroff, 51 bytes

1 and 0 for truthy and falsey. Wish type convertion were available. `.nr X \\$1=\\$2` did not work for some input.

```
.de F
.nr X \\$1
.nr Y \\$2
.nr X \\nX=\\nY
\\nX
..

```

Attempt This Online!
> 1 votes

# Answer
# Thunno 2, 2 bytes

```
Nạ

```

Attempt This Online!

The "cast to integer" built-in (`N`) handles leading/trailing spaces and leading zeros. Then, we can just check equality with .
> 1 votes

# Answer
# Stratos, 3 bytes

```
_=_

```

Both of the `_` take an input as a string and convert it to a number, then negate it.

Java converts the input to a number by removing 0s and spaces.

The `=` takes the results of this and checks for equality

Try it!
> 0 votes

# Answer
# Pyt, 1 byte

```
=

```

Explanation

```
         Implicitly takes two inputs, and casts them to integers/floats if possible.
=        Checks if the two are equal

```

Try it online!
> 0 votes

# Answer
# FALSE, 36 bytes

```
[0[^$9>][$32>[48-+10*]?]#%10/]$!\!=.

```

Numbers are received from the console, separated by a tab character. True=`-1`, False=`0`.
> 0 votes

# Answer
# Ruby, 21 bytes

Pretty boring.

```
->a,b{a.to_i==b.to_i}

```

Attempt This Online!
> 0 votes

# Answer
# Factor, 29 bytes

```
[ [ " "without dec> ] same? ]

```

Try it online!

Factor's number parser can't handle spaces so I have to remove them first.
> 0 votes

---
Tags: code-golf, string, number, decision-problem, parsing
---


title: Tips for golfing in C++

text:
# Question
Title: Tips for 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.

(Tips that apply to C as well can be found in Tips for golfing in C \- but note that some C tips don't work in C++. For example, C++ *does* require function prototypes and return values.)

# Answer
The ternary conditional operator `?:` can often be used as a stand in for simple `if`--`else` statements at considerable savings.

It is of special value in that it can be used to select alternate lvalues as in

```
#include <iostream>
#include <cstdlib>
int main(int c, char**v){
  int o=0,e=0,u;
  while(--c) ((u=atoi(v[c]))%2?o:e)+=u;
  std::cout << "Sum of odds " << o <<std::endl
            << "Sum of evens " << e <<std::endl;
}

```
> 29 votes

# Answer
Sometimes you can save two characters by using the fact that static storage duration variables (that especially includes all global scope variables) are automatically zero-initialized at the beginning (unlike automatic variables where you have no such guarantee). So instead of

```
int main()
{
  int a=0;
  // ...
}

```

you can write

```
int a;
int main()
{
  // ...
}

```
> 28 votes

# Answer
Some compilers (e.g. GCC) support multi-character constants. This can save a few characters when a large integer value is required. Example:

```
int n='  ';

```

The value is implementation-specific. Usually the value of `'ab'` is `256*'a'+'b'` or `'a'+256*'b'`. You can specify up to 4 characters between the quotation marks.
> 24 votes

# Answer
# Shorter header

This is GCC specific, it may be extensible to other compilers.

### Precompiled header.

In G++ `bits/stdc++.h` is the precompiled header consists of all other headers. If you need to `import` 2 different ones you can just use this.

### Shorter header.

This is all headers listed on http://en.cppreference.com/w/cpp/header:

```
$("#a").text(pako.inflate(atob('eJx9VkuW1DAM3HON2cOGx4o3V8lzK0q3wZ9gy90TTo+dDKCyM710yT9VqWS/2ECuzPzdhO3108vfUeCHGmUWNfJmVSMbsxo5m/VUEutZjaWsTo9NSkYfO/OvouNZDP1U4xqFOHkjNzVORmzU8YXDXcf5ym86lSIwvljBXOmWYtA7evYxbXCEi0aAAl930TM4JdiDSLYV0njQzSQNlA7Ikmy4KuDOJDFB6mGOHoVZHrPeNMsM7LhIBuWQ6C1pvW6Jjd5jKVKSXtII/qwlaIoA0EoAgHYPZy+A2GswDhCWH37tVpmkKShinZWtmzPzomkyyZoAika/GkiBRsUaU7jK5MxJULNexUGkdpaDAgvFcwKKq2Eqx1q4OCDLgOQBsdGbYIGxQV+KM9NdnmvRsgK99vIFZC95QPbSAmSvYEAeA0Jy7QxMNsdvX789RdoFbVh0Jce1+r6roHoYRXC/Fa4NAlxzN67vQXbk/xAfrn7UDEI73UjLXsUI7aXek1cru4dqIQ8Uh4H1Kl4HtRrseB8kpbEyDylg1sH84N1LjG6QY4bNqN604dpU/Ea8y4QJHLAm211jsnLzsJapDGvTaIsduBTdAt5TxTTOsCaDq+rg/Vq2WPwl0FBteQs02tY6zlsWBp++MzNUQDsaG2edNkky2JsOgae7xRe6brA3b9x2P3yqBoaiX2J6mDRP3WOdq2N4nvo3sYSYZm4RfBr/4/ghOF7IKXGOJRFD6lZszfM3p+FsimvdybhmIrQov621ZXoOYtwX/KVACG8BIbw4hPoPSwyzbepO+8txgfYJC/uvCgT7fwgGu08IBPsfEgSH3whEh7cZ6ek/LshQ/3RBdPhsQHR80yA8PtMQPmndqPhpO9Bpn7msI+bEsSfp96ZCYU7diOec+wpPOrckMvaBsz6Y9KS6//Xcp3f62LHdZu9NeFqjs7S9/gHXxXg4'), {to: 'string'}));
```

```
<script src="https://cdn.rawgit.com/nodeca/pako/master/dist/pako.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="a">

</pre>
```

sorted in increasing order of length.

Some of them are already longer than `bits/stdc++.h`, and some of them requires C++17 support. Some others are not supported by TIO G++ (for reasons I don't know of). Filter out them we have:

```
$("#a").text(pako.inflate(atob('eJx9VcuS3CAMvOc39p5Tak+p/MoUI2SbhIcDYrz++4BdW6WG1B7VYI36IebNRfLV8s/Ix69vb59VYVFVMLuqXCqq8q7oqyQusKql7l7XJmdzqtry36rPixj6o+p2CucUjGyqzkZc0ucLx5c+55U/NJUqUD+dIFfacoq6Y+CQ8gk/4ZMRkCC0LvoG5ww9iOTcgcZBm8kaqANQJLu4KuDFJCkD9WhTQGOWw+qmRSyo4xMZtENScKT92jIb3WOpUrP+pAv8XVvQHQGgRwCAPod3T0DcGo0HhOV32IevTNYSVHHeyTncsbxoZHajqxDBY1MKZ0E/RocmAyiFlmUdnlgDZ5CvLUPTT5uSJmSZkDIhLgUTHagxeUfJMr3ka507K/DiiiYgV5wBuWIDyJVOQI4JIVmH5SRX0vuP9y+RPqCLi06pE25rDVl/GT++HG5W9rYVhrrTgNAlJBK+sofQFdBRlpbHEWrxm8SLk57NlgHq6RoUncyiOXO3yHDr1nTauGdKfhLaQjNqk3Zcrwt/EO/tUY1I4Ia12H5N2ckWkNUc7gt4VljSmxaO/D+sS+6bEzhLZ4YRrpH6yPCifHKbPOwN8cFq1x6SDb4b5SzC4dEWBqK4pHyYbB/DH19p68D2cf+//APa+54V'), {to: 'string'}));
```

```
<script src="https://cdn.rawgit.com/nodeca/pako/master/dist/pako.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="a">

</pre>
```

It may happens that some of them can be replaced by shorter ones. Just binary search whether the one you need can be replaced. In particular:

```
cstdio -> ios        (-3 bytes)
algorithm -> regex   (-4 bytes)
vector -> queue      (-1 byte)
string -> map        (-3 bytes)
bitset -> regex      (-1 byte)
numeric -> random    (-1 byte)

```
> 20 votes

# Answer
One that I found handy:

Taking advantage of the fact that non-zero values evaluate to `true` in boolean expressions, and that `x&&y` evaluates to `x*y` when dealing with booleans

```
(x!=0 && y!=0)

```

evaluates to

```
(x*y)

```

You just have to be aware of overflows, as pointed out below.
> 17 votes

# Answer
Instead of using `while(1)`, use `for(;;)`, saving one character :)
> 15 votes

# Answer
When possible, change `&&` and `||` to `&` and `|` respectively.

When using simple if statements:

```
if(<condition>)<stuff>;

```

can be changed to:

```
<condition>?<stuff>:<any single character variable or literal>;

```

which saves a character.
> 13 votes

# Answer
Using the comma operator in lieu of open and close braces can save a few characters, if you have a situation where your clauses have more than one statement in them:

```
if(c){x=1;cout<<"Hi";y=2;}else{x=2;cout<<"Bye";y=3;}

```

vs.

```
if(c)x=1,cout<<"Hi",y=2;else x=2,cout<<"Bye",y=3;###

```

Two characters saved on a plain IF, or three total for an IF/ELSE.

As a point of distinction between C and C++, the result of a comma expression in C++ as a whole may be used as an lvalue...FWIW.
> 12 votes

# Answer
Use the following types:

```
u64, s64, u32, s32 (or int)

```

For repetitive words/types, use `#defines`:

```
#define a while

```

It's only worth it if you use `while` a lot to make up for the extra 10 characters. (About 4.)
> 10 votes

# Answer
If you're willing to use C++0x, you can use new features like lambdas.
> 10 votes

# Answer
Since array elements are stored directly after one another in memory, instead of something like this:

```
for(int x = 0; x < 25; x++) {
    for(int y = 0; y < 25; y++)
        array[x][y] = whatever;
}

```

You can do something like this:

```
int* pointer = array;
for(int i = 0; i < 25*25; i++, pointer++)
    *pointer = whatever;

```

Obviously neither of the above are golfed, for readability, but explicitly using pointers can save you a lot of space.
> 9 votes

# Answer
Quite an obvious one, but it you are using a lot of the standard library, `using namespace std;` might save a few characters.
> 9 votes

# Answer
# Use GCC builtins instead of importing

If you are using a GCC compiler, it sometimes helps to use their builtin functions, such as `__builtin_puts` or `__builtin_clz`. For example,

44 bytes:

```
int main(){__builtin_puts("Hello, world!");}`

```

50 bytes:

```
#import<cstdio>
int main(){puts("Hello, world!");}

```
> 9 votes

# Answer
Instead of writing big powers of 10, use **e notation**. For example, `a=1000000000` is longer than `a=1e9`. This can be extended to other numbers like `a=1e9+24` is better than `a=1000000024`.
> 8 votes

# Answer
You may use the ternary operator `?:` without any expressions in the true-block (it saves a byte)

```
#include <iostream>

int foo()
{
    std::cout << "Foo\n";
}

int main()
{
    1?foo():0;  // if (true) foo()
    0?:foo();   // if (!false) foo()
}

```

Check it here
> 8 votes

# Answer
Functions in `<algorithm>` often requires passing `a.begin(),a.end()` which is really long, instead you can use `&a[0],&*end(a)` to save a byte or two if `a` is `vector` or `string`.

std::sort(a.begin(),a.end());
std::sort(&a[0],&*a.end());

// with using namespace std;
sort(begin(a),end(a));
sort(&a[0],&*end(a));
```
</code></pre>
> 8 votes

# Answer
`#import` instead of `#include` gives you one more byte.

Also, the space character between `#import` and header is not necessarily:

```
#include <map>
// vs
#import<map>

```

And if you need something from `stdlib` header, you may import any header with STL container (preferable `set` or `map`) instead of `cstdlib`.
> 7 votes

# Answer
If you want to swap two integer variables a and b then ,

```
a^=b^=a^=b;

```

can be used , saving 5 characters than the standard way

```
a+=b;
b=a-b;
a-=b;

```
> 7 votes

# Answer
Arithmetic operations on Booleans:

Although

```
a*=b>0?.5:-.5

```

is better than

```
if(b>0)a*=.5;else a*=-.5;

```

it is not as good as

```
a*=(b>0)-.5

```

Also, using #define on anything that is used a lot. It is often shorter than using functions, since type names are not necessary.

Combine things as much as possible:

```
a+=a--;

```

is the same as

```
a=2*a-1;

```
> 6 votes

# Answer
It is useful to remember is that `a[i]` is the same as `*(a+i)`.

Replace `a[0]` with `*a` for two character savings. Also, `a[i][0]` is equivalent to `*a[i]` and `a[0][i]` shrinks down to `i[*a]`. So if you are hard-coding a `0` index in your array, a better way probably exists.
> 6 votes

# Answer
# Use generic lambdas as cheap templates

For types other than `int`, using them as function arguments can be expensive. However, generic lambdas were introduced (in C++14?) and allow any lambda to be a template - using `auto` for the argument types can save bytes. Compare:

```
double f(double x, double y)
[](auto x, auto y)

```

Generic lambdas are also very convenient for accepting iterators - probably the best way to accept array inputs in C++ is `[](auto a, auto z)`, where `a` and `z` are passed as `begin()` and `end()` of the array/vector/list/etc.
> 5 votes

# Answer
If you're doing C++11 or newer (which should always be the case now), use `auto` for complex types, if possible.

Example: 54 Bytes instead of 66

```
#include<vector>
std::vector<int> f(std::vector<int> l){return l;}

```

```
#include<vector>
auto f(std::vector<int> l){return l;}

```

Also, as performance does not matter, for some challenges a `std::list` may just do the job for a few bytes less:

```
#include<list>
auto f(std::list<int> l){return l;}

```
> 5 votes

# Answer
It's rather straightforward to cacluate when replacing something with a `#define` results in shorter code.

```
#define a blabla

```

Where `a` is a single letter name and `blabla` is the replacement of length \\$x\\$ has in total \\$10+x\\$ characters.

If you have \\$n\\$ times `blabla` in the code then the `#define` pays off when

$$10 + x + n \< nx$$

With the define you have \\$10 + x\\$ to define it and \\$n\\$-times a single character. Without it you have \\$n\\$-times `blabla` of length \\$x\\$. The following table lists how often `blabla` has to appear given its length for the define to make the code shorter:

| \\$x\\$ | \\$n\\$ |
| --- | --- |
| 2 | 13 |
| 3 | 7 |
| 4 | 5 |
| 5 | 4 |

Because the inequality is symmetric, the same table applies when \\$n\\$ and \\$x\\$ are swapped, ie if `blabla` appears \\$n = 2\\$ times in the code then the `define` results in shorter code when `blabla` is of length \\$x \ge 13\\$. The formula is

$$n \> \frac {10 + x} {x - 1}$$

or

$$x \> \frac {10 + n} {n - 1}$$

PS: Sometines the single letter named preprocessor symbol has to be followed by a space. This shifts the matters a little towards not using the define, but just a little.
> 5 votes

# Answer
G++ allows for variable-sized arrays, so there is no need to go through the lengthy pointer-malloc-new stuff.

```
int* array = new int[array_size];

```

becomes

```
int array[array_size];

```

Saves 9 bytes minimum with int.
> 4 votes

# Answer
Use `auto` instead of complex type names.

This can be done with generic lambdas and C++20 abbreviated function templates

```
int x(std::set<std::string>y){}
template<class T>int x(T&y){}
int x(auto&y){}
[](auto&x){}

```

This also allows you to avoid most includes.

Note that g++ on TIO requires `-fconcepts`.
> 4 votes

# Answer
When writing a full program you can use argc to initialize an integer variable to 1:

```
main(a){

```

is the same as:

```
main(){int a=1;

```
> 3 votes

# Answer
In my first attempt at code golf for task "Subtract the next numbers" I have started from function (58 bytes)

```
int f(int N, int P){int F;for(F=N;P;F-=++N,P--);return F;}

```

then safe 5 bytes with shifting to lambda and moving initialization out of `for` (53)

```
[](int N,int P){int F=N;for(;P;F-=++N,P--);return F;}

```

and finally after switching from `for` to `while` I got 51 bytes:

```
[](int N,int P){int F=N;while(P--)F-=++N;return F;}

```

The ungolfed test code is something like:

```
#include <iostream>
int main(void)
{
    int N, P;
    std::cin >> N >> P;
    auto f = [](int N,int P)
    {
        int F = N;
        while (P--)
            F -= ++N;
        return F;
    };
    std::cout << f(N, P) << std::endl;
    return 0;
}

```

**UPDATE:**

Actually `for` can reach the same length as `while`:

```
[](int N,int P){int F=N;for(;P--;F-=++N);return F;}

```
> 2 votes

# Answer
Kind of late to the party I guess...

If you want to turn an expression into -1 and 1 instead of 0 and 1, instead of this:

```
int x;
if (a * 10 > 5)
    x = 1;
else
    x = -1;

```

do this:

```
int x = (a * 10 > 5) * 2 - 1;

```

It can save some bytes depending on usage.
> 2 votes

# Answer
If you need a type alias, `using` is two bytes shorter than `#define`:

```
#define T ... // newline
using T=...;

```
> 1 votes

# Answer
Don't use `string("")`, use `""`. It saves 8 bytes.
> 0 votes

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


# Question
Title: Check whether letters of word are in alphabetical order
Write a function/program that accepts a string of lower/uppercase letters \[A-Za-z\] as input, that checks whether the occuring letters are unique and in alphabetical order (ignoring lower and uppercase) or not. The output must be truthy if they are unique and in alphabetical order and falsy if not.

Here some testcases

```
a                           true
abcdefGHIjklmnopqrSTUVWXyz  true
aa                          false
puz                         true
puzz                        false
puzZ                        false
puZ                         true
PuZ                         true
pzu                         false
pzU                         false
abcdABCD                    false
dcba                        false

```

If you want, run your program on all words of a wordlist like this one and and post some interesting ones =).

### Score

Lowest number of bytes wins.

# Answer
# CJam, 8 bytes

```
lel_$_&=

```

Here is a test harness for all examples in the challenge. This returns `0` or `1` (which are falsy and truthy, respectively, in CJam).

And here is a script to filter the word list in the question (takes a few seconds to run). You'll have to copy the word list into the input field manually, because it's too long for a permalink.

## Explanation

```
l        "Read input.";
 el      "Convert to lower case.";
   _$    "Get a copy and sort it.";
     _&  "Remove duplicates (by computing the set intersection with itself).";
       = "Check for equality with original (lower case) word.";

```
> 28 votes

# Answer
# Regex (any flavor), 55 bytes

Some people don't consider regex to be a programming language, but it's been used before, and it's not close to being the shortest.

```
^a?b?c?d?e?f?g?h?i?j?k?l?m?n?o?p?q?r?s?t?u?v?w?x?y?z?$

```

I've added one byte for the `i` (case-insensitive) flag. This is very straightforward and might be shorter to generate on the fly.

If regex alone are not allowed, you can use this 56-byte Retina program suggested by Martin Büttner:

```
i`^a?b?c?d?e?f?g?h?i?j?k?l?m?n?o?p?q?r?s?t?u?v?w?x?y?z?$

```

Running this on the wordlist linked above yielded 10 6-letter words in alphabetical order.

> \["abhors", "almost", "begins", "begirt", "bijoux", "biopsy", "chimps", "chinos", "chintz", "ghosty"\]
> 21 votes

# Answer
# Python 3, 44 bytes

```
*s,=input().lower()
print(sorted(set(s))==s)

```

A simple approach - check uniqueness, check sortedness.
> 20 votes

# Answer
# \>\<\>, ~~52~~ ~~42~~ 39 bytes

```
0>i:1+?v1n;
? )'`':/'@'v
0v?){:-<'`'/;n

```

This type of question is one of the few types that \>\<\> is pretty comfortable with, since we only need to deal with one char at a time.

## Explanation

Don't get lost! There's a lot of wrapping here.

```
0            Push 0. We'll be mapping a-z to 1-26, so 0 will be smaller than everything

(loop)
i            Read a char of input
:1+? 1n;     If there's no more input, print 1
:'`')?       If the char is bigger than backtick...
  '`'          Push backtick  (which is one before 'a'), else...
  '@'          Push an @ sign (which is one before 'A')
-            Subtract, mapping a-z to 1-26
:{)?         If the new char is bigger than the previous char...
               Repeat from the beginning of the loop, else...
  0n;          Print 0

```

## Previous solution, 42 bytes

```
0i:1+?v1n;n0/\!
?)'`':/'@'v
? ){:-<'`'/ vv

```

The interesting thing is that, despite appearing to have the same functionality, the alternative

```
0i:1+?v1n;n0\/!
?)'`':/'@'v
? ){:-<'`'/ ^^

```

*(The change is in the arrows and mirrors on the far right)*

actually gives *incorrect* results, due to \>\<\>'s interpreter using a Python defaultdict. What happens is that, by traversing through the empty space at the end of the second row, 0s are implicitly placed into the blank spaces when \>\<\> tries to access the cell. This then messes with the `?` conditional trampoline at the beginning of the same row, as the newly placed 0s are skipped rather than the `v` at the end.
> 12 votes

# Answer
# Haskell, 52 Bytes

```
import Data.Char
and.(zipWith(>)=<<tail).map toLower

```

Usage: `(and.(zipWith(>)=<<tail).map toLower) "abcd"` which outputs `True`.
> 9 votes

# Answer
# C, 67 65 57 54 (52) characters

```
f(char*s){int c,d=0;for(;(c=*s++)&&(c&~32)>(d&~32);d=c);return!c;}

```

a little shorter:

```
f(char*s){int c,d=0;for(;(c=*s++)&&(c&~32)>d;d=c&~32);return!c;}

```

and even shorter:

```
f(char*s){int d=32;for(;(*s|32)>d;d=*s++|32);return!*s;}

```

Here's a little test: http://ideone.com/ZHd0xl

After the latest suggestions here are still two shorter versions:

```
// 54 bytes
f(char*s){int d=1;for(;(*s&=95)>d;d=*s++);return!*s;}

// 52, though not sure if valid because of global variable
d;f(char*s){d=1;for(;(*s&=95)>d;d=*s++);return!*s;}

```

Also this code relies on the fact, that in ASCII lowercase and uppercase only differ by the 5th bit (32) which I filter out. So this might not work with other encodings obviously.

EDIT: The latest version always sets the 5th bit as `|32` is shorter than `&~32`.
> 9 votes

# Answer
# Ruby, 33

```
->s{c=s.upcase.chars
c==c.sort|c}

```

Checks to see if the sorted unique characters are the same as all the characters.
> 6 votes

# Answer
## Javascript (ES5), 101

```
function i(s){b=0;l=''.a
s.toUpperCase().split('').forEach(function(c){if(c<=l)b=1
l=c})
return!b}

```

## Improved to 87 by edc95:

upvote his comment :)

```
function i(s){return!s.toUpperCase().split(l='').some(function(c){return(u=l,l=c)<=u})}

```

*Btw, the test cases currently in OP are fulfilled if a program is only checking uniqueness, disregarding order.*

---

I cant write comments yet, so I'll answer some remarks here:

**@edc65:** Thanks! I tried rewriting it using `some()`, but I couldn't get a shorter solution, because even though it looks like it would enable me to get rid of the superflous b variable, you need to type "return" twice (same with `reduce()`), and you can't just return the comparison's result directly, because the last character needs to be saved after the comparison with it.

**@edc65:** That's a nice use of the comma operator for 87! I edited it into my answer for more visibility.
> 5 votes

# Answer
## Wolfram Mathematica, 49 37 bytes

```
f[x_]:=(l=Characters[ToLowerCase[x]];Union[l]==l)

```

P.S. Shorter solution by Martin Büttner:

```
Union[l=Characters@ToLowerCase@#]==l&

```
> 5 votes

# Answer
# Haskell, 90 bytes

Supplies the function `f :: String -> Bool`

```
import Data.List
import Distribution.Simple.Utils
f l=g$lowercase l
g l=sort l==l&&l==nub l

```

Usage (assuming it is saved as golf.hs). `...` is used to replace `ghci`'s verbose loading messages.

```
$ ghci golf.hs
...
*Main> f "as"
...
True
*Main> f "aa"
False

```

If someone has a `lowercase` method shorter than `import Distribution.Simple.Utils` then please comment.
> 4 votes

# Answer
# Pure Bash 4.x, 37

```
[[ ${1,,} =~ ^`printf %s? {a..z}`$ ]]

```

Try it online!

Input taken as a command-line parameter. As per standard shell semantics, exit code 0 means true (alphabetic) and exit code != 0 means false (not alphabetic).

The printf creates the regex as in @hsl's solution. The input string is expanded to lowercase and compared against the regex.

---

Previous answer:

### Bash + coreutils, 52

Straightforward solution:

```
a=`fold -1<<<${1,,}`
cmp -s <(sort -u<<<"$a")<<<"$a"

```
> 4 votes

# Answer
# J, 17 bytes

Checks if the lowercase sorted `/:~` string equals `-:` the lowercase nub `~.` string.

```
   (/:~-:~.)@tolower

   NB. testing with the example inputs
   ((/:~-:~.)@tolower) every (1$'a');'abcdefGHIjklmnopqrSTUVWXyz';'aa';'puz';'puzz';'puzZ';'puZ';'PuZ'
1 1 0 1 0 0 1 1

```

As in J a 1-charater long "string" represented as a regular string (with quotes) is just a character atom not a real string I formatted the input appropriately so all input would be real strings. (In the example above I used `1$'a'`.)
> 4 votes

# Answer
# MATLAB, ~~29~~ 27 bytes

Now for a one-liner which even makes sense outside of code-golf.

As an anonymous function (use as `o('yourstring')`)

```
o=@(s)all(diff(lower(s))>0)

```

I guess this function is pretty self-explanatory since it reads like a newspaper ad.

Previous version (29 bytes):

~~```
all(diff(lower(input('')))>0)

```~~

~~Input must be presented between `'` marks, e.g. `'Potato'`.~~
> 4 votes

# Answer
## Golang (65 bytes)

Go is not a golf friendly language, also, i suck at golf...

```
func a(s[]byte)(bool){return len(s)<2||s[0]|32<s[1]|32&&a(s[1:])}

```

Run it here: http://play.golang.org/p/xXJX8GjDvr

*edit 106-\>102*

*edit 102-\>96*

*edit 96-\>91*

*edit 91-\>87*

*edit 87-\>65*

I beat the java version, I can stop for today
> 4 votes

# Answer
# C (44 bytes)

`f(char*s){return(*s&=95)?f(s+1)>*s?*s:0:96;}`

Test it here: http://ideone.com/q1LL3E

Posting this because I can't comment yet, otherwise it would be a suggestion to improve the existing C answer because I completely stole the case-insensitive idea from the existing C answer.

Returns 0 if the string is not ordered, and a non-zero value if ordered.
> 4 votes

# Answer
## VBA (161 bytes)

```
Function t(s As String)
t = 0
For i = 2 To Len(s)
a = Left(LCase(s), i)
    If Asc(Right(a, 1)) <= Asc(Right(a, 2)) Then Exit Function
Next
t = 1
End Function

```

Compares ascii value with previous letter in lowercase, return 0 (false) when its value is smaller / equal and exit function
> 4 votes

# Answer
# Brachylog, 3 bytes

```
ḷ⊆Ạ

```

Try it online!

The predicate succeeds if the input meets the requirements outlined and fails if it does not, printing `true.` or `false.` if run as a program.

```
       The input,
ḷ      lowercased,
 ⊆     is a not-necessarily-contiguous sub-list of
  Ạ    "abcdefghijklmnopqrstuvwxyz".

```

The first version I came up with, not explicitly referencing the alphabet:

# Brachylog, 4 bytes

```
ḷ≠.o

```

Try it online!

```
        The input,
ḷ       lowercased,
 ≠      in which every character is distinct,
  .     is the output variable,
   o    which sorted,
        is still the output variable.

```
> 4 votes

# Answer
# JavaScript (ES6) 54

Convert to uppercase, then to array and sort. If during sort two element are in the wrong order or equal, return 0 (falsy) else 1 (truthy)

**Edit** Shortened thx to @Optimizer (but still 2 more than the @Tamas solution implemented in ES6: `F=s=>[...s.toUpperCase()].every(c=>(u=l,l=c)>u,l='')`)

```
F=s=>[...s.toUpperCase(x=1)].sort((a,b)=>a<b?1:x=0)&&x

```

**Test** in Firefox / FireBug console

```
;['a','abcdefGHIjklmnopqrSTUVWXyz','aa','puz','puzz','puzZ','puZ','PuZ']
.map(w=>w+' '+F(w))

```

> \["a 1", "abcdefGHIjklmnopqrSTUVWXyz 1", "aa 0", "puz 1", "puzz 0", "puzZ 0", "puZ 1", "PuZ 1"\]
> 3 votes

# Answer
# C# 6, 18 + ~~82~~ 76 = 94 bytes

Requires (18 bytes):

```
using System.Linq;

```

Code (76 bytes):

```
bool a(string s)=>(s=s.ToLower()).Distinct().OrderBy(x=>x).SequenceEqual(s);

```

C# 6 supports lambdas to define a function, which is useful for golfing.

Non-C# 6 version:

```
bool a(string s){return (s=s.ToLower()).Distinct().OrderBy(x=>x).SequenceEqual(s);}

```

Ungolfed code:

```
bool IsInAlphabeticalOrder(string s)
{
    s = s.ToLower();
    return s.Distinct()
            .OrderBy(x => x)
            .SequenceEqual(s);
}

```
> 3 votes

# Answer
## J, 21 characters

This is too long. The argument must have rank `1`, i.e. it must be a string or vector.

```
*/@(<=~.;/:~)@tolower

```
* `tolower y``y` in lower case.
* `/:~ y``y` in lexical order.
* `~. y` – the nub of `y`, that is, `y` with duplicates removed.
* `x ; y``x` and `y` put into boxes and then concatenated.
* `< y``y` put into a box.
* `x = y``x` compared element-wise with `y`.
* `(< y) = (~. y) ; (/:~ y)` – a vector indicating if `y` is equal to its nub and itself sorted.
* `*/ y` – the product of the items of `y`, or its logical and if the items are booleans.
* `*/ (< y) = (~. y) ; (/:~ y)` – a boolean indicating the desired property for lowercase `y`.
> 3 votes

# Answer
# Julia, 44 bytes

```
s->(l=lowercase(s);l==join(sort(unique(l))))

```

This creates an anonymous function that takes a single argument `s`, converts it to lower case, and compares it to the unique sorted version of the string. It returns a boolean, i.e. `true` or `false`. If you want to test it out, assign it like `f=s->...` and then call `f("PuZ")`, etc.
> 3 votes

# Answer
## k (6 bytes)

```
&/>':_

```

`&` returns true if both args are true

`/` modifies `&` to apply "over" a list, like a fold in functional languages

`>` greater than

`':` modifies `>` to apply "each-prior", so returns a vector of booleans stating which elements are greater than their predecessor

`_` makes it argument lower case

```
  _"puzZ"
"puzz"
  >':_"puzZ"
1110b
  &/>':_"puzZ"
0b

```

(`0b` means boolean false)

## q (13 bytes)

```
all(>':)lower

```

q is just syntactic sugar on k. `all` is defined as `&/`, and lower is `_`
> 3 votes

# Answer
# Perl 6, 35 bytes

```
{my@c=.uc.comb;@c eq@c.sort.unique}

```

This produces a callable block; if I could just assume that `$_` is already set to the desired word, I could delete the surrounding curly braces and lose two more bytes, but probably the only reasonable way to make that assumption would be to run it with `-n` and feed the word as standard input, which would add the two bytes right back.
> 3 votes

# Answer
## Java 8 - 90 89 87 85 chars

The idea here is to use a 'reduce' function that tracks the last char and "gives up" when it detects the sequence is not strictly ascending.

**golfed:**

```
int f(String s){return s.toLowerCase().chars().reduce(0,(v,c)->(v<0)?v:(c>v)?c:-1);}

```

**ungolfed:**

```
int f(String s){
    return s.toLowerCase()
            .chars()
            .reduce(0, (v,c) -> (v<0)? v : (c>v)?c:-1);
}

```

**example:**

```
System.out.println(new Quick().f("abc"));
System.out.println(new Quick().f("aa"));
System.out.println(new Quick().f("abcdefGHIjklmnopqrSTUVWXyz"));
System.out.println(new Quick().f("puZ"));
System.out.println(new Quick().f("Puz"));
System.out.println(new Quick().f("cba"));

```

**output:**

```
99
-1
122
122
122
-1

```
> 3 votes

# Answer
# , 37 bytes

```
all(diff(utf8ToInt(scan(,''))%%32)>0)

```

Try it online!

Posting since this is substantially different and shorter than Michal's R answer.

Converts the letters to ASCII codepoints with `utf8ToInt`, then takes modulo 32 so that lower and upper letters are converted to the same numbers 1...26. Computes the pairwise differences, and checks that they are all positive.
> 3 votes

# Answer
# Perl, 27

@hsl's regexp dynamically build.

```
#!perl -p
$"="?";@x=a..z;$_=/^@x?$/i

```

Also we can do a reverse match: convert the input into a regexp: `PuZ` =\> `.*p.*u.*z.*` and then match this to a string of letters in alphabetical order. Result - also 27 characters.

```
#!perl -lp
$_=join(s//.*/g,a..z)=~lc

```
> 2 votes

# Answer
# Python, 50 bytes

```
f=lambda x:sorted(set(x.lower()))==list(x.lower())

```

Try online here: http://repl.it/c5Y/2
> 2 votes

# Answer
# PHP (~~89~~ ~~76~~ ~~72~~ 63 bytes)

I'm pretty horrible at golfing, but I thought I'd give it a shot.

```
<?=(join(array_unique(str_split($a=strtolower($argv[1]))))==$a)+0;

```

I had to cast the output to an integer, since booleans aren't printed in php.

I was able to remove the echo by using `<?=`, I also removed the `$b`.

**\[edit\]**

Removed the space after `<?=` and followed manatwork's suggestion to cut 4 bytes.

Also, replacing the implode with join and omitting the glue parameter saved another 9 bytes. Thanks manatwork.
> 2 votes

# Answer
# Python 2, 43 bytes

```
lambda s:eval('"%s"'%'"<"'.join(s.lower()))

```

Try it online!

Puts `<` symbols between all the letters (converted to lowercase), and then `eval`s it. Python's chained comparison operators are perfectly happy to evaluate the whole thing as one big boolean expression.
> 2 votes

# Answer
# Vyxal, 6 bytes

```
⇩¨=‡Us

```

Try it Online!

## Explained

```
⇩¨=‡Us
⇩¨=    # is the lowercase version of the input invariant under:
  ‡Us  # uniquify and sort?

```
> 2 votes

# Answer
# Prolog (SWI), 36 bytes

```
\S:-maplist(to_lower,S,L),sort(L,L).

```

Try it online!

Ungolfed:

```
\S :-
  maplist(to_lower, S, L), % convert each character code in S to lowercase, putting that in a list called L
  sort(L, L). % Does L sorted and uniquified equal L?

```
> 2 votes

# Answer
# PHP (52 bytes)

This is an answer based on @HSL's regex (sorry dude).

The idea is to grab the regex and generate it instead of having it hard-coded.

Here is the code:

```
echo preg_match("@^".join('?',range(a,z))."?$@",$s);

```

Since this answer isn't entirely of my authority, I have marked it as "`Community Wiki`".

To use this, simply add a line before with `$s='String!';`.
> 1 votes

# Answer
# Erlang, 51

```
f(S)->G=string:to_lower(S),ordsets:from_list(G)==G.

```

Uses an ordered set (analogous to `java.util.TreeSet`) to sort the characters and discard any duplicates. The new list is then compared with the input string.

Test Function:

```
test() ->
    [io:format("~p ~p~n", [S, f(S)]) || S <- ["a","abcdefGHIjklmnopqrSTUVWXyz","aa","puz","puzz","puzZ","puZ","PuZ"]].

```
> 1 votes

# Answer
# Java, 96

```
boolean a(char[]a){int i=-1,l=0;for(;++i<a.length;l+=i>0&&a[i]<=a[i-1]?1:0)a[i]|=32;return l<1;}

```

Pretty straightforward here. Just convert all to lower and compare each to the previous character.
> 1 votes

# Answer
## PowerShell, 37

```
-join(($x="$input")[0..26]|sort)-eq$x

```

Can be shortened by another byte by using command-line arguments instead of stdin (`$args` instead of `$input`).

Tricks used:

* PowerShell is case-insensitive by default, simplifying the check.
* Getting a `char[]` from the input is a bit shorter if we know an upper bound for the length `[0..x]` instead of `[char[]]`
> 1 votes

# Answer
# Rebol - ~~26~~ 25

```
(s: input)= sort unique s

```

NB. Above works fine in Rebol 2. However in Rebol 3 `sort` isn't case insensitive (yet) so for now it would need to be written has `(s: input)= sort lowercase unique s`
> 1 votes

# Answer
# R, 62 Bytes

```
s=strsplit(tolower(word),"")[[1]]
all(s[order(unique(s))]==s)

```

This will throw a warning if there is a repeating character.

To avoid this, I inserted zeros to make both strings the same length. I assumed this is OK since we are only using letters and not numbers.

```
s <- strsplit(tolower(word), "")[[1]]
all(c(s[order(unique(s))],rep('0',length(s)-length(unique(s)) )) == s)

```
> 1 votes

# Answer
# Clojure, 69

```
(let[s(seq(.toLowerCase (read-line)))](= s(seq(apply sorted-set s))))

```

Run in the REPL, enter a string and press return. Prints `true` or `false`. E.g.

```
user=> (let[s(seq(.toLowerCase (read-line)))](= s(seq(apply sorted-set s))))
puZ
true
user=> (let[s(seq(.toLowerCase (read-line)))](= s(seq(apply sorted-set s))))
puzz
false

```
> 1 votes

# Answer
# Javascript, ~~147~~ 145 bytes

```
function(a){b=[];a=a.toLowerCase().split('');while(a.length)b.push(a.pop().charCodeAt(0));while(c=b.pop()){if(c>=b[b.length-1])return 0}return 1}

```

An anonymous function that converts to lowercase, creates an array of char codes, then checks them from right to left.
> 1 votes

# Answer
# Retina, 33 bytes

Byte count assumes ISO 8859-1 encoding.

```
T`L`l
^
$_¶
O`\G.
D`\G.
^(.*)¶\1$

```

**Try it online**

Translate uppercase to lowercase, duplicate input, sort the first line, deduplicate first line, then check if the lines are equal.
> 1 votes

# Answer
# C++14, ~~59~~ 58 bytes

-1 byte for `int` instead of `auto` in range-based for-loop.

As unnamed lambda returning via reference parameter. `64` (\>0) for true, `0` for false. Input `s` may be `std::string` or `char[]`.

```
[](auto&s,int&r){int b=r=64;for(int c:s)r*=b<(c&=95),b=c;}

```

The `&=95` is from this answer.

Ungolfed and usage:

```
#include<string>
#include<iostream>

auto f=
[](auto&s,int&r){
  int b=r=64;
  for(int c:s)
    r*=b<(c&=95),
    b=c;
}
;

int main(){
  std::string s;
  int r;
  s="ABC";
  f(s,r); std::cout << s << ", " << r << std::endl;
  s="AbC";
  f(s,r); std::cout << s << ", " << r << std::endl;
  s="ACB";
  f(s,r); std::cout << s << ", " << r << std::endl;
  s="AcB";
  f(s,r); std::cout << s << ", " << r << std::endl;
}

```
> 1 votes

# Answer
# Python 2, 62 bytes (thank to Shaggy)

```
def a(w):
    v=w.lower()
    print v==''.join(sorted(set(v)))

```

I know I can not beat anyone but here is my solution.

PoC: https://repl.it/repls/UnderstatedDecimalSales
> 1 votes

# Answer
# Japt, 6 bytes

```
v ä< e

```

Try it online!

Explanation:

```
v         #Convert to all lowercase
  ä  e    #For every pair of consecutive letters:
   <      # Check that the second letter is later in the alphabet than the first

```
> 1 votes

# Answer
# MathGolf, 6 bytes

```
mδ_s▀=

```

Try it online!

## Explanation

```
m        explicit map (per character)
 δ       capitalize string
         these two commands transforms the input string to uppercase
  _      duplicate the uppercase string
   s     sort(array)
    ▀    unique elements of string
     =   check if equal to the uppercased input

```
> 1 votes

# Answer
# APL (Dyalog Extended), 6 bytes<sup>SBCS</sup>

Anonymous tacit prefix function.

```
(∧≡∪)⌊

```

Try it online!

`(``)⌊` on the lowercase:

`∧≡∪` does the ascending sort match the unique?
> 1 votes

# Answer
# \>\<\>, ~~29~~ 20 bytes

Saved 9 bytes thanks to *Jo King*

```
0\0=n;
!\i1+48*%:r)?

```

Try it online!
> 1 votes

# Answer
# Bash+coreutils, 27 bytes

```
grep -Ei ^1`echo ?{a..z}?`$

```

Try it online!

There was an earlier answer with pure Bash, but this one is cool because it saves space by making a much "worse" regular expression. The command substitution expands to the regular expression

```
^1?a? ?b? ?c? ?d? ?e? ?f? ?g? ?h? ?i? ?j? ?k? ?l? ?m? ?n? ?o? ?p? ?q? ?r? ?s? ?t? ?u? ?v? ?w? ?x? ?y? ?z?$

```

which accepts many things that we don't care about (1's at the beginning and spaces almost anywhere) but that's okay because it selects correctly when limited to things in the input specification. This lets us avoid a `printf %s` and just accept the spaces that Bash gives when it expands `?{a..z}?`
> 1 votes

# Answer
# APL(NARS), 32 char, 64 bytes

```
{(k≡∪k)∧k≡k[⍋k←26∣¯1+(⎕A,⎕a)⍳⍵]}

```

how to use and test (note that "'a'" is a char type and ",'a'" is one type array chars):

```
  h←{(k≡∪k)∧k≡k[⍋k←26∣¯1+(⎕A,⎕a)⍳⍵]}
  h ,'a'
1
  h 'abcdefGHIjklmnopqrSTUVWXyz'
1
  h 'aa'
0
  h 'puz'
1
  h 'puzz'
0
  h 'puzZ'
0

```

Possible there is something more short.
> 1 votes

# Answer
# Ruby, 29 bytes

```
->s{s=~/^#{[*?a..?z]*??}?$/i}

```

Try it online!

Returns 0 if in order, or false if not in order.
> 1 votes

# Answer
# 05AB1E, 4 bytes

```
lDêQ

```

Try it online or verify all test cases.

**Explanation:**

```
      #  i.e. input: "Test"
l     # Convert the (implicit) input-string to lowercase
      #  STACK: ["test"]
 D    # Duplicate it
      #  STACK: ["test", "test"]
  ê   # Uniquify and sort the characters in the duplicated string
      #  STACK: ["test", "est"]
   Q  # Check if both strings are equal
      #  STACK: [0]
      # (after which the top of the stack is output implicitly as result)

```
> 1 votes

# Answer
# Husk, ~~7~~ 5 bytes

```
ΠẊ>ma

```

Try it online!

Inspired by caird's Jelly answer

```
   m    # map over all letters of input:
    a   #  make lowercase
 Ẋ      # then for each pair
  >     #  test if R > L
Π       # and get the product of all the results.

```
> 1 votes

# Answer
# Jelly, 5 bytes

```
Œu<ƝẠ

```

Try it online!

## How it works

```
Œu<ƝẠ - Main link. Takes a string S on the left
Œu    - Uppercase
   Ɲ  - Over overlapping pairs [a, b]:
  <   -   Is a < b?
    Ạ - True for all?

```
> 1 votes

# Answer
# x86 machine code, 15 bytes

Hexdump:

```
33 c0 ac 24 5f 3a e0 73 05 8a e0 e2 f5 f9 c3

```

A function which receives a pointer to the string in `esi` and its length in `ecx`. Returns in `CF`.

Disassembly:

```
10011860 33 C0                xor         eax,eax
10011862 AC                   lods        byte ptr [esi]
10011863 24 5F                and         al,5Fh
10011865 3A E0                cmp         ah,al
10011867 73 05                jae         bad (1001186Eh)
10011869 8A E0                mov         ah,al
1001186B E2 F5                loop        my+2h (10011862h)
1001186D F9                   stc
1001186E C3                   ret

```

I had arrange the comparison in such a way that for "bad" strings the carry flag gets set to 0.

Test program (works in Visual Studio):

```
#include <stdio.h>
#include <string.h>

__declspec(naked) char my()
{
    _asm
    {
        xor eax, eax;
    myloop:
        lodsb;
        and al, 0x5f;
        cmp ah, al;
        jae bad;

        mov ah, al;
        loop myloop;
        stc;
    bad:
        ret;
    }
}

__declspec(naked) bool __fastcall caller(const char*, size_t)
{
    _asm
    {
        push esi;
        mov esi, ecx;
        mov ecx, edx;
        call my;
        mov al, 0;
        adc al, 0;
        pop esi;
        ret;
    }
}

bool is_good(const char* s)
{
    printf("%s ", s);
    size_t l = strlen(s);
    return caller(s, l);
}

int main()
{
    printf("%d\n", is_good("abd"));
    printf("%d\n", is_good("a"));
    printf("%d\n", is_good("abcdefGHIjklmnopqrSTUVWXyz"));
    printf("%d\n", is_good("aa"));
    printf("%d\n", is_good("puz"));
    printf("%d\n", is_good("puzz"));
    printf("%d\n", is_good("puzZ"));
    printf("%d\n", is_good("puZ"));
    printf("%d\n", is_good("PuZ"));
    printf("%d\n", is_good("pzu"));
    printf("%d\n", is_good("pzU"));
    printf("%d\n", is_good("abcdABCD"));
    printf("%d\n", is_good("dcba"));
}

```

It contains a function `caller` which translates calling conventions.
> 1 votes

# Answer
# Pyth, 8 bytes

```
qKrQ1S{K

```

Try it online!

```
qKrQ1S{K
qKrQ1S{KQ  // Implicit input
 KrQ1      // Assign uppercase input to K
q    S{K   // Deduplicate K and sort it
q          // Is original K == deduplicated and sorted

```
> 1 votes

# Answer
# Excel ms365, 45 bytes

```
=CONCAT(SORT(UNIQUE(MID(A1,ROW(1:26),1))))=A1

```
> 1 votes

# Answer
# Vyxal, 3 bytes

```
⇩Þ⇧

```

Try it Online!
> 1 votes

# Answer
# Julia 1.0, 34 bytes

```
!x=all(diff(([x...].-'A').%32).>0)

```

Try it online!
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 44 bytes

```
n=>n.Aggregate((a,b)=>a>1&a%32<b%32?b:'')>1

```

Can be 42 bytes if I return a SOH char for non-alphabetic and anything else for alphabetic.

Try it online!
> 0 votes

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

```
w=>new Set(w).size==w.length&&[...w.toLowerCase()].sort().join``==[...w.toLowerCase()].join``

```

Try it online!
> 0 votes

# Answer
# Perl 6, ~~30~~ 14 bytes

```
{[<] .uc.ords}

```

Try it online!

Gets the ordinal values of the uppercased string and checks if they are in strictly increasing order.
> 0 votes

# Answer
# PHP, 42 bytes

```
for(;$c=_&$argn[$i++];$p=$c)$c<$p&&die(1);

```

exits with `1` (error) for falsy, exit code `0` for truthy.
Run as pipe with `-nR` or try it online.

If you absolutely need visible output, take these 51 bytes:

```
for(;$c=_&$argn[$i++];$p=$c)$c<$p&&die("0");echo 1;

```
> 0 votes

# Answer
# Jelly, 6 bytes

```
ŒuQ⁼ṢƊ

```

Try it online!

## Explanation

```
ŒuQ⁼ṢƊ Main link: takes string on the left
Œu     uppercase the input
     Ɗ fork: f(x) g h(x)
  Q    unique
   ⁼   equals
    Ṣ  sorted?

```
> 0 votes

# Answer
# Clojure, 37 bytes

```
#(apply < 0(map int(.toLowerCase %)))

```

If it is okay to throw an error on empty strings, we can save 2 bytes by getting rid of the 0.

```
#(apply <(map int(.toLowerCase %)))

```
> 0 votes

# Answer
# Thunno 2, 4 bytes

```
LDḳ=

```

Attempt This Online!

#### Explanation

```
LDḳ=  # Implicit input
L     # Lowercase the input
 D    # Duplicate this string
  ḳ   # Sort and uniquify
   =  # Are they equal?
      # Implicit output

```
> 0 votes

---
Tags: code-golf, string, decision-problem
---


# Question
Title: As many near-repdigit primes as possible
A near-repdigit number is a positive integer where all the digits are the same, except one. For example 101 and 227 are near-repdigits. A near-repdigit prime is a near-repdigit that is also prime. For example:

101, 113, 131, 151, 181, 191, 199, 211, 223, 227, 229, 233, 277, 311, 313, 331, 337, 353, 373, 383, 433, 443, 449, 499, 557, 577, 599, 661, 677, 727, 733, 757, 773, 787, 797, 811, 877, 881, 883, 887, 911, 919, 929, 977, 991, 997, 1117, 1151, 1171, 1181, 1511

These are all near-repdigit primes.

The smallest near-repdigit prime has two digits, but it is an open mathematical question whether there exists a near-repdigit prime for every possible number of digits larger than 2. It is conjectured, by me, that the answer is in fact yes.

# Task

For each integer `n` where `n >= 2`, compute a near-repdigit prime with `n` digits.

Your code can either output a near-repdigit prime with 2, 3, ... digits or, as they are easily compressible, output a compressed representation of each number. For example, any near-repdigit can be represented by four smaller numbers. The first is the number of digits, the second the majority digit, the third the minority digit and the fourth the location of the minority digit. You can choose whichever representation you prefer.

## Primality testing

There are many different ways to test if a number is prime. You can choose any method subject to the following conditions.

* You can use any primality test that is guaranteed never to make a mistake.
* You can use any well-known primality test which hasn't been proved to be correct but for which there is no known example number for which it gives the wrong answer.
* You can use a probabilistic primality test if the probability of giving the wrong answer is less than 1/1000.

I will test your code for 5 minutes on my ubuntu 22.04 machine, but please quote how high you get on your machine in your answer.

This challenge is judged per language.

In the *very* unlikely event that you find a number of digits n for which there is no near-repdigit prime, I will award a 500-rep bounty and you will get mathematical immortality.

# Results so far

* **n=1291** by Kirill L. in **Julia**
* **n=1291** by c-- in **C** with gmp
* **n=1232** by jdt in **C++** with gmp
* **n=972** by Kirill L. in **Julia**
* **n=851** by alephalpha in **Pari/GP**
* **n=770** by ZaMoC in **Wolfram Language** (not tested on my PC)
* **n=722** by gsitcia in **Pypy/Python**
* **n=721** by jdt in **C++**
* **n=665** by c-- in **C++**
* **n=575** by Seggan in **Kotlin**
* **n=403** by Arnauld in **nodejs**
* **n=9** by py3\_and\_c\_programmer in **Python**

# Answer
> 5 votes
# Julia n = 972 (single-threaded)

```
using Primes, ThreadPools

function nrdprime(n)
  a = fill(0, n)
  for j = 1:9
    a[1:n] .= j
    for k = n:-1:1, l = 0:9
      if j == l continue end
      if l == 0 && k == 1 continue end
      a[k] = l
      if iseven(a[n]) continue end
      x = parse(BigInt, join(a))
      if isprime(x)
        print("$n $j $l $k\n")
        return x
      end
      a[k] = j
    end
  end
  println(n, " has no answer")
end

@qthreads for i = 2:2000 nrdprime(i) end

```

Uses Primes.jl package (`import Pkg; Pkg.add("Primes")`). According to the source code, it relies on Miller-Rabin algorithm implementation from libgmp library.

UPDATE: Added multithreading with ThreadPools.jl (`import Pkg; Pkg.add("ThreadPools")`). Compared to Base.Threads module, using a pool allows scheduling calculations in a more convienient way for our use case. In order to take advantage of concurrency, run the program with `julia --threads N`, setting the number N in accordance with your CPU specification.

The output was changed to compressed form (`n major minor position`) and I also tweaked the code a bit to reduce the number of array allocations, but it looks like this isn't really a bottleneck.

Try it online! for `n` up to about 550 in 1 min, using an ancient version of Julia that still has primes-related functionality integrated in base, and thus available on TIO.

# Answer
> 2 votes
# C++ (gcc) with boost, n = 595

~354 digits in 60 seconds on TIO.

~595 digits in 5 minutes on my Windows machine, compiled with MSVC.

```
#include <atomic>
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include <unordered_map>
#include <boost/multiprecision/miller_rabin.hpp>

namespace mp = boost::multiprecision;

std::atomic<int> digits{ 2 };
std::mutex mtx;
std::unordered_map<int, mp::cpp_int> results;

mp::cpp_int calcPrimes(int n)
{
    char buf[10000] = { 0 };
    for (int i = '1'; i <= '9'; i+=2)
    {
        std::memset(buf, i, n);
        for (int j = '0'; j <= '9'; j++)
        {
            if (j != i)
            {
                for (int k = 0; k < n; k++)
                {
                    if (k > 0 || j > '0')
                    {
                        buf[k] = j;
                        mp::cpp_int num(buf);
                        if (miller_rabin_test(num, 10))
                        {
                            return num;
                        }
                        buf[k] = i;
                    }
                }
            }
        }
    }
    return 0;
}

void threadJob()
{
    for (;;)
    {
        int n = digits.fetch_add(1);
        auto result = calcPrimes(n);
        mtx.lock();
        results[n] = result;
        mtx.unlock();
    }
}

int main() {
    int count = 1;
    const auto start = std::chrono::steady_clock::now();
    const auto tc = std::thread::hardware_concurrency();
    std::vector<std::thread> threads;
    for (int j = 0; j < tc; j++)
        threads.emplace_back(threadJob);
    for (;;)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
        mtx.lock();
        auto seconds = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - start);
        for (const auto& result : results) {
            std::cout << std::setfill(' ') << std::setw(3) << result.first << ": " << result.second;
            std::cout << "  time: " << seconds.count() << " sec, count: " << count++ << "\n";
            if (result.second == 0)
            {
                std::cout << "Mathematical Immortality!!!";
                exit(1);
            }
        }
        results.clear();
        mtx.unlock();
    }
    for (int j = 0; j < tc; j++)
        threads[j].join();
}

```

Try it online!

# Answer
> 1 votes
# Python 3, computed till `n`=8

> "Takes 51 seconds for 8 digits"

Not a very interesting answer, I fear, and it's very slow.

```
from itertools import product as pt

def isprime(n):
    # This was borrowed from https://en.wikipedia.org/wiki/Primality_test
    # Modified to save bytes unnecessarily
    if n <= 3:return n > 1
    if not n%2 or not n%3:return False
    for i in range(5, int(n**.5)+1, 6):
        if not n%i or not n%(i+2):return False
    return True

def isnrep(n):
    if (not isprime(n)) or not (len(set(str(n)))==2):return False
    return list(str(n)).count(list(set(str(n)))[0])in[len(str(n))-1, 1]

def getnrepfor(n):
    x=[list(i)for i in eval("list(pt((1,2,3,4,5,6,7,8,9),"+("(0,1,2,3,4,5,6,7,8,9), "*(n-2))+"(1,3,7,9)))")]
    for i in range(len(x)):
        for j in range(len(x[i])):
            x[i][j]=str(x[i][j])
    x=[int("".join(i)) if isnrep(int("".join(i))) else '' for i in x]
    for i in x:
        if i!='':return i
    return 'It has been proven that for %d, there does not exist a near-repdigit' % n

```

Back to the bounty... I've found out that the amount of near-repdigit primes actually *increases* when the number of digits is increased. So I guess nobody will get that bounty.

Uses the 6k+-1 computation of primes.

I've updated this with an approach similar to lyxal's answer, but it hasn't produced much of a speedup. Oh well, guess esoteric languages are faster than those around 1991.

# Answer
> 1 votes
# Vyxal, at least n=116

```
ƛkdn1-v*9ʀẊ'ƒc¬;9ʀẊƛf÷$Ṁ;U'⌊=$⌊æ∧;h

```

Try it Online!

A simple modification of my answer to a CMC for near-rep numbers of length 8.

It can do up to n=116 in a minute on the online interpreter. Maybe more depending on where you run it.

The score here is cumulative total. If you want individual limits of `n`, it can handle at least n=200 in less than 10 seconds with a few modifications.

I'll explain this properly a bit later, but basically:

`kd7v*9ʀẊ` gets the Cartesian product of each digit from 0 to 9 repeated n times and the range \[0, 9\].

`'ƒc¬;` keeps items where the digit from the range isn't in the string (because this Cartesian product is \[repeated digit, number to insert at every position\])

`9ʀẊ` is once again Cartesian product with range \[0, 9\]. It gives a list of \[\[repeated digit, number to insert\], location to insert\]

`ƛf÷$Ṁ;` flattens each list, swaps the order of the number to insert and the position and performs the insertion

Finally, `'⌊=$⌊æ∧;` uniquifies the result and keeps only those invariant under conversion to int and which are also prime.

# Answer
> 1 votes
# JavaScript (Node.js), n = 351

Reached \\$n=351\\$ in 5 minutes on my laptop. Reaches \\$n\approx 250\\$ in 1 minute on TIO.

Uses a Miller-Rabin primality test with 10 rounds.

**NB**: Because the challenge allows a probability of false positive as high as 1/1000, we could actually perform fewer rounds -- at least until \\$n\\$ becomes really large. This would however not improve the performance drastically, as most of the computation is used for processing non-primes for which the test is most likely to fail on the first round anyway.

```
const ROUNDS = 10;

function modpow(k, e, m) {
  let r = 1n;

  while(e) {
    if(e & 1n) {
      r = (r * k) % m;
    }
    e >>= 1n;
    k = (k * k) % m;
  }
  return r;
}

function millerRabin(sz, n, k) {
  let d = n - 1n, s = 0n;
  do {
    s++;
    d >>= 1n;
  } while(!(d & 1n));

  while(k--) {
    let a;

    do {
      a = BigInt([...Array(sz)].map(_ => Math.random() * 10 | 0).join(''));
    } while(a < 2n || a > n - 1n);

    if(millerRabinIteration(n, d, s, a)) {
      return false;
    }
  }
  return true;
}

function millerRabinIteration(n, d, s, a) {
  let x = modpow(a, d, n);

  if(x == 1n || x == n - 1n) {
    return false;
  }

  for(let i = 0n; i < s - 1n; i++) {
    x = modpow(x, 2n, n);
    if(x == n - 1n) {
      return false;
    }
  }
  return true;
}

let ts = Date.now(), time;

for(let sz = 2; (time = Math.round((Date.now() - ts) / 1000)) < 300; sz++) {
  console.log(time + 's', 'n=' + sz, search(sz));
}

function search(sz) {
  for(let i = 1; i <= 9; i++) {
    let a = Array(sz).fill(i);

    for(let j = 0; j <= 9; j++) {
      for(let k = j ? 0 : 1; i !=j && k < sz; k++) {
        a[k] = j;
        let n = BigInt(a.join(''));
        if(
          n % 2n && n % 3n && n % 5n && n % 7n &&
          millerRabin(sz, n, ROUNDS)
        ) {
          return n;
        }
        a[k] = i;
      }
    }
  }
  return false;
}

```

Try it online!

# Answer
> 1 votes
# Kotlin, n = 575

```
fun main() {
    var n = 2
    while (true) {
        println(primesForN(n))
        n++
    }
}

fun primesForN(n: Int): String {
    for (major in '1'..'9') {
        // Java's String.repeat is much faster than Kotlin's
        @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
        val digits = (major.toString() as java.lang.String).repeat(n - 1)
        for (minor in '0'..'9') {
            if (major == minor) continue
            if (major.isEven()) {
                if (minor.isEven()) continue
                val number = digits + minor
                if (number.toBigInteger().isProbablePrime(10)) {
                    return number
                }
            } else {
                for (i in 0 until n - 1) {
                    if ((i == n - 1 && minor.isEven()) || (i == 0 && minor == '0')) continue
                    val number = digits.substring(0, i) + minor + digits.substring(i)
                    if (number.toBigInteger().isProbablePrime(10)) {
                        return number
                    }
                }
            }
        }
    }
    return "No near-repdigit primes found for n = $n"
}

fun Char.isEven() = this == '0' || this == '2' || this == '4' || this == '6' || this == '8'

```

Try it online!

Gotta love Kotlin's `CharRange`. The `isProbablePrime` test is a Miller-Rabin test that has a \\$\frac{1}{2^{10}}\\$ chance of failing. For ease, here is the jar file.

# Answer
> 1 votes
# Python 3 (PyPy), n = 808

~432 digits on TIO in one minute (no multiprocessing)

~808 digits on my computer in 5 minutes

~697 digits on my computer in 5 minutes on 1 core

Uses Baillie-PSW primality testing.

Avoids testing any multiple of 2, 3 or 5.

```
# aab -- a in [1,2,3,4,5,6,7,8,9]
#     -- b in [1,3,7,9]
# aba -- a in [1,3,7,9]
#     -- b in [0,1,2,3,4,5,6,7,8,9]
# baa -- a in [1,3,7,9]
#     -- b in [1,2,3,4,5,6,7,8,9]
# b + a*(n-1) != 0 mod 3

aab = [[(a,b) for a in [1,2,3,4,5,6,7,8,9] for b in [1,3,7,9] if (b + a*(n-1))%3] for n in range(3)]
aba = [[(a,b) for a in [1,3,7,9] for b in [0,1,2,3,4,5,6,7,8,9] if (b + a*(n-1))%3] for n in range(3)]
baa = [[(a,b) for a in [1,3,7,9] for b in [1,2,3,4,5,6,7,8,9] if (b + a*(n-1))%3] for n in range(3)]

def f(n):
    A = (10**n-1)//9
    # aab
    for a,b in aab[n%3]:
        if baillie_psw(a*A + (b-a)): return (n,a,b,0)
    # baa
    B = 10**(n-1)
    for a,b in baa[n%3]:
        if baillie_psw(a*A + (b-a)*B): return (n,a,b,n-1)
    # aba
    for k in range(1, n-1):
        B = 10**k
        for a,b in aba[n%3]:
            if baillie_psw(a*A + (b-a)*B): return (n,a,b,k)
    sike

def main():
    import multiprocessing
    import time
    t = time.time()
    for i in range(3, 2500, 2):
        if baillie_psw(i): small_primes.append(i)
    with multiprocessing.Pool(multiprocessing.cpu_count()-1 or 1) as pool:
        for i in pool.imap(f, range(2, 10000)):
            print(i, time.time() - t)

def baillie_psw(n):
    for p in small_primes:
        if n == p: return True
        if n%p == 0: return False
    return strong_pseudoprime(n) and lucas_prime(n)

small_primes = [2] # calculated out to 3000 in main

def ds(d):
    s = 0
    while d%2 == 0:
        s += 1
        d //= 2
    return d,s

def strong_pseudoprime(n):
    n1 = n-1
    d,s = ds(n1)
    x = pow(2,d,n)
    if x == 1 or x == n1: return True
    for _ in range(s):
        x = (x*x)%n
        if x == n1: return True
    return False

# code from https://en.wikipedia.org/wiki/Jacobi_symbol
def jacobi(D, n):
    D %= n
    t = 1
    while D:
        while D%2 == 0:
            D //= 2
            r = n%8
            if r == 3 or r == 5: t = -t
        n,D = D,n
        if D%4 == 3 == n%4: t = -t
        D %= n
    if n == 1: return t
    return 0

def sign(n):
    if n > 0: return 1
    if n < 0: return -1
    return 0

def isqrt(n):
    if n < 2: return n
    k = n//2
    k1 = n
    while k < k1:
        k1 = k
        k = (k+n//k)//2
    return k

def is_square(n):
    np = isqrt(n)
    return np*np == n

def UVQ(P, Q, D, k, m):
    u,v,q = 0,0,-1
    B = f'{k:b}'
    B1 = B.rstrip('0')
    for i in B1:
        u,v,q = (u*v)%m,(v*v-2*q)%m,(q*q)%m
        if i == '1':
            a = P*u + v
            b = D*u + P*v
            if a%2: a += m
            if b%2: b += m
            u,v,q = (a//2)%m, (b//2)%m, (Q*q)%m
    if u == 0 or v == 0: return True
    for _ in range(len(B)-len(B1)-1):
        u,v,q = (u*v)%m,(v*v-2*q)%m,(q*q)%m
        if v == 0: return True
    return False

def lucas_prime(n):
    for D in [5, -7, 9, -11, 13, -15, 17, -19, 21, -23, 25, -27, 29, -31, 33, -35, 37, -39, 41, -43]:
        J = jacobi(D, n)
        if J == -1: break
        if J == 0 and D%n: return False
    else:
        if is_square(n): return False
        else:
            while J != -1:
                D = -D - 2*sign(D)
                J = jacobi(D, n)
                if J == 0 and D%n: return False
    P = 1
    Q = (1-D)//4
    if Q == -1: P = Q = 5
    return UVQ(P, Q, D, n+1, n)

if __name__ == '__main__':
    main()

```

Try it online!

In profiling I found that about 97% of the time was spent in `strong_pseudoprime`, specifically the line `x = pow(2,d,n)`.

I wanted to avoid using external libraries in my answer, but it is possible to improve the speed significantly by using gmpy2 (or gmpy\_cffi with pypy), and replacing the line with `x = pow(mpz(2),d,n)`. This achieved ~1050 digits in 5 minutes.

# Answer
> 1 votes
# Wolfram Language (Mathematica), n=770

```
(n = #;
  r = RandomChoice[{1,3,7,9}];
  While[!
     PrimeQ[p =
       FromDigits@
        RandomSample[
         Join[Table[r,
           n - 2], {r1 =
            RandomChoice@Complement[Range[0, 9], {r}]}, {r}]]] ||
    r1 == r];
  i = IntegerDigits@p;
  f = First /@ Reverse@SortBy[Tally@i, Last];
  Flatten[{n, f, Position[i, f[[2]]]}]) &

```

Try it online!

n=500 in 1min
n=770 in 5min

# Answer
> 1 votes
# C++ (clang) with GMP n = 1164

To be compiled with the following flags: -O3 -lgmp -lpthread.

```
#include <atomic>
#include <chrono>
#include <cstring>
#include <iostream>
#include <mutex>
#include <thread>
#include <map>
#include <vector>
#include <gmp.h>

struct result
{
    char major;
    char minor;
    int pos;
};

std::atomic<int> digits{ 2 };
std::atomic<bool> timeOut{ false };
std::mutex mtx;
std::map<int, result> results;

result calcPrimes(int n)
{
    mpz_t x;
    char buf[10000] = { 0 };
    for (char i = '1'; i <= '9'; i+=2)
    {
        std::memset(buf, i, n);
        for (char j = '0'; j <= '9'; j++)
        {
            if (j != i)
            {
                for (int k = 0; k < n; k++)
                {
                    if (k > 0 || j > '0')
                    {
                        buf[k] = j;
                        mpz_init_set_str(x, buf, 10);
                        if (mpz_probab_prime_p(x, 10))
                        {
                            return { i, j, k };
                        }
                        buf[k] = i;
                    }
                }
            }
        }
    }
    return {};
}

void threadJob()
{
    while (!timeOut)
    {
        int n = digits.fetch_add(1);
        auto result = calcPrimes(n);
        mtx.lock();
        results[n] = result;
        mtx.unlock();
    }
}

int main() {
    int count = 0;
    int maxTime = 5 * 60;
    const auto start = std::chrono::steady_clock::now();
    const auto tc = std::thread::hardware_concurrency();
    std::vector<std::thread> threads;
    for (int j = 0; j < tc; j++)
        threads.emplace_back(threadJob);
    for (;;)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
        mtx.lock();
        auto seconds = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - start);
        if (seconds.count() >= maxTime)
        {
            timeOut = true;
            mtx.unlock();
            break;
        }
        for (const auto& result : results) {
            std::cout << result.first << ": " << "major: " << result.second.major << ", minor: " << result.second.minor << ", pos: " << result.second.pos;
            std::cout << ", time: " << seconds.count() << " sec, count: " << ++count << "\n";
        }
        results.clear();
        mtx.unlock();
    }
    for (int j = 0; j < tc; j++)
        threads[j].join();
    std::cout << "Time: " << maxTime << " seconds\n";
    std::cout << "Count: " << count << "\n";
}

```

Try it online!

# Answer
> 1 votes
# C (gcc) \+ GMP, n = 1015 (w/ -j2)

* Compile with same flags as in TIO.
* Specify number of threads as `-j jobs` depending on your hardware.

This uses `mpz_probab_prime_p()` from GMP which uses a combination of a Baille-PSW test, and then Miller-Rabin tests.

Output: ***digits majority minority location(1-indexed)***.

```
#define _XOPEN_SOURCE 700
#include <aio.h>
#include <gmp.h>
#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

typedef struct RepDigit {
    unsigned long maj;
    unsigned long min;
    unsigned long pos;
} RepDigit;

static RepDigit calc_primes(unsigned long digits);
static void init_ones(mpz_t rop, unsigned long digits);
static void *job(void *);

RepDigit
calc_primes(unsigned long digits)
{
    mpz_t rep, digit, num;
    unsigned long i, j, k;

    mpz_inits(rep, digit, NULL);
    init_ones(rep, digits);
    mpz_init_set(num, rep);
    mpz_add(rep, rep, rep);

    for (i = 1; i <= 9; mpz_add(num, num, rep), i += 2ul * (1ul + (i == 3))) {
        mpz_set_ui(digit, 10);
        for (k = 1; k < digits; mpz_mul_ui(digit, digit,  10), ++k) {
            mpz_submul_ui(num, digit, i);
            for (j = k == digits - 1; j <= 9; ++j) {
                if (j == i)
                    continue;
                mpz_addmul_ui(num, digit, j);
                if (mpz_probab_prime_p(num, 5))
                    goto end;
                mpz_submul_ui(num, digit, j);
            }
            mpz_addmul_ui(num, digit, i);
        }
    }

end:
    mpz_clears(rep, digit, num, NULL);
    return (RepDigit) {i, j, digits - k};
}

void
init_ones(mpz_t rop, unsigned long digits)
{
    mpz_ui_pow_ui(rop, 10, digits);
    mpz_sub_ui(rop, rop, 1);
    mpz_divexact_ui(rop, rop, 9);
}

void *
job(void *arg)
{
    RepDigit p;
    unsigned long n;
    char buf[2048][16];
    struct aiocb aiocbs[2048], *out;

    static atomic_ulong digits = 2;

    (void) arg;
    for (out = &aiocbs[0];; ++out) {
        n = atomic_fetch_add_explicit(&digits, 1, memory_order_relaxed);
        p = calc_primes(n);
        /* digits majority minority location(1-indexed) */
        out->aio_fildes = STDOUT_FILENO;
        out->aio_offset = 0;
        out->aio_buf = buf[out - aiocbs];
        out->aio_nbytes = snprintf(buf[out - aiocbs], sizeof buf[0], "%lu %lu %lu %lu\n", n, p.maj, p.min, p.pos);
        out->aio_reqprio = 0;
        out->aio_sigevent.sigev_notify = SIGEV_NONE;
        aio_write(out);
    }

    /* unreachable */
    return NULL;
}

int
main(int argc, char *argv[])
{
    int opt, jobs;
    pthread_t t;
    extern char *optarg;

    jobs = 1;
    while ((opt = getopt(argc, argv, "j:")) > 0) {
        switch (opt) {
        case 'j':
            jobs = atoi(optarg);
            if (jobs > 0)
                break;
            /* fallthrough */
        default:
            fprintf(stderr, "usage: %s [-j jobs]\n", argv[0]);
            exit(EXIT_FAILURE);
        }
    }

    while (jobs --> 1) {
        pthread_create(&t, NULL, &job, NULL);
        pthread_detach(t);
    }

    job(NULL);

    /* unreachable */
    return 0;
}

```

Try it online! n ~ 700 (w/ `-j2`).

# Answer
> 1 votes
# Python, with gmpy2, n=920

~920 digits in 5 minutes on my Windows machine

```
import gmpy2
import time

def nrdprime(n):
    for j in range(1,10):
        for k in range(n, 0, -1):
            for l in range(10):
                if j == l: continue
                if l == 0 and k == 1: continue
                a = [j] * n
                a[k-1] = l
                if a[n-1] % 2 == 0: continue
                x = int(''.join(map(str, a)))
                if gmpy2.is_prime(x):
                    print(n, j, l, k)
                    return x
    print(n, "has no answer")

start_time = time.time()
i = 2

while time.time() - start_time < 300:  # Run for 300 seconds (5 minutes)
    nrdprime(i)
    i += 1

print(f"Processed up to n = {i-1} in 5 minutes.")

```

# Answer
> 0 votes
# C++ (gcc), n = 595

* Compile with `-O3 -pthread -lfmt`

```
#include <atomic>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/miller_rabin.hpp>
#include <fmt/core.h>
#include <thread>

namespace mp = boost::multiprecision;

struct RepDigit {
    int pos;
    char maj, min;
};

static std::atomic<int> digits{2};

static RepDigit
calcPrimes(int digits)
{
    static const mp::cpp_int ten{10};
    char buf[2048] = {};
    for (char i = '1'; i <= '9'; i += 2) {
        std::memset(buf, i, digits);
        mp::cpp_int num{buf};
        mp::cpp_int n{ten};
        for (int k = 1; k < digits; n *= ten, ++k) {
            for (char j = '9'; j >= '0'; --j) {
                if (j == i)
                    continue;
                num += n * (j - i);
                if (mp::miller_rabin_test(num, 10))
                    return {digits - k, i, j};
                num -= n * (j - i);
            }
        }
    }
    return {};
}

static void
job()
{
    for (;;) {
        auto n = digits.fetch_add(1);
        auto p = calcPrimes(n);
        /* digits majority minority location(1-indexed) */
        fmt::print("{} {} {} {}\n", n, p.maj, p.min, p.pos);
    }
}

int
main()
{
    for (auto hc = std::thread::hardware_concurrency(); hc > 1; --hc)
        std::thread{job}.detach();

    job();
}

```

No TIO link because it doesn't have {fmt}.

# Answer
> 0 votes
# PARI/GP, 164 bytes, n = 839

```
f(n)=d=(10^n-1)/9;for(i=1,9,for(j=0,n-1,for(k=0,9,if(i!=k&&(k>0||j<n-1)&&((i*n+k-i)%3)&&ispseudoprime(p=d*i+(k-i)*10^j),return(p)))))
for(n=2,oo,print(n" -> "f(n)))

```

Attempt This Online!

The `ispseudoprime` function uses the BPSW primality test. Currently no counterexample is known.

The package name for PARI/GP is `pari-gp` on Ubuntu, Debian, Arch Linux and some other distros.

Runs as `gp -qf ./file_name.gp`.

---
Tags: primes, fastest-code
---