title: Find the Nth pair of twin primes

text:
# Question
Title: Find the Nth pair of twin primes
Two prime numbers are defined as twin primes if they differ by two. For example, 3 and 5 are twin primes as are 29 and 31.

Write a program that finds the nth pair of twin primes (where n comes from STDIN) and prints them on STDOUT, separated by a comma and a space. This is code-golf, so the shortest code wins.

Sample input:

```
3

```

Sample output:

```
11, 13

```

# Answer
> 11 votes
# Haskell 118

```
main=putStrLn.(!!)[show n++", "++show(n+2)|n<-[2..],all((>0).rem n)[2..n-1],all((>0).rem(n+2))[2..n]].(+)(-1)=<<readLn

```

Brute-force all twin primes and prints the nth pair.

# Answer
> 10 votes
# CJam, ~~29~~ 26 bytes

```
Y4]{{:)_{mp}/&!}g}q~*", "*

```

Try it online.

### Examples

```
$ for i in {1..10}; do cjam twin-primes.cjam <<< $i; echo; done
3, 5
5, 7
11, 13
17, 19
29, 31
41, 43
59, 61
71, 73
101, 103
107, 109

```

### How it works

```
Y4]        " Push [ 2 4 ].                                                            ";
{          "                                                                          ";
  {        "                                                                          ";
    :)     " Increment each integer in the array.                                     ";
    _      " Duplicate the array.                                                     ";
    {mp}/  " For each integer in the array, push 1 if it's prime and 0 otherwise.     ";
    &!     " Compute the logical NOT of the bitwise AND of the two previous integers. ";
  }g       " If the result is non-zero, repeat the loop.                              ";
}q~*       " Do the above “N” times, where “N” is the integer read from STDIN.        ";
", "       " Join the array by comma and space.                                       ";

```

# Answer
> 9 votes
# Perl, 101 87

### 87 characters, building over aschepler's comment

```
$n=pop;$r='^1$|^(11+?)\1+$';($t=1x$s)=~$r||"11t"=~$r||--$n||die"$s, ",$s+2,$/while++$s

```

### 101 characters, earlier answer

```
$n=pop;$r=qr/^1$|^(11+?)\1+$/;(1x$s)!~$r&&(1x($s+2))!~$r&&++$i==$n&&say($s,", ",$s+2)&&exit while++$s

```

### Usage:

```
$ perl ./twin_primes.pl 10
107, 109

```

### Explanation

```
$n = pop;                 # Pulls twin prime pair counter from @ARGV
$r = qr/^1$|^(11+?)\1+$/; # The money line - a regex that verifies
                          # if a string of 1's has non-prime length

while ( ++$s ) {          # Loop over integers

                          # '&&' short-circuits
    (1 x  $s    ) !~ $r   # Negated regex match evaluates to true if $s is prime
 && (1 x ($s+2) ) !~ $r   # Same for $s + 2
 &&          ++$i == $n   # Counter to control which pair to print
 && say( $s, ", ", $s+2 ) # Print the line
 && exit                  # Terminate program
}

```

The workings of the non-primality regex is explained in this SO question.

# Answer
> 8 votes
# C: 113

```
n,c,l;main(i){for(scanf("%d",&n),l=2;n;l=c==i?n-=i==l+2,i:l,i+=2)for(c=2;c<i&&i%c++;);printf("%d, %d\n",l-2,l);}

```

Sample run:

```
$ for i in $(seq 1 10); do echo $i | ./twinprimes; done
3, 5
5, 7
11, 13
17, 19
29, 31
41, 43
59, 61
71, 73
101, 103
107, 109

```

Thanks for help from Dennis, bebe, and Alchymist.

# Answer
> 6 votes
# CJam - 26

```
1e4,{mp},_2f-&qi(=_2+", "\

```

It works for primes smaller than 10000; you can replace `4` with a higher exponent for larger numbers (potentially up to 1020), but the program will get slower and will use more memory.

Try it at http://cjam.aditsu.net/

**Explanation:**

`1e4,` creates the array \[0 1 2 ... 9999\]
`{mp},` selects only the prime numbers
`_2f-` copies the array and subtracts 2 from each item
`&` intersects the two arrays, thus finding the lower primes from each twin prime pair
`qi` reads the input and converts to integer
`(=` adjusts the index and gets the corresponding (lower) twin prime from the array
`_2+` copies the prime and adds 2
`", "\` puts the comma and space between the two primes

# Answer
> 4 votes
# Javascript (E6) 92 ~~96~~

Shorter and compliant - use spidermonkey shell to read stdin/write stdout (with comma and space). It finds the 10000th pair 1260989, 1260991 in under a minute on my PC
Could be shorter using `p[n]=o=n` instead of `p.push(o=n)`, so that the p array is sparse. But that's quite slower, and I'm not going to win for code length anyway.

```
m=readline();for(n=3,o=p=[];m;n+=2)p.every(e=>n%e)&&(m-=n-o<3,p.push(o=n));print(o-2+', '+o)

```

To try in firefox console:

```
m=prompt();for(n=3,o=p=[];m;n+=2)p.every(e=>n%e)&&(m-=n-o<3,p.push(o=n));alert(o-2+', '+o)

```

**Ungolfed**

A function that found all first m twins (returns the largest value):

```
T=m=>{
  for (o=n=3, p=[2], t=[]; !t[m-1]; n+=2)
    p.every(e => n%e) && (n-o-2 ? 0 : t.push(n), p.push(o=n))
  return t
}

```

Example: `console.log(T(50))`

`[5, 7, 13, 19, 31, 43, 61, 73, 103, 109, 139, 151, 181, 193, 199, 229, 241, 271, 283, 313, 349, 421, 433, 463, 523, 571, 601, 619, 643, 661, 811, 823, 829, 859, 883, 1021, 1033, 1051, 1063, 1093, 1153, 1231, 1279, 1291, 1303, 1321, 1429, 1453, 1483, 1489]`

Just the last:

```
L=m=>{
  for (o=n=3,p=[2]; m; n+=2)
    p.every(e => n%e) && (m -= n-o==2, p.push(o=n))
  return o
}

```

Then, take that 2 lines and add IO

```
m = prompt()
for (o=n=3, p=[2]; m; n+=2)
  p.every(e => n%e) && (m -= n-o==2, p.push(o=n))
alert('o-2+', '+o)

```

# Answer
> 4 votes
## C#, 265

```
using System.Linq;class P{static void Main(string[] args){var i=int.Parse(args[0]);int f=0,c=0;for(int j=1;;j+=2){var b=(Enumerable.Range(1,j).Count(x=>j%x==0)==2);if(f==0 && b){f=j;continue;}if(b){c++;if(c==i){System.Console.WriteLine(f+","+j);break;}j-=2;}f=0;}}}

```

# Answer
> 4 votes
# J - ~~49 60 55~~ 51 bytes

I decided to go with a simple approach. Function `t` finds the next twin prime given a prime number as input (now this is included in the `f` function). Function `f` finds the nth twin prime. This also happens to be the first actual program I've written in J.

```
f=:[:(":,', ',":@+&2)(4&p:(,{~-=2:)])^:_@>:^:(]`2:)

```

Examples:

```
   f 1
3, 5
   f 2
5, 7
   f 3
11, 13
   f 4
17, 19
   f 5
29, 31
   f 100000
18409199, 18409201

```

Just for some eyebrowraises, have the ungolfed version.

```
twin =: (4&p:)(($:@[)`(,)@.(=(]+2:)))]
f    =: ((]-2:),])((0:{twin) ^: (]`(2:)))

```

### Explanation:

```
f=:[:(":,', ',":@+&2)(4&p:(,{~-=2:)])^:_@>:^:(]`2:)
                     (4&p:(,{~-=2:)])^:_@>:^:(]`2:)
                                        @>:^:(]`2:)  main loop
                                           ^:(]`2:)  Repeat n times, starting with value of 2
                                        @>:          Add one to the current value and apply to the following function.
                     (4&p:(,{~-=2:)])^:_             Get the next twin prime
                                     ^:_             Recurse until there's no change
                          (,{~-=2:)                  If next prime - current value == 2, return current value, otherwise the next prime.
                      4&p:                           Get the next prime
     (":,', ',":@+&2)                                Format the output and add 2 to the second value.
   [:                                                Apply the twin prime to the formatter.

Basically, if n is 4, this creates a recursion tree like this:
 let T be the recursion inside t
 and numbers between rows the return values of according function
   (t * n) 3
-> (t * 4) 3
-> t  t  t  t  3
   17 11 5  3
-> (T  T) (T  T) T  T  3
    17 13  11 7  5  3
-> 17

```

# Answer
> 4 votes
## Mathematica - 63 characters

```
Print[#-2,", ",#]&@Nest[NestWhile[NextPrime,#,#2-#!=2&,2]&,1,n]

```

### Notes

This is in fact a rather straightforward implementation. Shortening resulted in almost no obfuscation.

`NextPrime` is a builtin that finds the next prime after a number.

`NestWhile[NextPrime,#,#2-#1!=2&,2]&` is an anonymous function that finds the larger prime of the next twin prime pair after a number.

`Nest` applies this anonymous function `n` times.

`Print[#-2,", ",#]&` is an anonymous function that prints to stdout according to the specifications. Sadly this alone takes up 18 characters of the 63 character solution.

### Example

> ```
> In[1]:= Do[
>          Print[#-2,", ",#]&@Nest[NestWhile[NextPrime,#,#2-#!=2&,2]&,1,n],
>          {n, 1, 10}
>         ]
> 3, 5
> 5, 7
> 11, 13
> 17, 19
> 29, 31
> 41, 43
> 59, 61
> 71, 73
> 101, 103
> 107, 109
>
> ```

---

**Update:** Two characters could be saved by reimplementing this CJam solution. However, this algorithm limits the maximum value of `n`. Just replace the `Nest...` part by `Intersection[#,#-2][[5]]&@Prime@Range[999]`

# Answer
> 2 votes
# Perl, ~~100~~ 95

```
$n=<>;$i=3;while($c<$n&&($l=$i++)){$i++until!grep{$i%$_<1}(2..$i-1);$c++if$i-$l<3}print"$l, $i"

```

Ungolfed:

```
$n = <>;          # Read from STDIN
$i = 3;           # Tiny hack because I know I don't need the number 2
while ($c<$n && ($l = $i++)) {   # $c counts the pairs, $l is the last prime
  $i++ until ! grep {$i%$_<1} (2..$i-1);   # Increase $i until it's not divisible by anything
  $c++ if $i-$l < 3   # If $i and $l are twin primes, count it
}
print "$l, $i"    # That damned comma added a whole character to my code!

```

# Answer
> 2 votes
### Ruby 94

```
require'mathn'
n=gets.to_i
a=1
(a+=2;a.prime?&&(a+2).prime?&&n-=1)while n>0
$><<"#{a}, #{a+2}"

```

Online test: http://ideone.com/B2wxnG

# Answer
> 2 votes
## T-SQL (2008+): 344

Brute force a CTE to find primes, window function to count n, followed by a join to find the twin. Works in a second for outputs \< 1,000, just under a minute for outputs \< 10,000.

Golfed (SQLFiddle **here**):

```
WITH x(i) AS(SELECT 99 UNION ALL SELECT i-2
FROM x WHERE i>3),z AS(SELECT RANK()OVER(ORDER BY x.i)n,x.i
FROM x x LEFT JOIN x y ON x.i%y.i=0 AND y.i NOT IN(x.i,1)
WHERE y.i IS NULL)SELECT LTRIM(a)+', '+LTRIM(b)FROM(SELECT RANK()
OVER(ORDER BY x.i)n,x.i a,y.i b FROM z x,z y WHERE x.n=y.n-1
AND x.i=y.i-2) o WHERE n=3
OPTION(MAXRECURSION 0)

```

Legible:

```
WITH x(i) AS (
   SELECT 99
    UNION ALL
   SELECT i-2
   FROM x
   WHERE i > 3
)
,z AS (
SELECT RANK()OVER(ORDER BY x.i)n,x.i
FROM x x
WHERE NOT EXISTS
  (SELECT *
   FROM x y
   WHERE x.i%y.i = 0
    AND y.i NOT IN (x.i,1)
  )
)
SELECT LTRIM(a)+', '+LTRIM(b)
FROM (
    SELECT RANK()OVER(ORDER BY x.i)n,x.i a, y.i b
    FROM z x, z y
    WHERE x.n = y.n+1
    AND x.i = y.i+2
) o
WHERE n = 3
OPTION(MAXRECURSION 0)

```

# Answer
> 2 votes
# Vyxal , 57 bitsv2, 8.125 7.125 bytes

```
Þp'⇧æ;i:⇧

```

Try it Online!

Bitstring:

```
001010110100000101111000110100001000110100111000111011110

```

0-indexed

# Answer
> 1 votes
# PHP 5.4, 223

Not a smaller one, But one try from php.

```
$n=$argv[1];function i($k){for($i=2;$i<=(int)($k/2);$i++)if($k%$i==0)return 0;return 1;}function t($t){return (i($t) && i($t+2))?1:0;}$g=1;$d=0;do{if(t($g)==1){if($d<$n){$d++;}else{print_r([$g,$g+2]);break;}}$g++;}while(1);

```

# Answer
> 1 votes
## C 309

Keeps getting next primes and store odd and even terms then checks if the difference is two.

```
int main()
{
int n;
scanf("%d",&n);
int a=2,b=3,k=2,q;
int odd=1;
int p;
if(n>0)
{
while(n)
{
k++;
p=1;
q=ceil(sqrt(k));
for(int i=2;i<=q;i++)
{
if(k%i==0)
{
p=0;
break;
}
}
if(p)
{
if(odd%2==0)a=k;
else b=k;
if(abs(a-b)==2)n--;
odd++;
}
}
}
printf("%d %d\n",a,b);
return 0;
}

```

# Answer
> 1 votes
### GolfScript 46

```
~[1 3]\{\{))}%.{:x,{)x\%!},,2=}/*@\-.}do;', '*

```

Online test: link

**Annotated code:**

```
~                       # parse the input as an int
[1 3]                   # add the array [1, 3] on the stack
\                       # invert the items on the stack
{                       # begin loop
  \                     # bring the array to the top of the stack
  {))}%                 # add 2 to each of the numbers in the array
  .{:x,{)x\%!},,2=}/    # check if numbers are prime (leaves a 0 or 1 for both numbers on the stack)
  *                     # multiply the two 0/1 numbers (will only get 1 if both are 1)
  @\-                   # subtract the result from the inital int
  .                     # copy the new int value on the stack to be consumed by the 'do' loop
}do                     # repeat until the initial int was taken down to 0
                        # at this point the array contains the two numbers we're looking for
;                       # get rid of the 0 from the stack
', '*                   # format the output

```

# Answer
> 1 votes
## R, 91 chars

```
a=scan();n=1;p=5;while(n!=a){p=p+1;q=p-2;if(sum(!p%%2:p,!q%%2:q)<3)n=n+1};cat(q,p,sep=", ")

```

Nothing really fancy:

```
a=scan()
n=1
p=5
while(n!=a){
    p=p+1
    q=p-2
    if(sum(!p%%2:p,!q%%2:q)<3) # Check that p and q are both primes by checking
       n=n+1                   # the number of zeroes resulting from
}                              # p modulo each integers 2 to p and same for q
cat(q,p,sep=", ")

```

Usage:

```
> a=scan();n=1;p=5;while(n!=a){p=p+1;q=p-2;if(sum(!p%%2:p,!q%%2:q)<3)n=n+1};cat(q,p,sep=", ")
1: 10
2:
Read 1 item
107, 109

```

# Answer
> 1 votes
# Japt, ~~23~~ 19 bytes

-4 bytes thanks to Shaggy

```
@µX°j ©°Xj}f
[UU+2]

```

Run it online

# Answer
> 1 votes
# Husk, 11 bytes

```
!fo=2F≠Ẋeİp

```

Try it online!

non-competing, since it takes input from arguments rather than STDIN.

Returns a 2-element list.

Interesting version using `Ψ`: Try it online!

# Answer
> 1 votes
### PHP (153)

```
$nth=readline();$i=1;$l=1;$c=0;while(1){$q=0;for($j=1;$j<=$i;$j++){$q+=$i%$j==0?1:0;}if($q==2){if($i-$l==2&&++$c==$nth){echo"$l, $i";break;}$l=$i;}++$I;}

```

Readable format with properly named variables:

```
$nth = readline();

$i = 1;
$lastFoundPrime = 1;
$countOfFoundPrimes = 0;

while (1) {
  $quotient = 0;
  for ($j = 1; $j <= $i; $j++) {
    $quotient += $i % $j == 0 ? 1 : 0;
  }
  if ($quotient == 2) {
    if ($i - $lastFoundPrime == 2 && ++$countOfFoundPrimes == $nth) {
      echo "$lastFoundPrime, $i";
      break;
    }
    $lastFoundPrime = $i;
  }
  ++$i;
}

```

And wrapped in a for loop:

```
foreach (range(1, 10) as $nth) {

  $i = 1;
  $lastFoundPrime = 1;
  $countOfFoundPrimes = 0;
  while (1) {
    $quotient = 0;
    for ($j = 1; $j <= $i; $j++) {
      $quotient += $i % $j == 0 ? 1 : 0;
    }
    if ($quotient == 2) {
      if ($i - $lastFoundPrime == 2 && ++$countOfFoundPrimes == $nth) {
        echo "$lastFoundPrime, $i";
        break;
      }
      $lastFoundPrime = $i;
    }
    ++$i;
  }

  echo "\n";
}

```

Output:

```
3, 5
5, 7
11, 13
17, 19
29, 31
41, 43
59, 61
71, 73
101, 103
107, 109

```

# Answer
> 1 votes
**APL(NARS), 63 chars**

```
P;w;p;r
w←⎕⋄p←2
→3×⍳0≥w⋄w-←2=p-⍨r←1πp⋄p←r⋄→2
⎕←∊⍕¨3⌽', ',p,p-2

```

7+7+28+17+4=63 test

```
  P
⎕:
  1
3, 5
  P
⎕:
  1000
79559, 79561
  P
⎕:
  100000
18409199, 18409201

```

# Answer
> 0 votes
# AWK - 129

The file `fsoe-pairs.awk`:

```
{n=2;N=1
for(;;){if(n in L){p=L[n];del L[n]}else{p=n
if(n-N==2)if(!--$0){print N", "n;exit}N=n}P=p+n++
while(P in L)P+=p;L[P]=p}}

```

Running it:

```
$ awk -f fsoe-pairs.awk
1
3, 5
$ awk -f fsoe-pairs.awk
2
5, 7
$ awk -f fsoe-pairs.awk
10
107, 109

```

(1st line after command is input, the 2nd one is output)

This is based on an own prime generator algorithm I call "floating sieve of erastosthenes" (until I find it described elswhere) which only stores the needed part of the sieve and the already calculated primes.

# Answer
> 0 votes
## JavaScript (Node.js), 162 chars

Reads from stdin, outputs to stdout, exits "early" for input `<= 0`.

```
t=process.argv[2],c=0,l=1;if(t>0){for(i=0;;i++){p=!Array(i+1).join(1).match(/^1?$|^(11+?)\1+$/);if(p){if(i-2==l){if(c>=t-1){console.log(l+", "+i);break}c++}l=i}}}

```

Usage (script above saved as `ntp.js`):

```
>for /l %x in (0, 1, 10) do node ntp.js %x
>node ntp.js 0
>node ntp.js 1
3, 5
>node ntp.js 2
5, 7
>node ntp.js 3
11, 13
>node ntp.js 4
17, 19
>node ntp.js 5
29, 31
>node ntp.js 6
41, 43
>node ntp.js 7
59, 61
>node ntp.js 8
71, 73
>node ntp.js 9
101, 103
>node ntp.js 10
107, 109

```

# Answer
> 0 votes
# Python 2 (75)

```
c=input()
n=3
while c:n+=2;c-=all(n%i&~2for i in range(2,n-2))
print(n-2,n)

```

So what's going on here?

First, let's look at the expression `all(n%i&~2for i in range(2,n-2))`, which checks if `(n-2,n)` are a pair of twin primes.

The simpler expression `all(n%i for i in range(2,n))` simply checks if `n` is prime by trying every divisor `i` in the range `2<=i<=n-1`, and seeing if all remainders are nonzero. This `all` checks exactly this, since Python treats `0` as `False` and all other numbers as `True`.

Now, observe that `(n-2)%i==0` exactly when `n%i==2` for divisors `i>2`. So, we can perform the primality check on `n` and `n-2` at the same time by checking the remainders for both `0` and `2`. This could be done as `all(n%i not in [0,2] for i in range(2,n-2))`. We only try divisors in the range `2<=i<=n-3` for the sake of `n-2`, but this suffices for `n` as well since `n-1` and `n-2` can't be divisors unless `n<=4`. We will only try odd `n` starting from `5` to avoid this complication and that of the divisor `i=2`.

We golf the expression `n%i not in [0,2]` into `n%i&~2`, remembering that `0` is False and other numbers are `True`. The operator precedence `(n%i)&(~2)` is exactly what's needed. The bit-complement `~2` is `...11111101`, so its bitwise `and` with a number zeroes-out the `2`'s binary place value. This gives `0` (i.e., `False`) only for `0` and `2`, exactly what we want.

Phew! Now we have that the expression `all(n%i&~2for i in range(2,n-2))` checks whether `n` is the upper number of a twin prime pair. What remains is to iterate over them until we see `c` of them, where `c` is the inputted number. We start with `5` and counting up by `2` to avoid divisor issues. We decrement `c` each time we encounter an `n` that works, stopping when `c=0`. Finally, we print the twin prime pair that we end with.

# Answer
> 0 votes
# T-SQL(2012+),255 characters

A more compact T-SQL twin prime finder that also gets a little bit of a speed up.

```
with t(n)as(select 2+number from spt_values where type='p')select*from(select concat(b,', ',a),rank()over(order by a)from(select n,lag(n)over(order by n)from t where not exists(select*from t f where f.n<t.n and t.n%f.n=0))z(a,b)where a=b+2)r(s,k)where k=2

```

Human readable format::

```
    with t(n)as(
        select 2+number
        from spt_values
        where type='p'
    )
    select *
    from(
        select concat(b,', ',a),rank() over (order by a)
        from(
            select n, lag(n) over(order by n)

    from t
        where not exists(
            select 1 from t f
            where f.n<t.n and t.n%f.n=0)
    ) z(a,b)
    where a=b+2
) r(s,k)
where k=2

```

The basic gist is we use the built in table of numbers (master..spt\_values type='p') and alias that with a CTE as something short. We add 2 to remove the worry of pulling 0 or 1 trivial errors for our set, so now we have candidates of 2,2050.

Z the inner most query gets all primes from 2 to 2050, by filtering out any number n that is divisible by a number less than n. We then use a nifty T-SQL 2012 windowing function `lag` that lets us pull the previous result, so now Z's results a and b are the primes `P[n]` and `P[n-1]` respectively. The R query creates the output string, and filters out non-twin primes and also creates a sequence number for the output we call K. Finally the last query R allows us to filter and get the Kth twin prime by changing its variable.

# Answer
> 0 votes
**Mathematica -- 71 bytes**

```
n=Input[];
i=j=0;
While[j<n,i++;If[And@@PrimeQ[x={i,i+2}],j++]];Print@x

```

# Answer
> 0 votes
# PHP 8.3 145char

Runs up to 10,000 actually I had difficulty with `readline` simulating `stdin` not using this very often.

Programming support: Notepad

```
$j=readline();for($i=1;$i<10000;$i=$i+2){if((gmp_prob_prime($i))&&(gmp_prob_prime($i+2))){$x++;}if($x==$j){break;}}echo"$i, "; $i=$i+2;echo"$i";

```

```
$j=readline();
for ($i=1;$i<10000;$i=$i+2) {
if ((gmp_prob_prime($i))&&(gmp_prob_prime($i+2))) {$x++;}
if($x==$j) {break;}
}
echo"$i, ";
$i=$i+2;
echo"$i";

```

Output $j=\[1-12\]:

```
3, 5
5, 7
11, 13
17, 19
29, 31
41, 43
59, 61
71, 73
101, 103
107, 109
137, 139
149, 151

```

---
Tags: code-golf
---


title: Extract a string from a given string

text:
# Question
Title: Extract a string from a given string
You are given a string and two characters. You have to print the string between these characters from the string.

# Input

Input will first contain a string (not empty or `null`). In the next line, there will be two characters separated by a space.

# Challenge

Return the string between the two characters

# Example

```
Hello! What's your name?
! ?

```

should result in the output:

```
" What's your name"

```

# Rules

* The string will not be longer than 100 characters and will only contain ASCII characters in range (space) to `~`(tilde) (character codes 0x20 to 0x7E, inclusive). See ASCII table for reference.
* You must take input from the `stdin`( or closest alternative ).
* The output should be surrounded with quotes(`"`).
* You can write a full program, or a function which takes input, and outputs the final string
* The two characters will only contain ASCII characters in range (space) to `~`(tilde) (character codes 0x20 to 0x7E, inclusive). See ASCII table for reference.
* There is no guarantee that both the characters will be in the string.
* If any of the characters is not found in the string, print `"null"`.
* If any of the characters is found more than one times (unless both the characters are same) in a string, print `"null"`.
* If both the characters are the same character, print the string `"null"`.

# Test Cases

1)

```
<HTML>code</HTML>
> <                       --> "null"

```

2)

```
What's what?
' '                       --> "null"

```

3)

```
abcdefghijklmnopqrstuvwxyz
n k                       --> "lm"

```

4)

```
Testing...
e T                       --> ""

```

5)

```
Last test-case
  -                       --> "test"

```

# Scoring

This is code golf, so the shortest submission (in bytes) wins.

# Answer
# CJam, ~~34~~ ~~33~~ 32 bytes

```
'"l_l2%&2*2>NerN/0"null"t_,3=='"

```

Try it online in the CJam interpreter.

### Idea

1. Remove the second character from line 2.
2. Form a string consisting of a single copy of all characters that both lines have in common.
3. Repeat the resulting string twice and discard its first two characters.

This results in a two-character string (if the characters from line 2 are different and both occur in line 1) or an empty string.
4. Replace the characters of the resulting string in line 1 by linefeeds.
5. Split line 1 at linefeeds.

The resulting array's second element will be the desired string if the array contains exactly three chunks.
6. Replace the first element of the array with the string **null**.
7. Retrieve the second element of the array if its length is 3 and the first otherwise.
8. Prepend and append a double quote.

### Code

```
'"       e# Push a double quote.
l_       e# Read one line from STDIN. Push a copy.
l2%      e# Read one line from STDIN. Only keep characters at odd indexes.
&        e# Intersect both strings.
2*2>     e# Repeat the intersection twice and discard the first two characters.
Ner      e# Replace the characters of the resulting string with linefeeds.
N/       e# Split the result at linefeeds.
0"null"t e# Replace the first element of the resulting array with "null".
_,3=     e# Push 1 if the length of the array is 3 and 0 otherwise.
=        e# Retrieve the corresponding element from the array.
'"       e# Push a double quote.

```
> 3 votes

# Answer
# CJam, 38 bytes

```
l:Tl2%f#_W-$2,=2,@f#$~T<>1>"null"?'"_o

```

Too long...

### Explanation

```
l:T             e# Read a line and store in T.
l2%             e# Read the two characters into a list.
f#              e# Find each character in the list of two characters.
_W-             e# Copy and remove not found results.
$2,=            e# Sort and check if the result is exactly [0 1].
                e# If true:
2,@f#           e# Find 0 and 1 in the original results.
$               e# Sort.
~T<>            e# Get a slice of T between the two positions (left-closed).
1>              e# Remove the first character.
                e# If false:
"null"          e# The string "null".
?               e# End if.
'"_o            e# Append a quote and output another quote at the beginning.

```
> 2 votes

# Answer
# Pyth, ~~37~~ ~~36~~ 34 bytes

```
p?"null"njT9m/zd{J%2wt:z.uSmxzdJNN

```

Thanks to @isaacg for the two bytes save.

Try it online: Pyth Compiler/Executor

### Explanation:

```
                                     implicit: z = first input line
                    w                second input line
                  %2                 only use every 2nd char
                 J                   and store in J
                {J                   set(J), gets rid of duplicates
            m/zd                     count the number of appearances of each char
        njT1                         != [1, 1] ([1,1] is 10 in base 9)
 ?      njT1m/zd{J%2w                ... if [1,1] != number of appearances else ...
  "null"                               string "null"
                           mxzdJ     find the index for each char
                          S          sort the indices
                      :z.u           take the substring of z using these indices
                     t               remove the first char

p                               NN  print '"' + ... + '"'

```
> 2 votes

# Answer
# Ruby, ~~108~~ ~~95~~ 94

```
->s,f,l{a,b=[f,l].map{|u|(f==l||s.count(u)>1)&&abort('"null"');s.index u}.minmax;p s[a+1...b]}

```

And for the ungolfed version

```
def between(string, first, last)
    left, right = [first, last].map do |substring|
        abort('"null"') if first == last || string.count(substring) != 1
        string.index(substring)
    end.minmax
    p string[left + 1 ... right]
end

```
> 2 votes

# Answer
# Python 3, 149 bytes

```
s,i=input(),input();a,b=s.find(i[0]),s.find(i[2]);print('"'+('null',[s[a+1:b],s[b+1:a]][b<a])[(s.count(i[0])==s.count(i[2])==1)*(a!=b)*(a*b>-1)]+'"')

```

Ungolfed Version:

```
string, chars = input(), input()
a, b = string.find(chars[0]), string.find(chars[2])

    if string.count(chars[0]) == string.count(chars[2]) == 1 and a!=b and a*b>-1:
        if b<a:
            print('"' + string[b+1:a] + '"')
        else:
            print('"' + string[a+1:b] + '"')
else:
    print('"null"')

```

This is my first answer here, so tips and criticism are much appreciated.
> 2 votes

# Answer
# TypeScript's Type System, 160 bytes

```
//@ts-ignore
type F<S,U,Y=any,O={[K in U]:S extends`${Y}${K}${infer X}${Exclude<U,K>}${Y}`?S extends`${Y}${K}${Y}${K}${Y}`?0&1:X:0&1}[U]>=O extends 0&1?"null":O

```

Try it at the TypeScript playground!

This is a generic type `F` taking the string as the first type parameter `S` and the characters as a union type `U`.

If the input was two distinct characters that were guaranteed only to each appear once in the string, this would be 59 bytes:

```
type F<S,A,B>=S extends`${any}${A}${infer X}${B}${any}`?X:0

```

My original solution was around 150 bytes before I realized that the program had to check for the characters in either order, adding many bytes. I came up with the following solution at 161 bytes:

```
//@ts-ignore
type F<S,A,B,Y=any,Z="null">=S extends`${Y}${`${A}${infer X}${B}`|`${B}${infer X}${A}`}${Y}`?S extends{[K in A|B]:`${Y}${K}${Y}${K}${Y}`}[A|B]?Z:X:Z

```

...but then I thought of the current solution and it ended up exactly 1 byte shorter.

Explanation coming soon.
> 2 votes

# Answer
# C, 192 bytes

```
f(){char b[101],c,d,*p,*t;scanf("%[^\n]%*c%c%*c%c",b,&c,&d);p=strchr(b,c);t=strchr(b,d);c==d||!p||!t||strchr(p+1,c)||strchr(t+1,d)?puts("\"null\""):printf("\"%s\"",p<t?(*t=0,p+1):(*p=0,t+1));}

```

Ungolfed code:

```
f()
{
    char b[101],c,d,*p,*t; //Variables

    scanf("%[^\n]%*c%c%*c%c",b,&c,&d); //Scan input

    p=strchr(b,c);
    t=strchr(b,d); //Find occurrence of characters

    c==d         ||  //If both characters are the same
    !p           ||  //If no occurrence of first character found
    !t           ||  //If no occurrence of second character found
    strchr(p+1,c)||  //If two occurrence of first character found
    strchr(t+1,d) ?  //If two occurrence of second character found
    puts("\"null\"") //Print "null"
                  :  //else
    printf("\"%s\"",p<t?(*t=0,p+1):(*p=0,t+1)); //print the string
}

```

# Test it here
> 1 votes

# Answer
# Python 3, 172 bytes

```
x=input()
a=input()
a,b=a[0],a[2]
if(a!=b)&(x.count(b)==x.count(a)==1):
 if x.index(a)>x.index(b):q=a;a=b;b=q
 print('"'+x.split(a)[1].split(b)[0]+'"')
else:print('"null"')

```
> 1 votes

# Answer
# Javascript (*ES6*), 125 123 bytes

Idea stolen heavily from @edc65's solution.

```
[a,,b]=(p=prompt)(s=p()),[,c,d,e,,f]=s.split(RegExp('(['+(a+b).replace(/\W/g,'\\$&')+'])'))
p('"'+(!e||f||c==e?null:d)+'"')
```
> 1 votes

# Answer
## Python, 161 bytes

```
import re,sys
s,p=sys.stdin
m=re.match('[^%s]*([%s])([^%s]*)([%s])[^%s]*$'%((p[0]+p[2],)*5),s)
if m:g=m.group
print'"null"'if not m or g(1)==g(3)else'"'+g(2)+'"'

```

The solution mostly just uses a regular expression to extract the string. To accommodate that the letters could match in either direction, the start and end of the matched part allows either letter. Checking that the letters that actually matched to be different excludes the same letter being matched twice, as well as the two letters in the input being the same.

This is my first attempt at using Python for an answer here. So feedback on possible improvements is very welcome. I particularly have a feeling that there must be a way to make the condition in the print statement shorter.
> 1 votes

# Answer
# Python 3, 155 bytes

```
s,n,a,b=[input(),'null']+list(input())[::2];q,w=[s.find(a),s.find(b)];print('"'+{0>1:n,0<1:s[min(q,w)+1:max(q,w)],a==b:n}[s.count(a)==s.count(b)==1]+'"')

```

Try it online
> 1 votes

# Answer
# golflua, 132 bytes

```
L=I.r()I,J=I.r():m("(.) (.)")i=L:f(I)j=L:f(J)K,c=L:g(I,'')_,b=K:g(J,'')?i>j i,j=j,i$w((i==j|c+b!=2)&'"null"'|'"'..L:s(i+1,j-1)..'"')

```

Pretty ugly answer. The input bit is a bit rough (and requires two lines, first with the string & second with the slice characters ). Finding the locations of the flags is straight-forward, but just too long to compete with other answers. Output is pretty easy. An equivalent Lua program would be

```
Line1 = io.read()
Line2 = io.read()
I,J = Line2:match("(.) (.)")     -- boobs return the char flags
i = Line1:find(I)                -- find location of flags
j = Line1:find(J)
K,c = Line1:gsub(I,'')           -- replace flag w/ empty & store in K
_,b = K:gsub(J,'')               -- taking K ensures single flags fail
if i > j then i,j=j,i end        -- ensure we start low to high
if i==j or not (c+b == 2) then   -- if i & j are the same or not 2 counts, fail
   print('"null"')
else                             -- print the string otherwise
   print('"'..Line1:sub(i+1,j-1)..'"')
end

```
> 1 votes

# Answer
# Vyxal, 164 bitsv2, 20.5 bytes

```
"`(.*)`wYḂ"ṠẎf:₃[h|`¨β

```

Try it Online!

Bitstring:

```
00110000111000011110010000000100111011101000001101101000101001101101100110001100010100001110111101111111011010011000110000000101010010101011001110001001000110010001

```

Hello to all the people answering this as a result of me bumping it to the front page :p

## Explained

```
"`(.*)`wYḂ"ṠẎf:₃[h|`¨β
"                       # Pair the two characters into a list
 `(.*)`                 # Push the string "(.*)", representing a capturing group of any number of characters. The `()` is so that only the .* is returned in a regex match
       wY               # Create a list of [first char, ^, second char]
         Ḃ"             # And wrap it in a list with its reverse
           Ṡ            # Summate each list, giving two regexes: "<first char>(.*)<second char>", "<second char>(.*)<first char>"
            Ẏf          # Get all regex matches of both regexes and flatten into a single list
              :₃[       # If the length is 1 (i.e. there was only one match, meaning the characters aren't the same and there's a unique span):
                 h      #   Print the span
                  |`¨β  #   Otherwise, print "null"

```

Created with the help of Luminespire.
> 1 votes

# Answer
**APL(NARS), 50 chars**

```
{1 1≢↑+/⍵=⊂a←∪1↓1⌽⍺:'"null"'⋄1⌽'""',⍵[↑../⍸⍵∊a]∼a}

```

the use. For result not sure 100%

```
  '4 5' {1 1≢↑+/⍵=⊂a←∪1↓1⌽⍺:'"null"'⋄1⌽'""',⍵[↑../⍸⍵∊a]∼a} 'aifdji5ijj4'
"ijj"

```
> 1 votes

# Answer
# Perl, 65

```
#!perl -p0
$.*=s/\Q$1/
/g while s/ ?(.)\z//;/
(.*)
/;$_=$.-1?null:"\"$1\""

```

This requires there is no newline character at in the second line of the input.
> 0 votes

# Answer
# Kotlin, 238 bytes

```
"\""+v[0].let{s->v[1].let{val(a,b)=it.split("").drop(1).let{c->c[0] to c[2]};if(s.count{""+it==a}!=1||s.count{""+it==b}!=1||a==b)"null" else{val(c,d)= s.indexOf(a) to s.indexOf(b);s.substring((if(c<=d)c else d)+1,if(c<=d)d else c)}}}+"\""

```

Formatted version:

```
"\"" + v[0].let { s ->
    v[1].let {
        val (a, b) = it.split("")
            .drop(1)
            .let { c -> c[0] to c[2] } // get first and third char that we are looking fir
        if (s.count { "" + it == a } != 1 || s.count { "" + it == b } != 1 || a == b) { // check if there 0 or more times the character of the first or second char. also check if both are equal
            "null"
        } else {
            val (c, d) = s.indexOf(a) to s.indexOf(b) // fetch indices of thise two chars
            s.substring((if (c <= d) c else d) + 1, if (c <= d) d else c) // build a substring considering the reverse looking
        }
    }
} + "\""

```

Try it online!
> 0 votes

# Answer
# Scala 3, ~~192~~ 187 bytes

Saved 5 bytes thanks to @ceilingcat

---

Golfed version. Attempt This Online!

```
(s,c)=>{val(a,b)=(s.indexOf(c(0)),s.indexOf(c(2)));if(List(c(0),c(2)).forall(x=>s.count(_==x)==1)&a!=b&a*b> -1)"\""+(if (b<a)s.substring(b+1,a)else s.substring(a+1,b))+"\""else"\"null\""}

```

Ungolfed version. Attempt This Online!

```
object Main {
  def findSubstring(string: String, chars: String): String = {
    val a = string.indexOf(chars(0))
    val b = string.indexOf(chars(2))

    if (string.count(_ == chars(0)) == 1 && string.count(_ == chars(2)) == 1 && a != b && a * b > -1) {
      if (b < a) {
        "\"" + string.substring(b + 1, a) + "\""
      } else {
        "\"" + string.substring(a + 1, b) + "\""
      }
    } else {
      "\"null\""
    }
  }

  def main(args: Array[String]): Unit = {
    val string = scala.io.StdIn.readLine()
    val chars = scala.io.StdIn.readLine()
    println(findSubstring(string, chars))
  }
}

```
> 0 votes

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


title: Print a Block-Diagonal Matrix

text:
# Question
Title: Print a Block-Diagonal Matrix
Here is a simple, bite-sized (byte-sized?) code golf: given a non-empty list of positive integers less than 10, print a block-diagonal matrix, where the list specifies the size of the blocks, in order. The blocks must consist of positive integers less than 10. So if you're given as input

```
[5 1 1 2 3 1]

```

Your output could be, for instance,

```
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 0 0 0 1

```

or

```
1 2 3 4 5 0 0 0 0 0 0 0 0
6 7 8 9 1 0 0 0 0 0 0 0 0
2 3 4 5 6 0 0 0 0 0 0 0 0
7 8 9 1 2 0 0 0 0 0 0 0 0
3 4 5 6 7 0 0 0 0 0 0 0 0
0 0 0 0 0 8 0 0 0 0 0 0 0
0 0 0 0 0 0 9 0 0 0 0 0 0
0 0 0 0 0 0 0 1 2 0 0 0 0
0 0 0 0 0 0 0 3 4 0 0 0 0
0 0 0 0 0 0 0 0 0 5 6 7 0
0 0 0 0 0 0 0 0 0 8 9 1 0
0 0 0 0 0 0 0 0 0 2 3 4 0
0 0 0 0 0 0 0 0 0 0 0 0 5

```

or something like that. The elements in the matrix must be separated by (single) spaces, and the rows separated by (single) newlines. There must not be leading or trailing spaces on any lines. You may or may not print a trailing newline.

You may write a function or program, taking input via STDIN (or closest alternative), command-line argument or function argument, in any convenient string or list format (as long as it isn't preprocessed). However, the result must be printed to STDOUT (or closest alternative), as opposed to returned from a function, say.

You must not use any built-in functions designed to create block-diagonal matrices.

This is code golf, so the shortest submission (in bytes) wins.

# Leaderboards

I expect the array-based languages (like J and APL) to have the edge here, but I don't want that to discourage people from trying to do as well as they can in their language of choice. So here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. So why not try and grab a spot on the latter?

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

```
# Language Name, N bytes

```

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

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

```

```
function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=0,c=0,p=-1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);t++;c=p==o?c:t;i=i.replace("{{PLACE}}",c+".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);p=o;$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=45550;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script><link rel=stylesheet type=text/css href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id=answer-list><h2>Leaderboard</h2><table class=answer-list><thead><tr><td></td><td>Author<td>Language<td>Size<tbody id=answers></table></div><div id=language-list><h2>Winners by Language</h2><table class=language-list><thead><tr><td>Language<td>User<td>Score<tbody id=languages></table></div><table style=display:none><tbody id=answer-template><tr><td>{{PLACE}}</td><td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td>{{NAME}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table>
```

# Answer
> 20 votes
# J, 7 bytes

Thanks for FUZxxl for the 2-byte improvement.

Array based languages should be counted here in a different competition as they have a huge advantage. :)

```
   =/~@#<\

   (=/~@#<\) 3 1 1 2
1 1 1 0 0 0 0
1 1 1 0 0 0 0
1 1 1 0 0 0 0
0 0 0 1 0 0 0
0 0 0 0 1 0 0
0 0 0 0 0 1 1
0 0 0 0 0 1 1

```

Another 7-byte approach:

```
#]=@##\

```

Explanation for the old version `([:=/~]#<\)`:

The first step is generating `n` piece of similar things (e.g. numbers) for every list element `n`. These should be different from the other elements'. E.g. using the natural numbers `3 1 1 2` becomes `0 0 0 1 2 3 3`.

To save on bytes we use the boxed prefixes of the list:

```
   ]#<\ 3 1 1 2
┌─┬─┬─┬───┬─────┬───────┬───────┐
│3│3│3│3 1│3 1 1│3 1 1 2│3 1 1 2│
└─┴─┴─┴───┴─────┴───────┴───────┘

```

With the `=/~` verb we create a table of Descartes products of these boxed prefixes and each cell will be `1` if the two entries are equal `0` otherwise.

# Answer
> 11 votes
# APL, 10

```
∘.=⍨∆/⍋∆←⎕

```

Example:

```
      ∘.=⍨∆/⍋∆←⎕
⎕:
      5 1 1 2 3 1
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 0 0 0 1

```

Explanation:

* `∆←⎕`: read input, store in .
* `⍋∆`: find permutation that sorts  (this gives an unique value for each value in the input)
* `∆/`: for each of those unique values, repeat it `N` times, where `N` is the corresponding value in the input
* `∘.=⍨`: make a matrix comparing each value in that list to the other values.

# Answer
> 8 votes
# R, ~~69~~ 63

```
function(x)write(+outer(i<-rep(1:length(x),x),i,"=="),1,sum(x))

```

Test Case:

```
(function(x)write(+outer(i<-rep(1:length(x),x),i,"=="),1,sum(x)))(c(5,1,1,3,1))
1 1 1 1 1 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 0 1

```

The outer function does most of the work here, then its just a case of getting the output looking right - Thanks to @Vlo for his help with that

# Answer
> 6 votes
# Matlab, ~~60~~ 54 bytes

This would be Matlab's special field *IF* we could use builtin functions...

Thanks @sanchises for fixing the error I missed.

```
c=0;a=input('');for A=a;v=c+1:c+A;d(v,v)=1;c=c+A;end;d

```

# Answer
> 6 votes
# Python 3, ~~103~~ ~~97~~ ~~82~~ ~~78~~ 76 bytes

```
def P(L,n=0):k,*L=L;exec("print(*[0]*n+[1]*k+[0]*sum(L));"*k);L and P(L,n+k)

```

Using splat to take advantage of the space-separating nature of `print`, with a bit of recursion.

# Answer
> 6 votes
# Ruby, ~~86~~ ~~90~~ 83 bytes

My first golf ever!

```
->l{n=l.reduce :+;s=0;l.map{|x|x.times{puts ([0]*s+[1]*x+[0]*(n-x-s))*" "};s+=x}}

```

Receives an array with the integers, prints the expected result:

```
$ (->l{n=l.reduce :+;s=0;l.map{|x|x.times{puts ([0]*s+[1]*x+[0]*(n-x-s))*" "};s+=x}}).call([5, 1, 1, 2, 3, 1])
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 0 0 0 1

```

**Edit:**

Thanks to Martin Büttner for helping me shortening some things!

# Answer
> 6 votes
# Matlab, 53 bytes

Though it is only one char shorter than the other Matlab fragment, I figured the code is sufficiently different to warrant a new answer:

```
d=[];a=input('');for A=a;v=1:A;d(end+v,end+v)=1;end;d

```

The main trick is of course out of bounds indexing, but this is combined with using `end` as a variable to make it more compact.

# Answer
> 6 votes
# APL (Dyalog Extended), 6 bytes

```
∘.=⍨⍸⎕

```

Try it online!

A full program that takes the input vector from stdin and prints the matrix.

---

If a function returning a matrix were allowed:

# APL (Dyalog Extended), 5 bytes

```
∘.=⍨⍸

```

Try it online!

APL wins back against J and K with the extended domain for .

### How it works

```
∘.=⍨⍸
    ⍸  ⍝ Where; convert to an array that,
       ⍝   for each element n at index i, has n copies of i
∘.=⍨   ⍝ Outer product by element-wise equality on self

```

# Answer
> 4 votes
# CJam, 21

```
q~{T):Ta*~}%_f{f=S*N}

```

Try it at http://cjam.aditsu.net/

**Explanation:**

```
q~          read and evaluate the input array
{…}%        transform each number using the block
    T):T    increment T (initially 0)
    a*      wrap T in an array and repeat it <number> times
    ~       dump the repeated numbers so they end up in a flat array
_           duplicate the array
f{…}        for each array item and the array
    f=      compare the current item with each item, resulting in an array of 1 and 0
    S*      join with spaces
    N       add a newline

```

# Answer
> 4 votes
# Python 3, 79

```
def f(l,s=0):
 for x in l:r=[0]*sum(l);r[s:s+x]=[1]*x;s+=x;exec("print(*r);"*x)

```

Tracks the leftmost index of the block as `s` and makes the `x` entries after it be `1`, where `x` is the current block size. This row is then printed `x` times. Python 3 is needed to do `print(*r)`.

# Answer
> 4 votes
# Haskell, 118 116 bytes

```
(#)=replicate
f i=putStr$[e#(unwords$sum h#"0"++e#"1"++sum t#"0")|(h,e:t)<-map(`splitAt`i)[0..length i-1]]>>=unlines

```

Usage: `f [2,1,1,3]`

Output:

```
1 1 0 0 0 0 0
1 1 0 0 0 0 0
0 0 1 0 0 0 0
0 0 0 1 0 0 0
0 0 0 0 1 1 1
0 0 0 0 1 1 1
0 0 0 0 1 1 1

```

How it works:

```
[0..length i-1]           for each index n of the input list i
(h,e:t)<-map(`splitAt`i)  split i at n and
                            let e be the element at index n
                            let h be the list of elements to the left of e
                            let t be the list of elements to the right of e
                          foreach triple h, e, t make a list of
sum h # "0" ++              sh copies of "0" (sh = the sum of the elements of h) followed by
e # "1" ++                  e copies of "1" followed by
sum t # "0"                 st copies of "0" (st = the sum of the elements of t)
unwords                   join those list elements with spaces inbetween
e #                       make e copies
>>=unlines                join those lists with newlines inbetween
putStr                    print

```

# Answer
> 4 votes
# K (ngn/k), 12 bytes

```
5:'=/:/2#,&:

```

Try it online!

`5:` is "debug print". Since the default formatting of a matrix is not what is wanted here, it is printed row-wise via `'`.

---

if function returning a matrix (list of lists) were allowed:

# K (ngn/k), 9 bytes

```
=/:/2#,&:

```

Try it online!

Took almost two years to golf a byte from the previous ngn/k answer :P

The algorithm itself is the same. The problem with making something a train is that you're allowed to reference the input only once. This code solves the problem by making `=/:` reduce over the two copies of the vector `&x`.

# Answer
> 3 votes
# Pyth, ~~23~~ 21 bytes

GitHub repository for Pyth

```
Ju+G*]GHQYFNJjdmsqdNJ

```

Input is a list of integers, like `[3, 1, 1, 2]`. Try it online: Pyth Compiler/Executor

Uses a quite similar idea as randomra's J code. The first part of the code `Ju+G*]GHQY` generates `n` parts of similar things. For the example input `[3, 1, 1, 2]` the result looks like this:

```
[
 [],
 [],
 [],
 [[], [], []],
 [[], [], [], [[], [], []]],
 [[], [], [], [[], [], []], [[], [], [], [[], [], []]]],
 [[], [], [], [[], [], []], [[], [], [], [[], [], []]]]
]

```

First three identical elements, than one element , then one element again and at the end two identical elements.

```
Ju+G*]GHQY
 u      QY  reduce the input Q, start with empty list G=[]
            for each H in input, replace the value of G by:
  +G*]GH       G+[G]*H
J           store the result in J

```

The second part of the code is comparing the elements of the Cartesian product and printing it.

```
FNJjdmsqdNJ
FNJ          for N in J:
     m    J     map each element d of J to
       qdN          the boolean value of d == N
      s             and convert it to an integer (0 = False, 1 = True)
   jd           print the resulting list seperated by d (=space)

```

# Answer
> 3 votes
# C++ , 294 bytes

*Compiler used - GCC 4.9.2*

```
#include<bits/stdc++.h>
using namespace std;
#define F(a,b) for(a=0;a<b;a++)
#define V vector<int>
int n,i,j,s,o;
main(){V v;while(cin>>n)v.push_back(n),s+=n;vector<V> m(s,V(s,0));F(i,v.size()){F(j,v[i])F(n,v[i])m[j+o][n+o]=1;o+=v[i];}F(j,s){F(n,s)cout<<m[j][n]<<((n==s-1)?"":" ");cout<<"\n";}}

```

Explanation -:

```
#include<bits/stdc++.h>
using namespace std;
#define F(a,b) for(a=0;a<b;a++)
#define V vector<int>
int n, i, j, s, o;
/*
 n = Used to take inputs, and as an iterator after that
 i, j = Iterators
 s = sum of all the inputs
 o = offset ( used to find the location of the starting cell of the next matrix of 1's )
*/

main()
{
    V v;
    while ( cin >> n )  // Take input
    {
        v.push_back( n ), s += n;
    }

    vector<V> m( s, V( s, 0 ) ); // m is a matrix of size (s*s) with all elements initialized to 0
    F( i, v.size() )
    {
        F( j, v[i] )F( n, v[i] )m[j + o][n + o] = 1; // Assign 1 to the required cells
        o += v[i]; // Add the value of the current element to the offset
    }

    F( j, s )  // Output the matrix
    {
        F( n, s )cout << m[j][n] << ( ( n == s - 1 ) ? "" : " " ); // Prevent any trailing whitespace
        cout << "\n";
    }
}

```

# Answer
> 3 votes
# K, 30 bytes

```
{"i"$,/x#',:',/'g=\:\:x#'g:<x}

```

Basically stole marinus's answer

```
k){"i"$,/x#',:',/' g=\:\:x#'g:<x}5 1 1 2 3 1
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 0 0 0 1

```

# Answer
> 2 votes
# Python 2, ~~163~~ 114 bytes

gnibbler golfed this a bunch.

```
h=input()
r=range
l=len(h)
for i in r(l):
 for k in r(h[i]):print" ".join("01"[i==j]for j in r(l)for x in r(h[j]))

```

# Answer
> 2 votes
# Java, 163

```
a->{int n=a.stream().mapToInt(x->x).sum(),t=0,j,k;for(int i:a){for(j=0;j++<i;System.out.println("\b"))for(k=0;k<n;)System.out.print(k>=t&k++<t+i?"1 ":"0 ");t+=i;}}

```

A consumer which accepts a list of integers.

Readable version, with boilerplate code:

```
java.util.function.Consumer<java.util.List<Integer>> c = a -> {
    int n = a.stream().mapToInt(x -> x).sum(), t = 0, j, k;
    for (int i : a) {
        for (j = 0; j++ < i; System.out.println("\b")) {
            for (k = 0; k < n;) {
                System.out.print(k >= t & k++ < t + i ? "1 " : "0 ");
            }
        }
        t += i;
    }
};

```

Invoke using:

```
List list = Arrays.asList(5, 1, 1, 2, 3, 1);
c.accept(list);

```

# Answer
> 2 votes
# JavaScript (ES6), 103 ~~107~~

103 bytes as an anonymous function, not counting `F=` (but you need this to test it)

```
F=l=>alert(l.map((n,y)=>(l.map((n,x)=>Array(n).fill(x==y|0))+'\n').repeat(n))
.join('').replace(/,/g,' '))

```

**Test** In Firefox/FireBug console

```
F([5,1,1,2,3,1])

```

*Output*

```
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 0 1 1 0 0 0 0
0 0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 0 0 0 1

```

# Answer
> 2 votes
# Python 3, 74

```
def f(a,p=0):n=a.pop(0);exec("print(*'0'*p+'1'*n+'0'*sum(a));"*n);f(a,p+n)

```

# Answer
> 2 votes
# Octave, ~~49~~ 41 bytes

```
@(a)(c=repelems(b=1:length(a),[b;a]))'==c

```

# Answer
> 1 votes
# Pyth, ~~31~~ 30

```
FbQVbjd++*]0Z*b]b*]0--sQbZ)~Zb

```

A pretty naive program, takes the input on stdin. This can probably be golfed more ;)

Thanks @Jakube for pointing out a wasted char

Try it here

# Answer
> 1 votes
# R, ~~117~~ ~~144~~ ~~137~~ ~~133~~ ~~129~~ 123 bytes

Reasonably verbose at the moment. Should be able to shave a few more out. Gained a number of bytes formatting it correctly, but saved some swapping out the matrix for an array.

Thanks to Alex for the tip on the replacing sep with s and removing the function name.

Dropped the array completely and used a series of reps to build each line.

Although soundly beaten by Miff, his solution made me realise I could drop the s=' ' altogether.

```
function(i){s=sum(i);i=cumsum(i);b=0;for(n in 1:s){d=i[i>=n][1];cat(c(rep(0,b),rep(1,d-b),rep(0,s-d)),fill=T);if(d==n)b=d}}

```

And the test

```
> (function(i){s=sum(i);i=cumsum(i);b=0;for(n in 1:s){d=i[i>=n][1];cat(c(rep(0,b),rep(1,d-b),rep(0,s-d)),fill=T,s=' ');if(d==n)b=d}})(c(5,1,1,3,1))
1 1 1 1 1 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0
1 1 1 1 1 0 0 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 1 1 1 0
0 0 0 0 0 0 0 0 0 0 1
>

```

# Answer
> 1 votes
# Perl, 69

```
#!perl -na
$j=s/./0 x$&/ger;print+($j|$i.1x$_)=~s/\B/ /gr x($i.=0 x$_,$_)for@F

```

Uses standard input:

```
$ perl a.pl <<<"1 2 3"
1 0 0 0 0 0
0 1 1 0 0 0
0 1 1 0 0 0
0 0 0 1 1 1
0 0 0 1 1 1
0 0 0 1 1 1

```

# Answer
> 1 votes
## Batch - 226 Bytes

```
@echo off&setLocal enableDelayedExpansion&set c=0&for %%a in (%*)do set/ac+=1&for /l %%b in (1,1,%%a)do (set l=&set d=0&for %%c in (%*)do (set/ad+=1&for /l %%d in (1,1,%%c)do if !d!==!c! (set l=!l!1)else set l=!l!0)
echo !l!)

```

Takes input from stdin (`C:\>script.bat 5 1 1 2 3 1`) and echo's output. Unfortunately I couldn't get that last echo on the same line, otherwise I could probably call the whole line within `cmd/von/c` to avoid having to enable delayed expansion the long way.

Nice and neat - nothing but grunt work:

```
@echo off
setLocal enableDelayedExpansion
set c=0
for %%a in (%*) do (
    set /a c+=1
    for /l %%b in (1,1,%%a) do (
        set l=
        set d=0
        for %%c in (%*) do (
            set /a d+=1
            for /l %%d in (1,1,%%c) do if !d!==!c! (set l=!l!1) else set l=!l!0
        )
        echo !l!
    )
)

```

# Answer
> 1 votes
# Haskell, 124

```
(%)=replicate
d l=fst$foldr(\x(m,n)->(m>>mapM_(\_->putStrLn$unwords$n%"0"++x%"1"++(sum l-n-x)%"0")[1..x],n+x))(return(),0)l

```

Produces output by combining IO actions through `mapM_` and `foldr`. The function `d` should be given a list of ints.

# Answer
> 1 votes
# Jelly, 7 bytes

```
ĖŒṙ⁼þ`G

```

Try it online!

Same approach as the J answer.

```
      G    Grid format
   ⁼þ      a table of whether or not pairs of elements are equal, from
 Œṙ        the run-length decoded
Ė          enumeration of the input,
     `     compared with itself.

```

# Answer
> 1 votes
# K (ngn/k), 14 bytes:

`{5:'x=\:x:&x;}`

fixed. now prints to stdout

# Answer
> 1 votes
# Julia 1.6, 68 bytes

```
>(L,c=0)=((x,l...)=L;print(("0 "^c*"1 "^x*"0 "^sum(l)*"
")^x);l>c+x)

```

Attempt This Online!

port of Sp3000's answer

needs julia 1.6 for `x,l...=L`

output as a matrix would save a lot of bytes but printing it as expected uses more bytes:

`!L=(l=[(a=1;L.|>i->(a+=1)ones(i))...;]).==l'` (44bytes)

# Answer
> 1 votes
# Vyxal, 7 bytes

```
żẋf:v=⁋

```

Try it Online! -1 byte thanks to lyxal.

Same approach as a lot of the array-language answers

```
 ẋ      # Repeat elements of
ż       # [1...len(input)
 ẋ      # By numbers in the input
  f     # Flatten
   :v=  # Table by equality
      ⁋ # Format as grid

```

# Answer
> 1 votes
# Uiua, 20 bytes

4 bytes for constructing the array; 16 bytes for formatting the output :/

```
≡(&p↘1/⊂)∵⊂@ +@0⊞=.⊚

```

Try it online!

## Explanation

```
                ⊞=.⊚ # construct the table in the same way as other array languages
             +@0     # convert numbers to characters
      /⊂ ∵⊂@         # interleave spaces (including leading space)
    ↘1               # remove said leading space
≡(&p    )            # and print each line

```

# Answer
> 0 votes
## STATA, 155 bytes

```
di _r(a)
forv x=1/wordcount($a){
gl b=word($a,`x')
gl c=_N+1
set ob _N+$b
forv y=$c/_N{
g d`y'=_n>=$c
}
}
forv z=1/_N{
replace d`z'=0 if d`z'>1
}
l,noo noh

```

# Answer
> 0 votes
# TI-Basic (TI-83), 65 bytes

```
Ans→A
For(X,1,sum(Ans
cumSum(ʟA
Ans(C+1
For(Y,1,sum(ʟA
Output(X,2Y,Y>B and Y≤Ans
End
If X=Ans
IS>(C,0
End
Ans→B
End

```

It's always a good day when I get to use the `IS>(` command. Needs `B` and `C` to be uninitialized (or set to zero)

# Answer
> 0 votes
# 05AB1E, 8 bytes

```
Å1ƶ˜DδQ»

```

Outputs with `1`s like the first example.

Try it online.

`Å1ƶ˜` could alternatively be `āsÅΓ` for the same byte-count:
Try it online.

**Explanation:**

```
Å1       # Convert each value in the (implicit) input-list to a list of that many 1s
  ƶ      # Multiply each inner list by its 1-based index, so all become unique
   ˜     # Flatten the list of lists
    DδQ  # Create an equality-table:
    D    #  Duplicate the list
     δ   #  Pop both lists, and apply double-vectorized:
      Q  #  Equality check
       » # Join each inner list by spaces, and then each string by newlines
         # (after which this is output implicitly as result)

ā        # Push a list in the range [1, (implicit) input-length]
 s       # Swap so the input-list is at the top of the stack
  ÅΓ     # Pop both, and run-length decode it

```

---
Tags: code-golf, array
---


title: IP address or not?

text:
# Question
Title: IP address or not?
Your network scanning tool is annoyingly picky about input, and immediately crashes if you feed it an IPv4 address that contains improper characters or isn't properly formatted.

> An IPv4 address is a **32-bit numeric address** written as four numbers separated by periods. Each number can be **zero to 255**.

We need to write a tool to *pre-validate* the input to avoid those crashes, and our specific tool is picky: A *valid* format will look like `a.b.c.d` where a, b, c and d:

* Can be a `0` or a natural number with **no leading zeros**.
* Should be between 0 - 255 (inclusive).
* Should **not** contain special symbols like `+`, `-`, `,`, and others.
* Should be decimal (base `10`)

**Input**: A string

**Output**: Truthy or Falsey value (arbitrary values also accepted)

**Test Cases**:

```
Input            |  Output  |  Reason
                 |          |
- 1.160.10.240   |  true    |
- 192.001.32.47  |  false   |  (leading zeros present)
- 1.2.3.         |  false   |  (only three digits)
- 1.2.3          |  false   |  (only three digits)
- 0.00.10.255    |  false   |  (leading zeros present)
- 1.2.$.4        |  false   |  (only three digits and a special symbol present)
- 255.160.0.34   |  true    |
- .1.1.1         |  false   |  (only three digits)
- 1..1.1.1       |  false   |  (more than three periods)
- 1.1.1.-0       |  false   |  (special symbol present)
- .1.1.+1        |  false   |  (special symbol present)
- 1 1 1 1        |  false   |  (no periods)
- 1              |  false   |  (only one digit)
- 10.300.4.0     |  false   |  (value over 255)
- 10.4F.10.99    |  false   |  (invalid characters)
- fruit loops    |  false   |  (umm...)
- 1.2.3.4.5      |  false   |  (too many periods/numbers)
- 0.0.0.0        |  true    |
- 0.0 0.0.       |  false   |  (periods misplaced)
- 1.23..4        |  false   |  (a typo of 1.2.3.4)
- 1:1:1:1:1:1:1:1|  false   |  (an IPv6 address, not IPv4)

```

This is , so fewest bytes will win!

> **Note for the users** \- if anyone wants to add some test-cases, they're welcomed (by suggesting an edit).

# Answer
> 25 votes
# X86\_64 machine code: ~~18~~ 16 bytes

Edit: This answer doesn't quite work, as

1. I am using `inet_pton` from the standard C libraries, which means I need the extern. I didn't include the extern in my byte count though.
2. I used the red zone as a result for the actual address, but called a function which also could've used the red zone. It fortunately doesn't on my machine, but some odd standard library build might use it which could cause undefined behavior.

And yeah, the whole thing is pretty much being done by an already written function

Anyway, this is what I got: `48 89 fe 6a 02 5f 48 8d 54 24 80 e9 00 00 00 00`

Assembly:

```
section .text
    extern inet_pton
    global ipIsValid

ipIsValid:
    mov rsi, rdi
    ;mov rdi, 2 ; change to 10 for ipv6
    push 2
    pop rdi ; thank you peter
    lea rdx, [rsp - 128]
    jmp inet_pton

```

# Explanation:

Take a look at `inet_pton(3)`. It takes a string IP address and puts it in a buffer you can use with `struct sockaddr`. It takes 3 arguments: the address family (`AF_INET` (ipv4), 2, or `AF_INET6` (ipv6), 10), the ip address's string, and a pointer to the output. It returns 1 on success, 0 for an invalid address, or -1 for when the address family is neither `AF_INET` or `AF_INET6` (which will never occur because I'm passing a constant to it).

So I simply move the string to the register for the second argument, set the first register to 2, and set the third register to the red zone (128 bytes below the stack pointer) since I don't care about the result. Then I can simply `jmp` to `inet_pton` and let that return straight to the caller!

I spun up this quick test program to test your cases:

```
#include <stdio.h>
#include <arpa/inet.h>
#include <netinet/ip.h>

extern int ipIsValid(char *);

int main(){
    char *addresses[] = {
        "1.160.10.240",
        "192.001.32.47",
        "1.2.3.",
        "1.2.3",
        "0.00.10.255",
        "1.2.$.4",
        "255.160.0.34",
        ".1.1.1",
        "1..1.1.1",
        "1.1.1.-0",
        ".1.1.+1",
        "1 1 1 1",
        "1",
        "10.300.4.0",
        "10.4F.10.99",
        "fruit loops",
        "1.2.3.4.5",
        NULL
    };

    for(size_t i = 0; addresses[i] != NULL; ++i){
        printf("Address %s:\t%s\n", addresses[i],
            ipIsValid(addresses[i]) ? "true" : "false");
    }
    return 0;
}

```

Assemble with `nasm -felf64 assembly.asm`, compile with `gcc -no-pie test.c assembly.o`, and you'll get:

```
Address 1.160.10.240:   true
Address 192.001.32.47:  false
Address 1.2.3.: false
Address 1.2.3:  false
Address 0.00.10.255:    false
Address 1.2.$.4:    false
Address 255.160.0.34:   true
Address .1.1.1: false
Address 1..1.1.1:   false
Address 1.1.1.-0:   false
Address .1.1.+1:    false
Address 1 1 1 1:    false
Address 1:  false
Address 10.300.4.0: false
Address 10.4F.10.99:    false
Address fruit loops:    false
Address 1.2.3.4.5:  false

```

I could make this much smaller if the caller was supposed to pass `AF_INET` or `AF_INET6` to the function

# Answer
> 13 votes
# Java (JDK), 63 bytes

```
s->("."+s).matches("(\\.(25[0-5]|(2[0-4]|1\\d|[1-9])?\\d)){4}")

```

Try it online!

## Credits

# Answer
> 12 votes
# JavaScript (Node.js), 43 bytes

```
x=>x.split`.`.map(t=>[t&255]==t&&[])==`,,,`

```

Try it online!

# JavaScript (Node.js), 46 bytes

```
x=>x.split`.`.every(t=>k--&&[t&255]==t,k=4)*!k

```

Try it online!

used Arnauld's part

# JavaScript (Node.js), ~~54~~ ~~53~~ 51 bytes

```
x=>x.split`.`.every(t=>k--*0+t<256&[~~t]==t,k=4)*!k

```

Try it online!

-2B for `0+t<256`, -1B from Patrick Stephansen, +1B to avoid input `1.1.1.1e-80`

RegExp solution ~~58~~54 bytes

```
s=>/^((2(?!5?[6-9])|1|(?!0\d))\d\d?\.?\b){4}$/.test(s)

```

Thank Deadcode for 3 bytes

# Answer
> 11 votes
# PHP, 39 36 bytes

```
<?=+!!filter_var($argv[1],275,5**9);

```

Try it online!

275 resembles the constant `FILTER_VALIDATE_IP`

5\**9 is being used instead of the constant `FILTER_FLAG_IPV4`. This is sufficient, because `5**9 & FILTER_FLAG_IPV4` is truthy, which is exactly what PHP does in the background, as Benoit Esnard pointed out.

Here, `filter_var` returns the first argument, if it's a valid IPv4 address, or false if it's not. With `+!!`, we produce the output required by the challenge.

# Answer
> 11 votes
## PHP, 36 Bytes

```
echo(ip2long($argv[1])===false?0:1);

```

`ip2long` is a well-known built-in function.

# Answer
> 10 votes
# Perl 6, ~~22~~ ~~21~~ 20 bytes

*-1 byte thanks to Phil H.*

```
{?/^@(^256)**4%\.$/}

```

Try it online!

### Explanation

```
{                  }  # Anonymous Block
  /               /   # Regex match
   ^             $    # Anchor to start/end
    @(    )           # Interpolate
      ^256            #   range 0..255,
                      #   effectively like (0|1|2|...|255)
           **4        # Repeated four times
              %\.     # Separated by dot
 ?                    # Convert match result to Bool

```

# Answer
> 9 votes
# 05AB1E, ~~26~~ ~~24~~ ~~23~~ ~~22~~ ~~23~~ 17 bytes

```
'.¡DgsAì₅ÝAìÃg4)Ë

```

-1 byte thanks to *@Emigna*.
+1 byte for bugfixing test case `1.1.1.1E1` incorrectly returning a truthy result.

Try it online or verify all test cases.

**Explanation:**

```
'.¡          '# Split the (implicit) input-string on "."
   D          # Duplicate this list
    g         # Pop and push the length of this copy
   s          # Swap so the list is at the top again
    Aì        # Prepend the alphabet before each item
      ₅Ý      # Push a list in the range [0,255]
        Aì    # Prepend the alphabet before each integer here as well
          Ã   # Only keep those items from the first list
           g  # Pop and push its length as well
   4          # Push a 4
    )         # Wrap all three values on the stack into a list
     Ë        # Check that all three are the same (aka all three are 4s)
              # (after which the result is output implicitly)

```

Prepending the alphabet is necessary, because in 05AB1E, `"0"`, `"00"`, `"0e0"`, `"5E0"`, `"-0"` etc. are all the same 'integer' `0`.

# Answer
> 6 votes
# PowerShell, ~~59~~ ~~51~~ 49 bytes

*-8 bytes, thanks @AdmBorkBork*

*-2 bytes, `true` or `false` allowed by author*

```
try{"$args"-eq[IPAddress]::Parse($args)}catch{!1}

```

Test script:

```
$f = {

try{"$args"-eq[IPAddress]::Parse($args)}catch{!1}

}

@(
    ,("1.160.10.240" , $true)
    ,("192.001.32.47" , $false)
    ,("1.2.3." , $false)
    ,("1.2.3" , $false)
    ,("0.00.10.255" , $false)
    ,("192.168.1.1" , $true)
    ,("1.2.$.4" , $false)
    ,("255.160.0.34" , $true)
    ,(".1.1.1" , $false)
    ,("1..1.1.1" , $false)
    ,("1.1.1.-0" , $false)
    ,("1.1.1.+1" , $false)
    ,("1 1 1 1" , $false)
    ,("1"            ,$false)
    ,("10.300.4.0"   ,$false)
    ,("10.4F.10.99"  ,$false)
    ,("fruit loops"  ,$false)
    ,("1.2.3.4.5"    ,$false)

) | % {
    $s,$expected = $_
    $result = &$f $s
    "$($result-eq$expected): $result : $s"
}

```

Output:

```
True: True : 1.160.10.240
True: False : 192.001.32.47
True: False : 1.2.3.
True: False : 1.2.3
True: False : 0.00.10.255
True: True : 192.168.1.1
True: False : 1.2.$.4
True: True : 255.160.0.34
True: False : .1.1.1
True: False : 1..1.1.1
True: False : 1.1.1.-0
True: False : 1.1.1.+1
True: False : 1 1 1 1
True: False : 1
True: False : 10.300.4.0
True: False : 10.4F.10.99
True: False : fruit loops
True: False : 1.2.3.4.5

```

Explanation:

The script tries to parse an argument string, to construct a .NET object, IPAddress.

* return `$true` if `object` created and the argument string is equal to a string representation of the `object` (normalized address by `object.toString()`)
* return `$false` otherwise

## PowerShell, ~~59~~ ~~56~~ 54 bytes, 'don't use a .NET lib' alternative

*-3 bytes, `true` or `false` allowed by author*

*-2 bytes, thanks to @Deadcode for the cool regexp.*

```
".$args"-match'^(\.(2(?!5?[6-9])|1|(?!0\B))\d\d?){4}$'

```

Try it online!

Thanks @Olivier Grégoire for the original regular expression.

# Answer
> 6 votes
# Python 3: ~~81~~ ~~78~~ ~~70~~ ~~69~~ 66 bytes

```
['%d.%d.%d.%d'%(*x.to_bytes(4,'big'),)for x in range(16**8)].count

```

Loop over all possible IPv4 addresses, get the string representation and compare it to the input. It uh... takes a while to run.

EDIT: Removed 3 bytes by switching from full program to anonymous function.

EDIT2: Removed 8 bytes with help from xnor

EDIT3: Removed 1 byte by using an unpacked map instead of list comprehension

EDIT4: Removed 3 bytes by using list comprehension instead of the `ipaddress` module

# Answer
> 5 votes
# PHP 7+, ~~37~~ ~~35~~ 32 bytes

This uses the builtin function `filter_var`, to validate that it is an IPv4 address.

For it to work, you need to pass the key `i` over a GET request.

```
<?=filter_var($_GET[i],275,5**9);

```

Will output nothing (for a `falsy` result) or the IP (for a `truthy` result), depending on the result.

You can try this on: ~~http://sandbox.onlinephpfunctions.com/code/639c22281ea3ba753cf7431281486d8e6e66f68e~~ http://sandbox.onlinephpfunctions.com/code/ff6aaeb2b2d0e0ac43f48125de0549320bc071b4

---

This uses the following values directly:

* 275 = FILTER\_VALIDATE\_IP
* ~~1\<\<20 = 1048576 = FILTER\_FLAG\_IPV4~~
* 5\**9 = 1953125 (which has the required bit as "1", for 1048576)

Thank you to Benoit Esnard for this tip that saved me 1 byte!

Thank you to Titus for reminding me of the changes to the challenge.

---

I've looked into using the function `ip2long`, but it works with non-complete IP addresses.

Non-complete IPv4 addresses are considered invalid in this challenge.

If they were allowed, this would be the final code (only for PHP 5.2.10):

```
<?=ip2long($_GET[i]);

```

Currently, it isn't explicit in the documentation that this will stop working (when passed an incomplete ip) with newer PHP versions.

After testing, confirmed that that was the case.

Thanks to nwellnhof for the tip!

# Answer
> 5 votes
# C (gcc) / POSIX, 26 bytes

```
f(s){s=inet_pton(2,s,&s);}

```

Try it online!

Works as 64-bit code on TIO but probably requires that `sizeof(int) == sizeof(char*)` on other platforms.

# Answer
> 5 votes
# C# (Visual C# Interactive Compiler), ~~84~~ ~~79~~ 65 bytes

```
s=>s.Split('.').Sum(t=>byte.TryParse(t,out var b)&t==b+""?1:5)==4

```

Try it online!

-5 and -14 bytes saved thanks to @dana!

~~\# C# (Visual C# Interactive Compiler), 61 bytes~~

~~```
s=>s.Count(c=>c==46)==3&IPAddress.TryParse(s,out IPAddress i)

```
Try it online!
This is a work in progress. The code use `System.Net` (+17 bytes if you count it). if you wonder why I count and parse:
The limitation with IPAddress.TryParse method is that it verifies if a string could be converted to IP address, thus if it is supplied with a string value like "5", it consider it as "0.0.0.5".
~~

~~source~~

As @milk said in comment, it will indeed fail on leading zeroes. So, the 61 bytes one is not working.

# Answer
> 4 votes
# Python 2, ~~85 82~~ 81 bytes

-1 byte thanks to Kevin Cruijssen

```
from ipaddress import*
I=input()
try:r=I==str(IPv4Address(I))
except:r=0
print~~r

```

Try it online!

113 byte answer is deleted as it fails for `1.1.1.1e-80`

# Answer
> 4 votes
# Japt, ~~17~~ 15 bytes

```
q.
Ê¶4«Uk#ÿòs)Ê

```

Try it or run all test cases or verify additional test cases from challenge comments

---

## Explanation

We split to an array on `.`, check that the length of that array is equal to `4` AND that the length when all elements in the range `["0","255"]` are removed from it is falsey (`0`).

```
                 :Implicit input of string U
q.               :Split on "."
\n               :Reassign resulting array to U
Ê                :Length of U
 ¶4              :Equals 4?
   «             :&&!
    Uk           :Remove from U
      #ÿ         :  255
        ò        :  Range [0,255]
         s       :  Convert each to a string
          )      :End removal
           Ê     :Length of resulting array

```

# Answer
> 4 votes
# ECMAScript pure regex, 41 bytes

`^((2(?!5?[6-9])|1|(?!0\B))\d\d?\.?\b){4}$`

Try it online!
Try it on regex101

I think the logic in this regex speaks for itself, so I will merely pretty-print but not comment it:

```
^
(
    (
        2(?!5?[6-9])
    |
        1
    |
        (?!0\B)
    )
    \d\d?
    \.?\b
){4}
$

```

This can be used to shave 2 bytes off the following other answers:

Some alternative 41 byte versions:

`^((2(?!5?[6-9])|1|(?!0\d))\d\d?\.?\b){4}$`
`^(((2(?!5?[6-9])|1|(?!0))\d)?\d\.?\b){4}$`
`^(((2(?!5?[6-9])|1)\d|[1-9]?)\d\.?\b){4}$`

Here is an alternative version that allows leading zeros, but does so consistently (octets may be represented by a maximum of 3 decimal digits):

`^((2(?!5?[6-9])|1|0?)\d\d?\.?\b){4}$`

Or allow any number of leading zeros:

`^(0*(2(?!5?[6-9])|1?)\d\d?\.?\b){4}$`

Or if allowed to have undefined behavior regarding leading zeros (as it so happens, a leading zero is only allowed only in 2-digit octets):

`^((2(?!5?[6-9])|1?)\d\d?\.?\b){4}$`

# Answer
> 3 votes
# sfk, 176 bytes

* was originally Bash + SFK but TIO has since added a proper SFK wrapper

```
xex -i "_[lstart][1.3 digits].[1.3 digits].[1.3 digits].[1.3 digits][lend]_[part2]\n[part4]\n[part6]\n[part8]_" +xed _[lstart]0[digit]_999_ +hex +linelen +filt -+1 -+2 +linelen

```

Try it online!

# Answer
> 3 votes
# Mathematica, ~~39~~ 31 bytes

Original version:

```
¬FailureQ[Interpreter["IPAddress"][#]]&

```

Modified version (thanks to Misha Lavrov)

```
 AtomQ@*Interpreter["IPAddress"]

```

which returns `True` if the input is a valid IP address (try it).

In case you insist on getting `1` and `0` instead, then an additional 7 bytes would be necessary:

```
Boole/@AtomQ@*Interpreter["IPAddress"]

```

# Answer
> 3 votes
# Bash, 15 bytes

```
ipcalc -c `cat`

```

Try it online!

Outputs exit code 0 for truthy, 1 for falsy.

# Answer
> 3 votes
# Python 2, ~~93~~ ~~89~~ ~~67~~ 53 bytes

```
[i==`int(i)&255`for i in input().split('.')]!=[1]*4>_

```

Try it online!

Thanks to Dennis for shaving *another* 14 bytes on the internal comparisons and exit code.

Special thanks to Jonathan Allan for shaving 22 bytes & a logic fix! Pesky try/except begone!

Taking properly formatted strings instead of raw bytes shaves off 4 bytes, thanks Jo King.

# Answer
> 3 votes
# ~~Python3~~ Bash\* 60

\*Also other shells. Any one for which the truthy/falsy test passes on a program exit code

```
read I
python3 -c "from ipaddress import*;IPv4Address('$I')"

```

## Explanation

The trouble with a pure Python solutions is that a program crashing is considered indeterminate. We could use a "lot" of code to convert an exception into a proper truthy/fasly value. However, at some point the Python interpreter handles this uncaught exception and returns a non-zero exit code. For the low-low cost of changing languages to your favourite Unix shell, we can save quite a bit of code!

Of course, this is vulnerable to injection attacks... Inputs such as `1.1.1.1'); print('Doing Something Evil` are an unmitigated threat!

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

Returns a Boolean value.

```
s=>[0,1,2,3].map(i=>s.split`.`[i]&255).join`.`==s

```

Try it online!

# Answer
> 2 votes
# Red, 106 bytes

```
func[s][if error? try[t: load s][return off]if 4 <> length? t[return off]s =
form as-ipv4 t/1 t/2 t/3 t/4]

```

Try it online!

Returnd `true` or `false`

## Explanation:

```
f: func [ s ] [
    if error? try [                  ; checks if the execution of the next block result in an error
        t: load s                    ; loading a string separated by '.' gives a tuple
    ] [                              ; each part of which must be in the range 0..255
        return off                   ; if there's an error, return 'false'
    ]
    if 4 <> length? t [              ; if the tuple doesn't have exactly 4 parts
        return off                   ; return 'false'
    ]
    s = form as-ipv4 t/1 t/2 t/3 t/4 ; is the input equal to its parts converted to an IP adress
]

```

# Answer
> 2 votes
# Charcoal, ~~45~~ 21 bytes

```
Ｉ∧⁼№θ.³¬Φ⪪θ.¬№Ｅ²⁵⁶Ｉλι

```

Try it online! Link is to verbose version of code. Edit: Saved 24 bytes by porting @Shaggy's Japt answer. Explanation:

```
    θ                   Input string
   №                    Count occurrences of
     .                  Literal `.`
  ⁼                     Equal to
      ³                 Literal 3
 ∧                      Logical And
       ¬                Logical Not
          θ             Input string
         ⪪              Split on
           .            Literal `.`
        Φ               Filter by
            ¬           Logical Not
               ²⁵⁶      Literal 256
              Ｅ         Map over implicit range
                   λ    Map value
                  Ｉ     Cast to string
             №          Count occurrences of
                    ι   Filter value
Ｉ                       Cast to string
                        Implicitly print

```

# Answer
> 2 votes
# Python 3, ~~109~~ 93 bytes

```
import re
lambda x:bool(re.match(r'^((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(\.(?!$)|$)){4}$',x))

```

**Explanation**

Each octet can be 0 - 255 :

* starts with 25 and having 0-5 as last digit
* start with 2, has 0-4 as second digit and any digit at the end
* starts with 1, and 00 - 99 as rest digits
* has only 2 digits - 1-9 being the first one and any digit thereafter
* or just a single digit

An octet can end with a (.) or just end, with the condition that it cannot do both , the negative lookahead `(?!$)` takes care of this case

Thanks @Zachary for making me realize I can discard spaces (since it is code golf)
Thanks @DLosc for the improvements and making me realize my mistake, its been corrected now.

# Answer
> 2 votes
# Retina, ~~46~~ 44 bytes

```
^
.
^(\.(25[0-5]|(2[0-4]|1\d|[1-9])?\d)){4}$

```

Port of *@OlivierGrégoire*'s Java answer, so make sure to upvote him!
-2 bytes thanks to *@Neil*.

Try it online.

**Explanation:**

```
^
.                           # Prepend a dot "." before the (implicit) input
^...$                       # Check if the entire string matches the following regex
                            # exactly, resulting in 1/0 as truthy/falsey:
 (                          #  Open a capture group
  \.                        #   A dot "."
    (25[0-5]                #   Followed by a number in the range [250,255]
    |(2[0-4]|         ) \d) #   or by a number in the range [200,249]
    |(      |1\d|     ) \d) #   or by a number in the range [100,199]
    |(          |[1-9]) \d) #   or by a number in the range [10,99]
    |(                )?\d) #   or by a number in the range [0,9]
 )                          #  Close capture group
  {4}                       #  This capture group should match 4 times after each other

```

# Answer
> 2 votes
# Stax, 14 bytes

```
∞n·Θ3ª&JH‼∙*~Γ

```

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

```
VB      constant 256
r       [0 .. 255]
'|*     coerce and string-join with "|"; i.e. "0|1|2|3 ... 254|255"
:{      parenthesize to "(0|1|2|3 ... 254|255)"
]4*     make 4-length array of number pattern
.\.*    string join with "\\."; this forms the complete regex
|Q      is the input a complete match for the regex?

```

Run this one

# Answer
> 2 votes
# Perl 5 `-pF/\./`, 47 bytes

```
$\=@F==4&&!/[^0-9.]/;$\&&=!/^0./&&$_<256for@F}{

```

Try it online!

# Answer
> 2 votes
# Retina, ~~42~~ 41 bytes

```
~(K`

255*
["^(("|'|]")\.?\b){4}$"L$`
$.`

```

Try it online! Based on a previous version of @nwellnhof's Perl 6 answer, but 1 byte saved by stealing the `\.?\b` trick from @Deadcode's answer. Explanation:

```
K`

```

Clear the work area.

```
255*

```

Insert 255 characters.

```
["^(("|'|]")\.?\b){4}$"L$`
$.`

```

Generate the range 0..255 separated with `|`s, prefixed with `^((`, and suffixed with `)\.?\b){4}$`, thus building the regular expression `^((0|1|...255)\.?\b){4}$`.

```
~(

```

Evaluate that on the original input.

# Answer
> 2 votes
# Jelly, 11 bytes

```
⁹ḶṾ€ṗ4j€”.ċ

```

A monadic link accepting a list of characters which yields \\$1\\$ if it's a valid address and \\$0\\$ otherwise. Builds a list of all \\$256^4=4294967296\\$ addresses and then counts the number of occurrences of the input therein.

**Here's similar @ Try it online!** that uses \\$16\\$ () rather than \\$256\\$ (), since the method is so inefficient!

### How?

```
⁹ḶṾ€ṗ4j€”.ċ - Link: list of characters, S
⁹           - literal 256
 Ḷ          - lowered range = [0,1,2,...,254,255]
  Ṿ€        - unevaluate €ach = ['0','1',...,['2','5','4'],['2','5','5']]
    ṗ4      - 4th Cartesian power = ALL 256^4 lists of 4 of them
            -               (e.g.: ['0',['2','5','5'],'9',['1','0']])
        ”.  - literal '.' character
      j€    - join for €ach (e.g. ['0','.','2','5','5','.','9','.','1','0'] = "0.255.9.10")
          ċ - count occurrences of right (S) in left (that big list)

```

# Answer
> 1 votes
# C (gcc), ~~287~~ 197 bytes

```
#import<regex.h>
g;f(char*s){regex_t r;g=regcomp(&r,"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$",1);g=regexec(&r,s,0,0,0);return !g;}

```

Try it online!

Thanks to Logern for the big save !

# Answer
> 1 votes
# Pip, ~~25~~ 16 bytes

```
a~=X,256RL4J"\."

```

Takes the candidate IP address as a command-line argument. Try it online! or Verify all test cases

### Explanation

Regex solution, essentially a port of recursive's Stax answer.

```
                  a is 1st cmdline arg (implicit)
    ,256          Range(256), i.e. [0 1 2 ... 255]
   X              To regex: creates a regex that matches any item from that list
                  i.e. essentially `(0|1|2|...|255)`
        RL4       Create a list with 4 copies of that regex
           J"\."  Join on this string
 ~=               Regex full-match
a                 against the input

```

# Answer
> 1 votes
# , 59 bytes

Passes special cases not in test with periods at start/end

```
function(s)length(a<-scan(,t=s,s,,,"."))==4&all(a%in%0:255)

```

Try it online!

# Answer
> 1 votes
## JavaScript, 89 bytes

```
(_,r=`(${[...Array(256).keys()].join`|`})`)=>RegExp(`^${(r+'\\.').repeat(3)+r}$`).test(_)

```

Try it online!

Create `RegExp` capture groups from indexes of an array having `length` `256` for range `0-255` joined with `|` and followed by escaped `.` character (`^(0|1...|255)\.(0|1...|255)\.(0|1...|255)\.(0|1...|255)$`) repeated `3` times closing with joined array followed by `$` to match end of string, return `true` or `false` result of input passed to `RegExp.prototype.test()`.

# Answer
> 1 votes
# Ruby, ~~123~~ 107 bytes

Try it online!

```
a=gets.chomp
e=a.split'.'
(p 0;exit)if(e.map(&:to_i).join'.')!=a
p(e.all?{|i|(0..255)===i.to_i}&&e.size==4)

```

This could definitely be shorter, probably with a regex of some sort, but I wanted to do it without a regex.

Thanks to MegaTom for Array#all?

`0` or `false` is falsy; `true` is truthy.

Explanation:

The input is taken from stdin. It's split into an array of the numbers (as strings) on the periods.

If the array isn't the same as it is with the elements converted to numbers and back to strings, the program outputs `0` and exits. This eliminates cases with leading zeros and illegal characters.

The array is converted to an array of true/false values representing whether the value is between 0 and 255, inclusive.

`true` is outputted if the array is only true values, meaning that all the numbers were between 0 and 255, and only if it has exactly 4 elements, meaning that there were 4 original numbers. `false` is outputted otherwise, meaning invalid numbers (higher than 255) or too many numbers.

# Answer
> 1 votes
**APL(NARS), 45 chars**

```
{'...'≢⍵∼⎕D:0⋄4≠+/255≥⍎¨a←⍵⊂⍨⍵≠'.':0⋄a≡⍕¨⍎¨a}

```

test

```
  f←{'...'≢⍵∼⎕D:0⋄4≠+/255≥⍎¨a←⍵⊂⍨⍵≠'.':0⋄a≡⍕¨⍎¨a}
  f '1.160.10.240'
1
  f '192.001.32.47'
0
  f '1.2.3.'
0
  f '1.2.3'
0

```

# Answer
> 0 votes
# Batch, 53 bytes

```
@(ping -4 %1&echo g 255.255.255.255 w)|find/c"g %1 w"

```

Disconnect your Internet connection first to avoid the standard loophole.

I can't find information on how to avoid `^"`.

# Answer
> 0 votes
# APL(NARS) 50 chars, 100 bytes

```
{'...'≢⍵∼⎕D:0⋄4≠≢w←⍵⊂⍨⍵≠'.':0⋄w≢⍕¨m←⍎¨w:0⋄256>⌈/m}

```

test:

```
  p←{'...'≢⍵∼⎕D:0⋄4≠≢w←⍵⊂⍨⍵≠'.':0⋄w≢⍕¨m←⍎¨w:0⋄256>⌈/m}
  {⍞←'[',⍵,'=',(p ⍵),']'⋄⍬}¨a
[1.160.10.240= 1 ][192.001.32.47= 0 ][1.2.3.= 0 ][0.00.10.255= 0 ][1.2.$.4= 0 ][255.160.0.34= 1 ][.1.1.1= 0 ][1..1.1.1= 0 ][1.1.1.-0= 0 ][.1.1.+1= 0 ][1 1 1 1= 0 ][1= 0 ][10.300.4.0= 0 ][10.4F.10.99= 0 ][fruit loops= 0 ][1.2.3.4.5= 0 ][0.0.0.0= 1 ][0.0 0.0.= 0 ][1.23..4= 0 ][1:1:1:1:1:1:1:1= 0 ]

```

# Answer
> 0 votes
# Scala, 87 bytes

A port of @Olivier Grégoire's answer.

Try it online!

```
val f:String=>Boolean=s=>("." + s).matches("(\\.(25[0-5]|(2[0-4]|1\\d|[1-9])?\\d)){4}")

```

# Answer
> 0 votes
# Thunno 2, 15 bytes

```
'./Ẋl4=ɠL€ṘxƇp&

```

Try it online!

#### Explanation

```
'./Ẋl4=ɠL€ṘxƇp&  '# Implicit input
'./              '# Split the input on "."s
   Ẋ              # Store this in x without popping
    l4=           # Check if the length equals 4
       ɠL         # Push the range [0..255]
         €Ṙ       # Convert each to a string
           xƇp    # Check if each of the values in x
                  # is in this list of strings
                  # (NOTE: this checks three things at once:
                  #   1. all the parts are numbers
                  #   2. all of them are in the range [0..255]
                  #   3. none of them have leading zeros)
              &   # Check if both things are true
                  # Implicit output

```

# Answer
> 0 votes
# Go, 81 bytes

```
import."net/netip"
func f(s string)bool{a,e:=ParseAddr(s)
return e==nil&&a.Is4()}

```

Attempt This Online!

Uses the `net/netip` package from the standard library.

# Go, 119 bytes

```
import."regexp"
func f(s string)bool{return MustCompile(`^(\.(25[0-5]|(2[0-4]|1\d|[1-9])?\d)){4}$`).MatchString("."+s)}

```

Attempt This Online!

Using the regex from @Olivier Grégoire's post.

# Answer
> -1 votes
# PHP, 27 26 24 Bytes

```
<?=+!!ip2long($argv[1]);

```

Based on @rexkogitans and @nwellnhof solutions Fails for 0.0.0.0 because PHP internal function 0.0.0.0 is not considered a valid IP address Try it!

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


title: Output 5-line calendar

text:
# Question
Title: Output 5-line calendar
Given year, month and optionally weekday of 1st, output the calendar of the month. The first week should remain nonempty.

For empty cell, fill it with the date where it's supposed to be, in last or next month, and add `#` to indicate gray. If last few days can't fit in 5 lines, then they share last line with 5th week, use `/` to separate two days.

Sample Input: `Nov 2023`

Sample Output:

```
 #29   #30   #31     1     2     3     4
   5     6     7     8     9    10    11
  12    13    14    15    16    17    18
  19    20    21    22    23    24    25
  26    27    28    29    30    #1    #2

```

Sample Input: `Dec 2023`

Sample Output:

```
 #26   #27   #28   #29   #30     1     2
   3     4     5     6     7     8     9
  10    11    12    13    14    15    16
  17    18    19    20    21    22    23
24/31   25    26    27    28    29    30

```

Sample Input: `Feb 2026`

Sample Output:

```
   1     2     3     4     5     6     7
   8     9    10    11    12    13    14
  15    16    17    18    19    20    21
  22    23    24    25    26    27    28
  #1    #2    #3    #4    #5    #6    #7

```

Outputting a 2D array of string is fine. SMTWTFS and MTWTFSS are both allowed. Input is flexible.

Shortest code win.

# Answer
# Charcoal, ~~108~~ 93 bytes

```
≔⊕⪪”)∨←∧h”¹ε§≔ε²¬﹪⊟Φ↨Ｎ¹⁰⁰ι⁴ＵＭεＩ…·¹⁺²⁸ιＮη≔⁺⁺#⮌…⮌§ε⊖ηＮ§εηυＦ⁻Ｌυ³⁵§≔υ±⁷⁺⁺§υ±⁸/⊟υＥ…⪪⁺υ⁺#⊟ε⁷¦⁵⭆ι◧λ

```

Try it online! Link is to verbose version of code. Takes input in the order year, month, weekday (0-indexed). Explanation:

```
≔⊕⪪”)∨←∧h”¹ε§≔ε²¬﹪⊟Φ↨Ｎ¹⁰⁰ι⁴ＵＭεＩ…·¹⁺²⁸ι

```

Get an array of lists of the days of the months as strings, with February calculated according to whether the year is divisible by four.

```
Ｎη≔⁺⁺#⮌…⮌§ε⊖ηＮ§εηυ

```

Input the month and concatenate any necessary trailing days from the previous month to the current month.

```
Ｆ⁻Ｌυ³⁵§≔υ±⁷⁺⁺§υ±⁸/⊟υ

```

If there are more than 35 days then fold the extra days into the previous week. (The assignment uses `-7` because the extra day has been popped by this point.)

```
Ｅ…⪪⁺υ⁺#⊟ε⁷¦⁵⭆ι◧λ

```

Fill any remaining days with days from the next month and pretty-print the output. (`…⪪⁺υ⁺#⊟ε⁷¦⁵` would just output the 2D array.)
> 2 votes

# Answer
# Python, 165 bytes

```
from datetime import*
lambda y,m,w,k=timedelta:[*zip(*[(f"#{(q:=date(y,m,1)+k(t-w)).day}"[q.month==m:]+f'/{q.day+7}'*(t>27>(q+k(7)).month==m)for t in range(35))]*7)]

```

Attempt This Online!

MTWTFSS. Takes one-indexed year and month, and zero-indexed weekday
> 1 votes

# Answer
# Scala 3, ~~239~~ 224 bytes

Saved 15 bytes thanks to @corvus\_192

---

MTWTFSS. Takes one-indexed year and month, and zero-indexed weekday

---

Golfed version. Attempt This Online!

```
(y,m,w)=>{val s=LocalDate.of(y,m,1);val f=s.`with`(TemporalAdjusters.previousOrSame(DayOfWeek.of(w%7)))
Seq.tabulate(35)(i=>f.plusDays(i))grouped 7 map(_.map(day=>(if(day.getMonthValue==m)""else"#")+day.getDayOfMonth))toSeq}

```

Ungolfed version. Attempt This Online!

```
import java.time._
import java.time.temporal.TemporalAdjusters

object Main {
  def main(args: Array[String]): Unit = {
    def f(year: Int, month: Int, weekday: Int): Array[Array[String]] = {
      val monthStart = LocalDate.of(year, month, 1)
      val firstDayOfWeek = monthStart.`with`(TemporalAdjusters.previousOrSame(DayOfWeek.of((weekday % 7) + 0)))

      val days = Array.tabulate(35)(i => firstDayOfWeek.plusDays(i))
      val weeks = days.grouped(7).toArray
      weeks.map(_.map { day =>
        val prefix = if (day.getMonthValue == month) "" else "#"
        s"$prefix${day.getDayOfMonth}"
      })
    }

    val result = f(2023, 12, 1) // 1 corresponds to Monday in LocalDate
    result.foreach(week => println(week.mkString("(", ", ", ")")))
  }
}

```
> 1 votes

# Answer
# Jelly, 59 bytes

```
ọ4,25>/“ḢȷĠ’b4¤o+28ṙḣ3RUḣ€1¦⁵UṾ€€Ż€€ÐoẎs7ḣ6µṪẠƇż@Ṫj€”/ṭo”#G

```

Try it online!

A full program that takes three integer arguments: the 4-digit year, the 1-indexed month, and the 0-indexed day of the week for the first of the month. My example on TIO assumes Monday as the first day of the week. The output to STDOUT is a calendar in the desired format.

The first 7 bytes are taken directly from @Dennis’ clever answer to a previous question on calculating leap years.

## Explanation

```
ọ4,25>/“ḢȷĠ’b4¤o+28ṙḣ3RUḣ€1¦⁵UṾ€€Ż€€ÐoẎs7ḣ6µṪẠƇż@Ṫj€”/ṭo”#G
ọ4,25                                                        # Number of times the year can be divided by 4 and 25 (importantly the first number will be >=2 for years that are multiples of 400 and 1 for those that are other century years)
     >/                                                      # Reduce using greater than (will return 1 for leap years and 0 for others)
       “ḢȷĠ’b4¤o                                             # Or with [2,3,3,0,3,2,3,2,3,3,2,3] (This is stored as a base-250 integer than is converted to base 4)
                +28                                          # Add 28
                   ṙ                                         # Rotate to the left by the 1-indexed month number
                    ḣ3                                       # First three (will be the lengths of the months before, at and after the relevant month)
                      R                                      # Ranges 1..each of these
                       U                                     # Reverse each range
                        ḣ€1¦⁵                                # For the month before, take the first x values only where x is the 0-indexed day of the first day of the main month
                             U                               # Reverse each month’s days again
                              Ṿ€€                            # Uneval each day (will convert to Jelly strings)
                                 Ż€€Ðo                       # Prefix the first and last month’s days with a zero
                                      Ẏ                      # Join outer lists
                                       s7                    # Split into pieces length 7
                                         ḣ6                  # Take the first six
                                           µ                 # Start a new chain with this as the argument
                                            Ṫ                # Pop the tail (the sixth row of the calendar)
                                             ẠƇ              # Keep only those where all are truthy (will remove any days from the following month since those are prefixed by zero)
                                               ż@Ṫ           # Zip the tail of the calendar with this (I.e. the fifth row of the calendar)
                                                  j€”/       # Join each with slashes
                                                      ṭ      # Tag onto the remaining (first) four rows of the calendar
                                                       o”#   # Or with hashes (will replace the zero prefixes with hashes)
                                                          G  # Format as a grid

```

Created with the help of Luminespire.
> 1 votes

# Answer
# Google Sheets, 134 bytes

`=wraprows(index(regexreplace(substitute(text(sequence(35,1,A1-weekday(A1,2)*(mod(A1,6)<>4)),"MMMd"),text(A1,"MMM"),),"[A-z]+","#")),7)`

Put a value like `Nov 2023` in cell `A1` and the formula in cell `B1`.

The rules allow that the weekday can be specified separately. To do that , put `=weekday(A1, 2)` in cell `B1` (**123 bytes**):

`=wraprows(index(regexreplace(substitute(text(sequence(35,1,A1-B1*(mod(A1,6)<>4)),"MMMd"),text(A1,"MMM"),),"[A-z]+","#")),7)`

(does not produce `24/31` for `Dec 2023`)
> 0 votes

# Answer
# JavaScript (ES6), 123 bytes

Expects `(year, month)(weekday)`, where *weekday* is 0-indexed SMTWTFS.

```
(y,m,n=0)=>g=w=>n++<35?(n-(h=k=>i=new Date(y,m-1,n-w+k).getDate())``&~7?"#"+i:i)+(n*h(7)>868?"/"+i:"")+`
 `[n%7&&1]+g(w):""

```

Try it online!

### Method

We walk through the calendar slots by iterating from `n=1` to `n=35`.

The helper function `h` takes a parameter `k` and returns the date of the month for the year `y`, month `m` and day `n-w+k`. The result is saved in the global variable `i`.

```
h = k =>
  i = new Date(y, m - 1, n - w + k).getDate()

```

If `n - h(0)` is negative or greater than 7, it means that the date belongs to the previous or the next month respectively. Hence the test:

```
n - h(0) & ~7 ? "#" + i : i

```

We have to add the `/xx` pattern if we are located on the last row of the calendar (`n ≥ 29`) and the date at +7 days still belongs to the current month. For this purpose, we use the test:

```
n * h(7) > 868

```

This test is true if and only if `n ≥ 29` and `h(7)` reaches a threshold corresponding to one of the last few days of the month:

| n | h(7) |
| --- | --- |
| 28 | ≥32 (impossible) |
| 29 | ≥30 |
| 30 | ≥29 |
| 31 | ≥29 |
| 32 | ≥28 |
| 33 | ≥27 |
| 34 | ≥26 |
| 35 | ≥25 |
> 0 votes

---
Tags: code-golf, date
---