title: Ten-row bar chart

text:
# Question
Title: Ten-row bar chart
**This is Hole-1 from *The Autumn Tournament* of APL CodeGolf. I am the original author of the problem there, and thus allowed to re-post it here.**

---

Given a list of numbers, produce a horizontal bar chart of `#` characters for how many numbers fit into each of ten equal-sized groups. For example, if the data ranges from 0-100, the ranges will be 0–9.9, 10–19.9, …, 90–100. (Formally, \[0,10), \[10,20), …, \[90,100\].). You may assume that there will be at least two numbers and that not all numbers will be the same.

### Examples:

`[1,0,0,0,0,0,0,0,0,0]` gives:

```
#########

#

```

`[0,1,2,3,4,5,6,7,8,9]` gives:

```
#
#
#
#
#
#
#
#
#
#

```

`[0,1,2,3,4,5,6,7,8,9,10]` gives:

```
#
#
#
#
#
#
#
#
#
##

```

`[0,1,2,3,4,5,6,7,8,9,10,11]` gives:

```
##
#
#
#
#
#
#
#
#
##

```

`[0,-0.5,-1,-1.5,-2,-2.5,-3,-3.5,-4,-4.5,0.5,0,-0.5,-1,-1.5,-2,-2.5,-3,-3.5,-4,1,0.5,0,-0.5,-1,-1.5,-2,-2.5,-3,-3.5,1.5,1,0.5,0,-0.5,-1,-1.5,-2,-2.5,-3,2,1.5,1,0.5,0,-0.5,-1,-1.5,-2,-2.5,2.5,2,1.5,1,0.5,0,-0.5,-1,-1.5,-2,3,2.5,2,1.5,1,0.5,0,-0.5,-1,-1.5,3.5,3,2.5,2,1.5,1,0.5,0,-0.5,-1,4,3.5,3,2.5,2,1.5,1,0.5,0,-0.5,4.5,4,3.5,3,2.5,2,1.5,1,0.5,0]` gives:

```
###
#######
###########
###############
#########
###################
###############
###########
#######
###

```

`[9014,9082,9077,9068,8866,8710,9049,8364,8867,9015,9064,9023,9024,8804,8805,8800,8744,8743,8714,9076,8593,8595,9075,9675,8968,8970,8711,8728,8834,8835,8745,8746,8869,8868,9073,9074,9042,9035,9033,9021,8854,9055,9017,9045,9038,9067,9066,8801,8802,9496,9488,9484,9492,9532,9472,9500,9508,9524,9516,9474,8739,9079,8900,8592,8594,9053,9109,9054,9059]` gives:

```
#
####
#########
############
######
#########################

###########
#

```

`[0,8,10,13,32,12,6,7,27,9,37,39,95,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,1,2,175,46,48,49,50,51,52,53,54,55,56,57,3,165,36,163,162,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,4,5,253,183,127,193,194,195,199,200,202,203,204,205,206,207,208,210,211,212,213,217,218,219,221,254,227,236,240,242,245,123,125,168,192,196,197,198,201,209,214,216,220,223,224,225,226,228,229,230,231,232,233,234,235,237,238,239,241,91,47,92,60,61,62,45,43,247,215,63,126,42,40,124,59,44,33,243,244,246,248,34,35,30,38,180,64,249,250,251,94,252,96,182,58,191,161,41,93,31,160,167]` gives:

```
#############
######################
##########################
#########################
#########################
#
########
################
########################
##########################

```

# Answer
> 4 votes
# Python 2, ~~107~~ 95 bytes

```
l=input();m=min(l);s=(max(l)-m)/10.;c=0
exec'print"#"*sum(m<=v-c*s<m+s+c/9for v in l);c+=1;'*10

```

Try it online!

# Answer
> 4 votes
# , ~~77~~ 81 bytes

*+4 bytes to fix some test cases*

```
for(i in hist(x<-scan(),seq(min(x),max(x),,11),r=F)$c)cat(rep('#',i),'\n',sep='')

```

Try it online!

Link is to a version of the code that takes comma-separated input; this version takes space-separated.

Reads from stdin, prints to stdout.

R is a statistical programming language that does its best to give high-quality results, which is sometimes frustrating:

`hist` bins the inputs into a histogram with `breaks` as its second argument. Normally, one would expect that you could specify that the number of breaks to be 10. Indeed, this is the case:

> `breaks`
>
> one of:
>
> * a vector giving the breakpoints between histogram cells,
> * a function to compute the vector of breakpoints,
> * **a single number giving the number of cells for the histogram,**
> * a character string naming an algorithm to compute the number of cells (see ‘Details’),
> * a function to compute the number of cells.

(emphasis added).

The next sentence, however, says:

> In the last three cases the number is a suggestion only; as the breakpoints will be set to `pretty` values, the number is limited to `1e6` (with a warning if it was larger).

So I looked at the documentation of `pretty` and it just doesn't work for our situation, because it picks break points thusly:

> Compute a sequence of about `n+1` equally spaced ‘round’ values which cover the range of the values in `x`. The values are chosen so that they are 1, 2 or 5 times a power of 10.

Which simply won't do.

So the `seq(min(x),max(x),,11)` specifies 11 equally-spaced points as the `breaks`, `hist(x,breaks,r=F)$c` gives the counts, `r=F` ensures that the bins are right-open intervals, and the `for` loop takes care of the rest.

# Answer
> 4 votes
# Python 2, 96 bytes

```
l=input()
m=min(l)
w=max(l)-m
for i in range(10):print"#"*sum(w*i<=(x-m)*10<w*-~i+i/9for x in l)

```

Try it online!

# Answer
> 3 votes
# Mathematica, 152 bytes

```
(Do[Print[""<>Table["#",Length@Select[s=#,Min@s+(t=#2-#&@@MinMax@s/10)(i-1)<=#<Min@s+t*i&]]],{i,9}];Print[""<>Table["#",Length@Select[s,Max@s-t<=#&]]])&

```

Try it online!

# Answer
> 3 votes
# C (gcc), 241 bytes

```
#define P(x)for(;x--;putchar('#'));puts("");
double a[999],u,l,x;i,j,n[9];main(k){for(;scanf("%lf",&x)>0;u=u>x?u:x,l=l<x?l:x,a[i++]=x);for(;j<i;++j)for(k=0;k<9;)if(a[j]<l+(++k)*(u-l)/10){n[k-1]++;break;}for(k=0;k<9;++k){i-=n[k];P(n[k])}P(i)}

```

Try it online!

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

*Edit* 2 bytes save thx @JustinMariner

A function returning an array of strings

```
l=>l.map(v=>o[i=(v-n)/(Math.max(...l)-n)*10|0,i>9?9:i]+='#',o=Array(10).fill``,n=Math.min(...l))&&o

```

*Less golfed*

```
list => {
   var max = Math.max(...list),
       min = Math.min(...list),
       output = Array(10).fill(''),
       index;

   list.forEach( value => (
      index = (value - min) / (max - min) * 10 | 0,
      output [index > 9 ? 9 : index] += '#'
   ) )
   return output
}

```

**Test**

```
var F=
l=>l.map(v=>o[i=(v-n)/(Math.max(...l)-n)*10|0,i>9?9:i]+='#',o=Array(10).fill``,n=Math.min(...l))&&o

var test=[
[1,0,0,0,0,0,0,0,0,0],
[0,1,2,3,4,5,6,7,8,9],
[0,-0.5,-1,-1.5,-2,-2.5,-3,-3.5,-4,-4.5,0.5,0,-0.5,-1,-1.5,-2,-2.5,-3,-3.5,-4,1,0.5,0,-0.5,-1,-1.5,-2,-2.5,-3,-3.5,1.5,1,0.5,0,-0.5,-1,-1.5,-2,-2.5,-3,2,1.5,1,0.5,0,-0.5,-1,-1.5,-2,-2.5,2.5,2,1.5,1,0.5,0,-0.5,-1,-1.5,-2,3,2.5,2,1.5,1,0.5,0,-0.5,-1,-1.5,3.5,3,2.5,2,1.5,1,0.5,0,-0.5,-1,4,3.5,3,2.5,2,1.5,1,0.5,0,-0.5,4.5,4,3.5,3,2.5,2,1.5,1,0.5,0],
[0,8,10,13,32,12,6,7,27,9,37,39,95,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,1,2,175,46,48,49,50,51,52,53,54,55,56,57,3,165,36,163,162,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,4,5,253,183,127,193,194,195,199,200,202,203,204,205,206,207,208,210,211,212,213,217,218,219,221,254,227,236,240,242,245,123,125,168,192,196,197,198,201,209,214,216,220,223,224,225,226,228,229,230,231,232,233,234,235,237,238,239,241,91,47,92,60,61,62,45,43,247,215,63,126,42,40,124,59,44,33,243,244,246,248,34,35,30,38,180,64,249,250,251,94,252,96,182,58,191,161,41,93,31,160,167],
[9014,9082,9077,9068,8866,8710,9049,8364,8867,9015,9064,9023,9024,8804,8805,8800,8744,8743,8714,9076,8593,8595,9075,9675,8968,8970,8711,8728,8834,8835,8745,8746,8869,8868,9073,9074,9042,9035,9033,9021,8854,9055,9017,9045,9038,9067,9066,8801,8802,9496,9488,9484,9492,9532,9472,9500,9508,9524,9516,9474,8739,9079,8900,8592,8594,9053,9109,9054,9059]];

output=x=>O.textContent+=x+'\n\n'

test.forEach(t=>output(t+'\n'+F(t).join`\n`))
```

```
<pre id=O></pre>
```

# Answer
> 2 votes
# Python 2, ~~126~~ 121 bytes

```
def f(a):
 m=min(a);r=range(10);A=[sum(x>=m+i*(max(a)-m)/10.for x in a)for i in r]+[0]
 for i in r:print'#'*(A[i]-A[i+1])

```

Try it online!

# Answer
> 2 votes
# Jelly, 21 bytes

A monadic link returns a list of strings.

```
_Ṃµ÷Ṁ×⁵Ḟµ<⁵+ċÐ€⁵R¤”#ẋ

```

Try it online!

# Answer
> 2 votes
# Charcoal, 31 bytes

```
≔Ｉ⪪Ｓ,θＥχ×#ΣＥθ⁼ι⌊⟦⁹⌊×χ∕⁻λ⌊θ⁻⌈θ⌊θ

```

Try it online! Link is to verbose version of code. Input of variable-length lists seems to a little awkward in Charcoal, so I've had to wrap the list in an array containing a string. Explanation:

```
   Ｓ                            Input string
  ⪪ ,                           Split on commas
 Ｉ                              Cast elements to integer
≔    θ                          Assign to variable q
      Ｅχ                        Map from 0 to 9
           Ｅθ                   Map over the list
                      ⁻λ⌊θ      Subtract the minimum from the current
                          ⁻⌈θ⌊θ Subtract the minimum from the maximum
                     ∕          Divide
                   ×χ           Multiply by 10
                  ⌊             Floor
               ⌊⟦⁹              Take minimum with 9
             ⁼ι                 Compare to outer map variable
          Σ                     Take the sum
        ×#                      Repeat # that many times
                                Implicitly print on separate lines

```

# Answer
> 2 votes
# Pyth,  ~~32~~  31 bytes

```
*R\#_M.++msmgk+JhSQ*dc-eSQJTQTZ

```

**Try it here!** or **Verify all the test cases.** (with pretty-print using `j`)

# How this works

This is a full program that takes input from STDIN. This is for the 32-byte version. I'll update it soon.

```
*R\#_M.++msmgk+hSQ*dc-eSQhSQTQTZ  ~ Full program.

         m                    T   ~ Map over [0, 10) with var d.
           m                 Q    ~ Map over the input with var k.
            g                     ~ Is higher than or equal to?
             k                    ~ The current element of the input, k.
              +hSQ*dc-eSQhSQT     ~ We'll break this down into pieces:
               hSQ                  ~ The lowest element of the input list.
              +                     ~ Plus:
                  *dc-eSQhSQT       ~ We'll break this down into more pieces:
                  *                   ~ Multiplication.
                   d                  ~ The current element of [0, 10), d.
                    c       T         ~ Float division by 10 of:
                     -eSQhSQ          ~ The difference between the maximum and minium
                                        of the input list.
          s                       ~ Sum. Count the number of truthy results.
        +                      Z  ~ Append a 0.
      .+                          ~ Get the deltas.
    _M                            ~ Gets -delta for each delta in the list above.
  \#                              ~ The literal character "#".
*R                                ~ Vectorized multiplication. Optionally, you can
                                    use j to join by newlines (as the link does).
                                  ~ Output implicitly.

```

# Answer
> 2 votes
# Fortran 2003, 263 bytes

I wrote it on GNU gfortran 5.4.0, and compiled without any additional flags.

It reads from STDIN, one value at a time, and prints to STDOUT.

Here it goes:

```
program h;real,allocatable::a(:);character f*9;allocate(a(0));do;read(*,*,end=8)r;a=[a,r];enddo;9 format("(",i0,"(""#""))")
8 a=(a-minval(a))+epsilon(1.);a=ceiling(10*a/maxval(a));do i=1,10;j=count(a==i);if(j==0)print*;if(j==0)cycle;write(f,9)j;
print f;enddo;end

```

Ungolfed explanation: (I don't know if "golfed" can be applied to fortran but either way :P)

```
program h
real,allocatable::a(:)       ! Create an allocatable array so we can reallocate dynamically
character f*9                ! A character array to format the output
allocate(a(0))               ! Allocate "a" empty at first
do
  read(*,*,end=8)r           ! Read from STDIN. If EOF, goes to 8, otherwise
  a=[a,r]                    ! Appends to "a"
enddo
9 format("(",i0,"(""#""))")  ! A format label
8 a=(a-minval(a))+epsilon(1.)! (8) Normalizes a (adds epsilon to avoid zero-indexing)
a=ceiling(10*a/maxval(a))    ! Normalizing and multiplying by the number of bins
do i=1,10                    ! Looping on all the bins
  j=count(a==i)              ! Counting the number of occurrences
  if(j==0)print*             ! If none, prints empty line
  if(j==0)cycle              ! And skips the rest of the loop
  write(f,9)j                ! Otherwise writes the count(j) to the print label
  print f                    ! And prints to STDOUT
enddo
end

```

Fun fact: I made a similar code just yesterday to test my implementation of a Weibull random number generator, so it only needed a little adaptation :)

# Answer
> 2 votes
# Perl 5, 85 + 1 (`-a`) = 86 bytes

```
@F=sort{$a<=>$b}@F;map$r[($_-$F[0])/($F[-1]-$F[0])*10].='#',@F;$r[9].=pop@r;say for@r

```

Try it online!

# Answer
> 1 votes
# Java (OpenJDK 8), ~~246~~ ~~221~~ ~~209~~ ~~207~~ ~~206~~ ~~163~~ ~~162~~ ~~161~~ 157 bytes

```
l->{String x="";double b=l[0],m=b,q,i;for(double d:l){b=d<b?d:b;m=d>m?d:m;}for(i=(m-b)/10,q=b;q<m;q+=i,x+="\n")for(double d:l)x+=d>=q&d<q+i?"#":"";return x;}

```

Try it online!

# Answer
> 1 votes
# Perl 5, 84 + 19 (-MList::Util=min,max) bytes

```
$s=-($m=min@_=@ARGV)+max@_;$a[($_-$m)*10/$s]++for@_;$a[9]+=pop@a;print"#"x$_,$/for@a

```

Try It Online

# Answer
> 1 votes
# Perl 5, 102 bytes

```
$l=(@n=sort{$a<=>$b}<>)[-1]-($f=$n[0]);$m=$f+$l*$_/10,say'#'x(@n-(@n=grep$_>=$m,@n))for 1..9;say'#'x@n

```

Try it online.

Ungolfed:

```
my @n = sort { $a <=> $b } <>;
my $f = $n[0];
my $l = $n[-1] - $n[0];
for (1 .. 9) {
    my $m = $f + $l * ($_ / 10);
    my $c = scalar @n;
    @n = grep { $_ >= $m } @n;
    say('#' x ($c - scalar @n));
}
say('#' x scalar @n);

```

# Answer
> 1 votes
# q/kdb+, 52 bytes

**Solution:**

```
{sum[t=/:bin[m+.1*(t:(!)10)*max[x]-m:min x;x]]#'"#"}

```

Try it online! (Note the TIO link is a 44 byte K (oK) port of this solution as there is no TIO for q/kdb+).

**Examples:**

```
q){sum[t=/:bin[m+.1*(t:(!)10)*max[x]-m:min x;x]]#'"#"}1 0 0 0 0 0 0 0 0 0f
"#########"
""
""
""
""
""
""
""
""
,"#

q){sum[t=/:bin[m+.1*(t:(!)10)*max[x]-m:min x;x]]#'"#"}9014 9082 9077 9068 8866 8710 9049 8364 8867 9015 9064 9023 9024 8804 8805 8800 8744 8743 8714 9076 8593 8595 9075 9675 8968 8970 8711 8728 8834 8835 8745 8746 8869 8868 9073 9074 9042 9035 9033 9021 8854 9055 9017 9045 9038 9067 9066 8801 8802 9496 9488 9484 9492 9532 9472 9500 9508 9524 9516 9474 8739 9079 8900 8592 8594 9053 9109 9054 9059f
,"#"
"####"
"#########"
"############"
"######"
"#########################"
""
""
"###########"
,"#"

```

**Explanation:**

Most of the code is used creating the buckets that `bin` buckets the input into.

```
{sum[t=/:bin[m+.1*(t:til 10)*max[x]-m:min x;x]]#'"#"} / ungolfed solution
{                                                   } / lambda function with implicit x as parameter
                                               #'"#"  / take (#) each-both "#", 1 2 3#'"#" => "#","##","###"
 sum[                                         ]       / sum up everything inside the brackets
         bin[                              ;x]        / binary search each x in list (first parameter)
                                    m:min x           / store minimum of list x in variable m
                             max[x]-                  / subtract from the maximum of list x
                  (t:til 10)*                         / range 0..9 vectorised multiplication against max delta of list
               .1*                                    / multiply by 0.1 (aka divide by 10)
             m+                                       / minimum of list vectorised addition against list
     t=/:                                             / match each-right against range 0..9 (buckets)

```

# Answer
> 0 votes
# Jelly, 19 bytes

```
_Ṃµ÷Ṁ×⁵Ḟ«9ċÐ€⁵Ḷ¤”#ẋ

```

Try it online!

This is based upon my APL answer for the original problem, which I will post after that competition is over.

## How? (I'm not good at explaining things)

```
_Ṃµ÷Ṁ×⁵Ḟ«9ċÐ€⁵Ḷ¤”#ẋ
_Ṃ                  = subtract the minimum
  µ                 = Sort of like a reverse-order compose
   ÷Ṁ               = divide by the max
     ×⁵             = Multiply by 10
       Ḟ            = Take the floor
        «9          = x => min(x,9)
          ċÐ€⁵Ḷ¤    = count occurrences of [0,...,9]
                ”#ẋ = create the list

```

---
Tags: code-golf, ascii-art, classification, statistics, apl
---


title: Drawing a square with an 'x' inside

text:
# Question
Title: Drawing a square with an 'x' inside
Task:

* Make a program that draws the following figure line by line.
* Your program should wait for one-second after drawing each line(it can be longer, just has to be a noticeable difference) .
* Your program can **only** draw line by line (you cannot jump to another point or re-draw over a line)
* Given a positive integer n, produce an art image of the below drawing
* The angle measures should always be the same (regardless of n's value)
* However, each line's length should be 150\*n pixels
* You only need to account for when n = 1, n = 2, n = 3

The picture below shows when `n` = 1

(You don't have to include the angles and side lengths in your drawing - they are just guides)

**Answering** \- Name the language you used followed by its bytes

Example:

> **Java (swing), 500 bytes**

**Scoring**

Good luck!

# Answer
> 3 votes
# Python 2, ~~150~~ ~~140~~ ~~132~~ 120 bytes

*-5 bytes thanks to @Mr.Xcoder*

```
from turtle import*
n=150*input()
for a,b in zip([0,90,30,120,30]+[135]*3+[-75,240],[n]*5+[2**.5*n,n]*2+[n]):rt(a);fd(b)

```

Try it on Trinket modified slightly to run with Python 3

---
Tags: code-golf, graphical-output
---


title: Expand an Array

text:
# Question
Title: Expand an Array
**Expand an array to all directions by duplicating the outer elements**

You will be given two inputs: an array and the expansion degree
For example if I give you `[[1,2,3][4,5,6][7,8,9]]` and `3`, you must output:

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

```

As you can see the given array is in the center and all the outer elements have expanded:
`1` -\> 3 times up, 3 times left and also to every position of the upper left corner
`2`-\> 3 times up
`5`-\> is not an outer element
etc

here are some more test cases to make things clearer

```
Input   [[4,5,6]],0

Output
4 5 6

Input  [[1]],2

Output

1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1
1 1 1 1 1

Input  [[1,2,3]],2

Output
1 1 1 2 3 3 3
1 1 1 2 3 3 3
1 1 1 2 3 3 3
1 1 1 2 3 3 3
1 1 1 2 3 3 3

Input  [[1,2,3][11,22,33][111,222,333][1111,2222,3333]],1

Output
   1       1       2       3       3
   1       1       2       3       3
  11      11      22      33      33
 111     111     222     333     333
1111    1111    2222    3333    3333
1111    1111    2222    3333    3333

```

You can use as many whitespaces as you like.
But the output has to be a `mXn` array just like it is shown here.
You cannot output a list of lists.

This is Shortest answer on bytes wins

# Answer
# Octave, 35 bytes

```
@(a,x)padarray(a,[x x],'replicate')

```

Try it online!
> 4 votes

# Answer
# Matlab, 27 bytes

```
@(a,n)padarray(a,[n,n],'r')

```

The key over the Octave solution is that Matlab accepts partial option strings when they are unambiguous.
> 4 votes

# Answer
# MATL, 10 bytes

```
th2Y5I4$Ya

```

Port of @rahnema1's Octave answer.

**Try it online!**

### Explanation

```
t      % Implicit input: number, n. Duplicate
h      % Concatenate. Gives an array [n,n]
2Y5    % Push 'replicate' (predefined literal). Will be used as an input flag
I      % Push 3. Will be used as equivalent to an input flag
4$     % Specify that the next function will use 4 inputs
Ya     % Call 'padarray' with 4 inputs. This takes the array as implicit
       % input. Number 3 as third input is interpreted as the input flag
       % 'both'. So the function pads the array (first input) by n in each
       % dimension (second input) by replicating the border (third input) in
       % both directions (fourth input). Implicit display

```
> 3 votes

# Answer
# Jelly, 13 bytes

```
;ṫ¥0$¡Ṛ$⁺Zµ⁺G

```

Try it online!
> 2 votes

# Answer
# 05AB1E, ~~33~~ ~~28~~ 23 bytes

```
F2Fø2FR¤¸«]øεD€gZs-ú}ø»

```

Try it online! ~~15~~ 10 bytes of actual code, the rest is formatting the output. Explanation:

```
       ¤                Copy last element
        ¸               Turn it into a list
         «              Concatenate
    2F                  Repeat twice
      R                 Reverse list each time
 2F                     Repeat twice
   ø                    Transpose list each time
F                       Repeat the given number of times
          ]             Close all the loops
           ø            Transpose the array
             D          Duplicate
              €g        Take length of each number
                Z       Get the maximum
                 s-     Subtract each length from the maximum
                   ú    Pad with that number of spaces
            ε       }   For each row (column originally)
                     ø  Transpose back
                      » Join with spaces and newlines

```

Formatting costs 2 bytes if I copy @ErikTheOutgolfer's output format for 12 bytes:

```
F2Fø2FR¤¸«]»

```
> 1 votes

# Answer
# Python 2, ~~138~~ 113 bytes

*-9 bytes thanks to @JonathanFrech*
*-16 bytes thanks to @Lynn*

```
a,n=input()
for e in a[:1]*n+a+n*a[-1:]:print' '.join('%*s'%(len(`max(sum(a,[]))`),n)for n in e[:1]*n+e+n*e[-1:])

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 15 bytes

```
2F2F¤¸².×«R}ø}»

```

Try it online!

Yes, this output format is valid.
> 1 votes

# Answer
# Python 2.7, 74 characters

Pretty straightforward: uses numpy padding and regex to force a return string without brackets. This code returns an anonymous lambda.

```
import numpy,re;lambda a,n:re.sub('[\[\]]', '',str(numpy.pad(a,n,'edge')))

```
> 0 votes

# Answer
# Python 2, ~~94~~ ~~89~~ ~~86~~ 82 bytes

```
a,n=input()
for l in a[:1]*n+a+n*a[-1:]:print' '.join(map(str,l[:1]*n+l+n*l[-1:]))

```

Try it online!
> 0 votes

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


title: The prime frog

text:
# Question
Title: The prime frog
The "prime frog" is a strange animal that jumps between integers, until it arrives on 3 or 19...

---

Your program should accept an integer `n` as input and output the result of the below algorithm (`3` or `19`).

For a given integer `n >= 2`:

1. Let `f` be the position of the frog. It is initially set to `n`
2. if `f = 3` or `f = 19` : the frog stops jumping - halt the program and output `f`.
3. if `f` is prime : the frog jumps to the position `2×f-1`. Go back to step 2.
4. if `f` is composite : let `d` be `f`'s biggest prime divisor. The frog jumps to the position `f-d`. Go back to step 2.

**Examples:**

An example with `n = 5`:

```
5 > 9 > 6 > 3 stop

```

The program should output `3`.

Another example with `n = 23`:

```
23 > 45 > 40 > 35 > 28 > 21 > 14 > 7 > 13 > 25 > 20 > 15 > 10 > 5 > 9 > 6 > 3 stop

```

Again, the program should output `3`.

**Test cases:**

```
10 => 3
74 => 19
94 => 3
417 => 3
991 => 19
9983 => 19

```

You can assume `1 < n < 1000000` (I have checked the program ends for these values).

# Answer
> 15 votes
# Python 2, ~~101~~ ~~93~~ ~~92~~ ~~90~~ ~~88~~ ~~87~~ 85 bytes

```
import sympy
n=input()
while~16&n-3:m=max(sympy.factorint(n));n-=[1-n,m][m<n]
print n

```

Try it online!

# Answer
> 12 votes
# C (gcc),  ~~87~~  65 bytes

```
i,k;f(n){for(i=n;i>1;)for(k=i;k%--i;);n=~16&n-3?f(n-k?:n+n-1):n;}

```

Try it online!

**Explanation:**

```
i,k;
f(n)
{
    for (i=n; i>1;)              // Loop until `k` is prime (the largest positive
                                 // `i` inequal to `k` that divides `k` is 1).
        for (k=i; k%--i;);       // Find the largest factor `k`

    n =                          // Returning like this is undefined behaviour,
                                 // but happens to work with gcc. This can be
                                 // replaced with `return` at the cost of 4 bytes.

        ~16&n-3                  // If `n` is 3 or 19, this expression equals 0 and
                                 // the algorithm halts. Otherwise the function
                                 // calls itself to perform the next iteration.

        ? f(n-k ?: n+n-1)        // If `n-k` is non-zero, n is not prime.
                                 // In this case call `f` with the value of `n-k`.
                                 // (Omitting the second `n-k` between `?` and `:`
                                 // is a gcc extension)
                                 // Otherwise call `f` with `2*n-1`.

        : n;                     // All done, `n` is returned.
}

```

**Portable version (72 bytes):**

```
i,k;f(n){for(i=n;i>1;)for(k=i;k%--i;);return~16&n-3?f(n-k?n-k:n+n-1):n;}

```

Try it online!

**With more appropriate variable names:**

```
f,r;o(g){for(f=g;f>1;)for(r=f;r%--f;);g=~16&g-3?o(g-r?:g+g-1):g;}

```

Try it online!

# Answer
> 10 votes
## Retina, ~~63~~ 62 bytes

*Thanks to Neil for saving 1 byte.*

```
{`^(11+)(?<!^\2+(11+))(?=\1+$)

^(?!(11+)\1+$|111$|1{19}$)1
$_

```

Try it online!

Input and output in unary (the test suite uses decimal for convenience). This solution gets incredibly slow for larger inputs. The `9983` test case times out on TIO.

### Explanation

Due to the `{`, both stages of the program are simply run in a loop until they no longer affect the string. We alternate between a stage processing composites and a stage processing primes. That lets us avoid an actual conditional (which doesn't really exist in Retina). If the current value is the wrong kind for the stage, the stage simply does nothing.

```
^(11+)(?<!^\2+(11+))(?=\1+$)

```

This processes composites. We match a potential divisor with `(11+)`, but then we check that it's not composite with `(?<!^\2+(11+))`, so we only consider prime factors. Due to the greediness of `+`, this prioritise the largest factor. Then we check that this potential divisor is an *actual* divisor by trying to match the rest of the string with repetitions of it, `(?=\1+$)`. This divisor is simply removed from the string, which is how you subtract something in unary.

```
^(?!(11+)\1+$|111$|1{19}$)1
$_

```

This processes primes, except **3** and **19**. The negative lookahead makes sure that the input is not composite, not **3** and not **19**. Then we match a single `1` and replace it with the entire string. This is a unary form of computing **n - 1 + n**, which of course is **2n-1**.

Once we hit **3** or **19**, neither stage can match the string and it will no longer be changed.

# Answer
> 10 votes
# Jelly, 12 bytes

```
_ÆfṂoḤ’$µÐḶṂ

```

Try it online!

### How it works

```
_ÆfṂoḤ’$µÐḶṂ  Maink link. Argument: n

        µ     Combine the links to the left into a chain.
         ÐḶ   Repeatedly call the chain monadically until the results are no longer
              unique. Yield the loop, i.e., the first occurrence of the first
              repeated integer, up to and excluding the repetition.
              Let's call the argument of the chain k.
_Æf             Subtract all prime factors of k from k.
   Ṃ            Take the minimum of the differences. This yields 0 iff k is prime.
     Ḥ’$        Compute 2k-1.
    o           Take the logical OR of the results.
              The result is now a rotation of either [3, 5, 9, 6] or
              [19, 37, 73, 145, 116, 87, 58, 29, 57, 38].
          Ṃ   Take the minimum, yielding either 3 or 19.

```

# Answer
> 7 votes
# Wolfram Language (Mathematica), 65 ~~66~~ ~~68~~ bytes

```
#//.i:Except[3|19]:>If[PrimeQ@i,2i-1,i-#&@@Last@FactorInteger@i]&

```
* *-1 bytes, thanks to Misha Lavrov!*
* *-2 bytes, thanks to Martin!*

Try it online!

Inspired by the tip. Basically, it just recreates the algorithm.

`//.` is `RepeatedReplace` and `/;` is `Condition`. So, the code will replace `i_` (a single quantity) with `If[PrimeQ@i,2i-1,i-#&@@Last@FactorInteger@i]`, until `i!=3&&!=19` evaluates `True`.

Benchmark:

# Answer
> 7 votes
# Husk, 15 bytes

```
Ω€p57§|o←DṠ-o→p

```

Try it online!

## Explanation

```
Ω€p57§|o←DṠ-o→p  Implicit input n.
Ω                Do this to n until
 €p57            you get a prime factor of 57 (which are 3 and 19):
            o→p   Take last element of the prime factors of n
          Ṡ-      and subtract it from n,
     §|           or if this gives 0 (so n is prime),
       o←D        double and decrement n.

```

# Answer
> 6 votes
# 05AB1E, ~~19~~ ~~18~~ 17 bytes

```
[ÐƵηfså#pi·<ëDfθ-

```

Try it online!

**Explanation**

```
[      #            # loop until
 Ð   så             # a copy of the current value is contained in
  Ƶηf               # the unique prime factors of 171
        pi          # if the current value is prime
          ·<        # double and decrement
            ë   -   # else subtract
             Dfθ    # the largest prime factor of a copy of the current value

```

# Answer
> 5 votes
# JavaScript (ES6), ~~73~~ ~~71~~ 69 bytes

```
f=n=>57%n?f(n-(g=(k,d=1)=>++d<k?k%d?g(k,d):g(k/d):d<n?d:1-n)(n)):n%38

```

### Test cases

```
f=n=>57%n?f(n-(g=(k,d=1)=>++d<k?k%d?g(k,d):g(k/d):d<n?d:1-n)(n)):n%38

console.log('10   -> ' + f(10))   // 3
console.log('74   -> ' + f(74))   // 19
console.log('94   -> ' + f(94))   // 3
console.log('417  -> ' + f(417))  // 3
console.log('991  -> ' + f(991))  // 19
console.log('9983 -> ' + f(9983)) // 19
```

### Formatted and commented

```
f = n =>                 // given n
  57 % n ?               // if n is neither 3, 19 or 57 (and assuming that n is > 1):
    f(                   //   do a recursive call to f() with:
      n -                //     n minus
      (g = (k, d = 1) => //     the result of the recursive function g():
        ++d < k ?        //       increment d; if d is less than k:
          k % d ?        //         if d is not a divisor of k:
            g(k, d)      //           recursive call to g() with k and d unchanged
          :              //         else:
            g(k / d)     //           recursive call to g() with k = k / d, d = 1
        :                //       else, d is now the highest prime divisor of n:
          d < n ?        //         if d is less than n:
            d            //           n is composite: return d, which results in f(n - d)
          :              //         else:
            1 - n        //           n is prime: return 1 - n, which results in f(2n - 1)
      )(n)               //     initial call to g()
    )                    //   end of recursive call to f()
  :                      // else:
    n % 38               //   return n % 38 (gives 19 as expected if n = 57)

```

# Answer
> 4 votes
# Jelly, ~~23~~ 19 bytes

*-4 bytes from miles.* Still longer than 05AB1E, though.

```
Ḥ’$_Æf$ÆP?Ṫµḟ3,19$¿

```

Try it online!

# Answer
> 4 votes
# Python 2, ~~110~~ ~~105~~ ~~103~~ 101 bytes

*-2 bytes thanks to @Lynn*

```
f=lambda n,i=2,k=0:i/n and(n*(n&~16==3)or f((2*i-1,k-i)[k>0]))or n%i and f(n,i+1,k)or f(n/i,2,k or n)

```

Try it online!

---

# Python 2, ~~116~~ ~~112~~ 105 bytes

```
f=lambda n,i=2:i/n*i or n%i and f(n,i+1)or f(n/i)
n=input()
while~16&n-3:n=[2*n-1,n-f(n)][f(n)<n]
print n

```

Try it online!

# Answer
> 4 votes
# MATL, ~~22~~ 21 bytes

*Thanks to @Giuseppe for removing 1 byte!*

```
`tZp?Eq}tYfX>-]tI19h-

```

Try it online! Or verify all test cases.

### Explanation

```
`           % Do...while
  t         %   Duplicate. Takes (implicit) input the first time
  Zp        %   Is it prime?
  ?         %   If so
    Eq      %     Times 2, minus 1
  }         %   Else
    t       %     Duplicate
    YfX>-   %     Prime divisors, maximum, subtract
  ]         %   End
  t         %   Duplicate
  I19h      %   Push array [3 19]
  -         %   Subtract, element-wise. The result is truthy if and only if
            %   it doesn't contain any zero
            % End (implicit). Next iteraton if top of the stack is truthy
            % Display (implicit)

```

# Answer
> 4 votes
# Haskell - 154 bytes

```
f 3=3
f 19=19
f n
 |(c==[1])=f$2*n-1
 |True=f$n-head c
 where c=z n;v b=reverse[x|x<-[1..(b-1)],b`rem`x==0];z j=case v j of[1]->[1];s->filter((==[1]).v)$s

```

Probably missing some golf tricks here, this is my first attempt at haskell golf.

# Answer
> 3 votes
# Neim, ~~17~~ 16 bytes

```
ͻY÷DΞᚫ<#D

```

Explanation:

```
ͻ                   Start infinite loop
 D                  Duplicate
  Y                 Push 57
                   Prime factors: [3 19]
                   If the second-to-top of stack is in the list
      ÷             Break the loop
       D            Duplicate
        Ξᚫ<       If prime, double and decrement
            #D   Otherwise, subtract the largest prime factor

```

Try it online!

# Answer
> 3 votes
# Java 8, ~~140~~ ~~135~~ ~~134~~ 94 bytes

```
n->{for(int f,t,m=0;57%n>0;n=f>n?2*n-1:n-m)for(t=n,f=1;f++<t;)for(;t%f<1;t/=m=f);return n%38;}

```

-5 bytes converting recursive Java 7 method to Java 8 lambda with loop.
-1 byte implicit thanks to *@Arnauld*'s JavaScript answer by changing `n!=3&n!=19` and `return n;` to `57%n>0` and `return n%38;`.
~~I think it should be possible to somehow combine the two loops and check if `n` is a prime, and get it's largest prime factor at the same time, but I can't figure it out (yet). So this will be the initial version for now.~~
-40 whopping bytes thanks to @Nevay, by doing what I couldn't do: combining the loops to check for primes and largest prime factor at once.

**Explanation:**

Try it here (executes even `999999` in under 1 second).

```
n->{                  // Method with integer as both parameter and return-type
  for(int f,          //  Flag-integer
          t,          //  Temp-integer
          m=1;        //  Max prime factor integer, starting at 0
      57%n>0;         //  Loop (1) as long as `n` is not 3, not 19 and not 57:
      n=f>n?          //    After every iteration: if `f` is larger than `n`:
         2*n-1        //     Change `n` to `2*n-1`
        :             //    Else:
         n-m)         //     Change `n` to `n-m`
    for(t=n,          //   Reset `t` to `n`
        f=1;          //   Reset `f` to 1
        f++<t;)       //   Inner loop (2) from 2 to `t` (inclusive)
      for(;t%f<1;     //    Inner loop (3) as long as `t` is divisible by `f`
        t/=m=f;       //     Set `m` to `f`, and set `t` to `t/f`
      );              //    End of inner loop (3)
                      //   End of inner loop (2) (implicit / single-line body)
                      //  End of loop (1) (implicit / single-line body)
  return n%38;        //  Return `n%38`, which is now either 3 or 19
}                     // End of method

```

# Answer
> 3 votes
# \+ numbers, ~~102~~ 99 bytes

```
function(n){while(!n%in%c(3,19))n="if"(isPrime(n),2*n-1,n-max(primeFactors(n)))
n}
library(numbers)

```

Try it online!

R isn't known for short built-ins, and even the packages follow suit!

# Answer
> 3 votes
# Bash, 73 bytes

```
((57%$1))&&$0 $[(x=$1-`factor $1|sed 's/.* //'`)?x:2*$1-1]||echo $[$1%38]

```

Try it online! Modified slightly to work on TIO.

Recursively calls its own script file using `$0`, ~~which does not work in TIO because it must be ran as `./filename.sh`~~. Accepts input as command-line argument.

Uses the same modulus trick as @Arnauld's JS answer.

## Test Cases

```
$ for t in 5 23 10 74 94 417 991 9983;{ echo -n "$t -> "; ./prime-frog.sh $t; }
5 -> 3
23 -> 3
10 -> 3
74 -> 19
94 -> 3
417 -> 3
991 -> 19
9983 -> 19

```

# Answer
> 2 votes
# Python 3, 97 bytes

```
f=lambda n:n*(n&-17==3)or f(n-max(k*all(n%k<k%j for j in range(2,k))for k in range(n+1))or 2*n-1)

```

Try it online!

# Answer
> 1 votes
# Pyth, 19 bytes

```
.W!/P57H?P_ZtyZ-ZeP

```

**Verify all the test cases!**

The Husk answer inspired me to save 2 bytes (`,3 19` to `P57`).

## How this works

```
.W!/P57H?P_ZtyZ-ZeP  - Full program.

.W                   - Functional while. While A(value) is truthy, value = B(value). Returns the last value.
    P57              - The prime factors of 57 ([3, 19]).
   /   H             - Count the occurences of the current value.
  !                  - Logical NOT. 0 -> Truthy, anything else -> Falsy.
        ?P_Z         - If the current value is prime, then:
            tyZ        - Double the current value, decrement.
               -ZeP    - Else, Subtract the maximal prime factor of the current value from itself.
                     - Print implicitly.

```

# Answer
> 1 votes
# PowerShell, ~~150~~ 126 bytes

```
for($n="$args";57%$n){$a=$n;$d=for($i=2;$a-gt1){if(!($a%$i)){$i;$a/=$i}else{$i++}};if($n-in$d){$n+=$n-1}else{$n-=$d[-1]}}$n%38

```

Try it online! (warning: slow for bigger numbers)

Iterative method. PowerShell doesn't have any prime factorization built-ins, so this borrows code from my answer on Prime Factors Buddies.

First is our `for` loop. The setup sets `$n` to be the input value, and the conditional keeps the loop going so long as `57%$n` is non-zero (thanks to Arnauld for that trick). Inside the loop we first get a list of prime factors of `$a` (set to `$n`). This is the code borrowed from Prime Factors Buddies. If the input `$a` is already prime, this will return just `$a` (important later). That (potentially just `$a`) gets stored into `$d`.

Next is an `if`/`else` conditional. For the `if` part, we check whether `$n` is `-in` `$d`. If it is, that means that `$n` is prime, so we take `$n=2*$n-1` or `$n+=$n-1`. Otherwise, it's composite, so we need to find the largest prime factor. That means we need to take the last one `[-1]` of `$d` and subtract that from `$n` with `$n-=`. This works because we're looping up from `2` and thus the last element of `$d` is already going to be the largest.

Once we're done looping, we just place `$n%38` (again, thanks Arnauld) on the pipeline and output is implicit.

# Answer
> 1 votes
# APL (Dyalog Unicode), ~~113~~ ~~90~~ 59 bytes

```
⎕CY 'dfns'
g←{1pco ⍵:f(2×⍵)-1⋄f⍵-⊃⌽3pco ⍵}
f←{⍵∊3 19:⍵⋄g ⍵}

```

Try it online!

~~TIO works with values up to ~3200. Tested on my PC for the last test case. To test on TIO, just add `f value` to the bottom of the code.~~ Doesn't apply anymore, thanks to @Adám for pointing out that my primality checking algorithm was really bad and supplying me with a replacement; also for the 23 byte save.

Edited to fix byte count.

### How it works

```
⎕CY 'dfns'                      # Imports every Defined Function, which is shorter than importing just the function I used (pco).

g←{1pco ⍵:f(2×⍵)-1⋄f⍵-⊃⌽3pco ⍵}
g←                              # define g as
   1pco ⍵:                      # if the argument ⍵ is prime
          f(2×⍵)-1              # Call f over 2×⍵-1
                  ⋄f            # else, call f over
                    ⊃           # the first element of the
                      3pco ⍵    # list of prime factors of ⍵
                     ⌽          # reversed

f←{⍵∊3 19:⍵⋄g ⍵}
f←                              # Define f as
   ⍵     :                      # if the argument ⍵
    ∊                           # is in
     3 19                       # the list [3, 19]
          ⍵                     # return the argument ⍵
           ⋄                    # else
            g ⍵                 # call g over the argument ⍵

```

# Answer
> 1 votes
# Axiom, 93 bytes

```
h(n)==(repeat(n=3 or n=19 or n<2=>break;prime? n=>(n:=2*n-1);n:=n-last(factors(n)).factor);n)

```

test:

```
(4) -> [[i,h(i)] for i in [10,74,94,417,991,9983]]
   (4)  [[10,3],[74,19],[94,3],[417,3],[991,19],[9983,19]]
                                                  Type: List List Integer

```

There would be 68 bytes function

```
q x==(n<4=>3;n=19=>n;prime? n=>q(2*n-1);q(n-last(factors n).factor))

```

but for n=57991 (if I remember well) it goes out the stack space reserved.

# Answer
> 0 votes
# Python 2, 93 bytes

Port from TFeld's answer without external libs.

```
n=input()
while~16&n-3:
 f=n;i=2
 while i<f:
	if f%i:i+=1
	else:f/=i
 n-=[1-n,f][f<n]
print n

```

Try it online!

---
Tags: code-golf, sequence, primes
---


title: Two First Names

text:
# Question
Title: Two First Names
A person has two first names if their last name is also a common first name. You are tasked with determining which full names in a list are two first names.

```
John Smith
John Doe
Luke Ryan
Ryan Johnson
Jenna Jackson
Tom John

```

Any name that occurs in the first name column is potentially a first name. If the number of occurrences of the name in the first name column is *greater* than the number of occurrences in the last name column, it is **definitely** a first name.

In the above list, `John` appears twice in the first names and once in the last names so it is definitely a first name. `Ryan` appears once in the first and once in the last so it is (probably) a first name.

Therefore, `Tom John` definitely has two first names and `Luke Ryan` probably does.

Given the above list, your code should output the follow:

```
Luke Ryan has two first names
Tom John definitely has two first names

```

---

**Input**

As mentioned above, your code will take in a list of full names (from standard input, one per line) separated by spaces. Names can include hyphens or apostrophes, but you will never be given a first or last name that includes spaces (ie no `Liam De Rosa`, but `Liam De-Rosa` or `Liam De'Rosa` are fair game. In other words, names will match `[-'A-Za-z]+`.

Each full name will be unique (ie `John Smith` will not appear twice).

**Output**

Print full names names (once per line) followed by either `has two first names` or `definitely has two first names` if they meet the criteria above. Names should only be printed once.

Names that are not two first names do not need to be printed.

You must preserve the case and special characters of the name.

**Examples**

Input

```
Madison Harris
Riley Hudson
Addison Hills
Riley Phillips
Scott Hill
Levi Murphy
Hudson Wright
Nathan Baker
Harper Brooks
Chloe Morris
Aubrey Miller
Hudson Lopez
Samuel Owen
Wyatt Victoria
Brooklyn Cox
Nathan Murphy
Ryan Scott

```

Output

```
Riley Hudson definitely has two first names
Ryan Scott has two first names

```

Input

```
Owen Parker
Daniel Hall
Cameron Hall
Sofia Watson
Mia Murphy
Ryan Jones
Emily Ramirez

```

Output

```
[no output]

```

Input

```
Olivia Robinson
Jacob van-Dyke
Jacob Ella
Brayden De'Rosa
Levi Brook
Brook Bella
Ella Hill
Ella Anderson
Brook-Anne van-Dyke

```

Output

```
Jacob Ella definitely has two first names
Levi Brook has two first names

```

**Notes and Scoring**

Good luck!

# Answer
# Java (OpenJDK 8), ~~238~~ ~~222~~ ~~221~~ ~~220~~ 212 bytes

```
l->{for(String n:l){int k=0,j=0,q=0;for(String b=n.split(" ")[1];k<l.length;j+=l[k++].matches(b+" .*")?1:0)q+=l[k].endsWith(" "+b)?1:0;if(j>0)System.out.println(n+(j>q?" definitely":"")+" has two first names");}}

```

Try it online!
> 6 votes

# Answer
# Python 2, ~~141~~ ~~137~~ ~~132~~ 130 bytes

*-2 bytes thanks to @JonathanFrech*

```
n=map(str.split,input())
for f,l in n:
 c=cmp(*[x.count(l)for x in zip(*n)])
 if~c:print f,l,'definitely '*c+'has two first names'

```

Try it online!
> 6 votes

# Answer
# Perl 5, ~~120~~ 118 + 2 (`-al`) = 120 bytes

```
$f{$F[0]}++;$l{$k{$_}=$F[1]}++}{map{print$_.' definitely'x($f{$t}>$l{$t})." has two first names"if$f{$t=$k{$_}}}keys%k

```

Try it online!
> 3 votes

# Answer
# AWK, ~~127~~ 123 bytes

```
{a[$1]++
b[L[++X]=$2]++
N[X]=$0}END{for(;++i<=X;)if(A=a[L[i]])print N[i],(b[L[i]]<A?"definitely ":"")"has two first names"}

```

Saving 1 byte by not using the built-in `NR` value.

Try it online!
> 3 votes

# Answer
# Ruby, ~~105~~ 129 bytes

+24 bytes because I missed part of the spec

```
->a{a.map{|e|l=e[r=/\S+$/];i=a.count{|n|n[/\S+/]==l};e+"#{' definitely'if i>a.count{|n|n[r]==l}} has two first names"if i>0}-[p]}

```

Try it online!
> 3 votes

# Answer
# Python 2, ~~140~~ ~~127~~ ~~122~~ 131 bytes

```
N=map(str.split,input())
F,L=zip(*N)
for f,l in N:
 if l in F:print f,l,'definitely '*(F.count(l)>L.count(l))+'has two first names'

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 144 bytes (Work in progress)

```
|vy#Dθˆн})©gF®®NèQO¯®NèQO-D®¯NèQO¯¯NèQO-D.À>0›s>0›&i0›s0›&i®Nè" "¯Nè" defínítely has two fírst names"J,ë®Nè" "¯Nè" has two fírst names"J,}ë\\}}´

```
> 2 votes

# Answer
# 05AB1E, ~~53~~ 51 bytes

```
|UXv“€°‚•€ÛŒî“D„´Î ì)yð«ìõ¸ìXð¡øεy#θQO}`.S>sèˆ}¯õK»

```

Try it online!

### Explanation

```
|                                                       # Take inputs as array
 UX                                                     # Store in X and push X to stack
   v                                          }         # For each name, do
    “€°‚•€ÛŒî“D                                         #   Push "has two first names" twice
               „´Î ì                                    #   Prepend "definitely " to one of those
                    )yð«ì                               #   Wrap both strings in an array and prepend (name + " ") to each
                         õ¸ì                            #   Prepend " " to array
                            Xð¡øεy#θQO}`                #   Get occurences in input first and last names
                                        .S>             #   0 for not first name, 1 for first name and 2 for definitely first name
                                           sèˆ          #   Get string at that index and push to global array
                                               ¯õK»     # Output global array, 1 string per line

```

### Or ~~51~~ 49 bytes, assuming standard I/O Rules (input and output as arrays)

```
UXv“€°‚•€ÛŒî“D„´Î ì)yð«ìõ¸ìXð¡øεy#θQO}`.S>sèˆ}¯õK

```

Try it online!
> 2 votes

# Answer
# PHP, 172 bytes

```
for(;$s=$argv[++$i];$f[$a]++,$l[$n[]=$b]++)[$a,$b]=explode(" ",$s);for(;$b=$n[+$k++];)$f[$b]<$l[$b]||print$argv[$k].($f[$b]>$l[$b]?" definetly":"")." has two first names
";

```

takes names as separate command line arguments.

Run with `-nr` or try it online.
> 1 votes

# Answer
# Python 3, 187 bytes

```
n={}
c=[]
while 1:
 try:a,b=input().split();n[a]=n.get(a,0)+1;n[b]=n.get(b,0)-1;c+=[[a,b]]
 except:[print(a,b,'definitely has two first names'[(n[b]>0)*11:])for a,b in c if n[b]>=0];break

```
> 0 votes

# Answer
# , 207 bytes

```
n=readLines("stdin")
s='definitively has two first names\n'
x=matrix(t(unlist(sapply(n,strsplit,' '))),2)
j=1
for(i in n){a=apply(x[2,j]==x,1,sum)
b=a[2]>=a[1]
if(a[1])cat(paste(i,substr(s,14*b,34)))
j=j+1}

```

Try it online!
> 0 votes

# Answer
## JavaScript (ES6), 149 bytes

```
s=>s.replace(/(.*) (.*)\n/g,(_,t,u)=>g(`
${u} `)>1?t+` ${u}${v>g(` ${u}
`)?` definitely`:``} has two first names
`:``,g=u=>v=`
${s}`.split(u).length)

```

I/O includes trailing newline. Largely inspired by @RobertoGraham's answer.
> 0 votes

# Answer
# Haskell, ~~144~~ ~~140~~ 139 bytes

```
g.map words.lines
g s=id=<<[n++' ':f++[c|c<-" definitely",t 0>t 1]++" has two first names\n"|[n,f]<-s,let t i=filter(==f)$map(!!i)s,[]<t 0]

```

Try it online!
> 0 votes

# Answer
## PowerShell, 176 bytes

```
$n=$args
$s=" has two first names"
$f=$n|%{$_.Split()[0]}
$l=$n|%{$_.Split()[1]}
$i=0
$l|%{switch(($f-match$_).count){{$_-eq1}{$n[$i]+$s}{$_-gt1}{$n[$i]+" definitely"+$s}}$i++}

```
> 0 votes

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


title: Advice for ruby

text:
# Question
Title: Advice for ruby
How can I shorten:

```
p=gets.to_i
a=gets
b=gets.to_i

```

If my input is an integer, followed by a string, followed by an integer?

# Answer
> 7 votes
## Use ARGV ($\*) and mass assignment

*(disclaimer: I don't know Ruby, but this works on TIO)*

```
p,a,b=$*
p=p.to_i
b=b.to_i

```

~~28~~ 26 bytes instead of 30 (thanks to Snack for pointing out the $\* trick)

# Answer
> 6 votes
# Use a lambda

Answers are typically allowed as lambda functions with your input/output being the parameters/return value of the lambda, so you can do this:

`->p,a,b{...}`

If you assigned this to a variable `f` then it would be called as

`f[p,a,b]`

It's generally fine to assume the types of the inputs as well, but to be safe you can mention it in your answer.

Relevant meta post about acceptable input/output methods

# Answer
> 6 votes
If you need a full program with stdin/stdout io for some reason, the shortest you can do is use the `-n` flag to shorten one call to `gets.to_i` to `eval$_`:

```
p=eval$_
a=gets
b=gets.to_i

```

The `-n` flag surrounds your code with `while gets ... end`, so the program will loop if more input is supplied than your program consumes.

---
Tags: code-golf, tips, ruby
---


title: Create a universal integer sequence

text:
# Question
Title: Create a universal integer sequence
### Definition

Let's call an (infinite) integer sequence universal if it contains every finite integer sequence as a contiguous subsequence.

In other words, the integer sequence **(a1, a2, …)** is universal if and only if, for each finite integer sequence **(b1, …, bn)**, there is an offset **k** such that **(ak+1, …, ak+n) = (b1, …, bn)**.

The sequence of positive prime numbers, for example, is not universal, among others for the following reasons.

* It doesn't contain any negative integers, **1**, or composite numbers.
* Although it contains **3**, it does not contain the contiguous subsequence **(3, 3, 3)**.
* Although it contains **2** and **5**, it does not contain the contiguous subsequence **(2, 5)**.
* Although it contains the contiguous subsequence **(7, 11, 13)**, it does not contain the contiguous subsequence **(13, 11, 7)**.

### Task

Pick *any* single universal integer sequence **(a1, a2, …)** and implement it in a programming language of your choice, abiding to the following rules.

* You can submit a full program or a function.
* You have three options for I/O:

1. Take no input and print or return the entire sequence.
    2. Take an index **n** as input and print or return **an**.
    3. Take an index **n** as input and print or return **(a1, …, an)**.
* For I/O options *2* and *3*, you may use **0**-based indexing if you prefer.
* Your submission must be deterministic: if run multiple times with the same input, it must produce the same output.

In addition, unless it's immediately obvious, please prove that the sequence you picked is universal. Your proof may not depend on unproven conjectures.

Standard rules apply. May the shortest code in bytes win!

# Answer
> 14 votes
# Husk, 5 bytes

This prints an infinite list

```
ΣṖ…İ±

```

Try it online! or find the first index of your sequence. (Takes a lot of memory for most sequences)

### Explanation:

```
   İ±   Infinite list [1,-1,2,-2,3,-3,4,-4,5,-5...]
  …     Rangify       [1,0,-1,0,1,2,1,0,-1,-2,...]
 Ṗ      Powerset
Σ       Concatenate

```

In Husk  behaves nicely for infinite lists. You can see it's behaviour here

# Answer
> 9 votes
# Python 2, ~~49~~ ~~46~~ 43 bytes

```
def f(n):d=len(`n`);return n/d**(n%d)%d-d/2

```

`f(n)` returns **an** only. This uses the smallest digit of `n` in base `d` to extract one of the higher digits.

Try it online! This script (courtesy of Dennis) takes any finite sequence and gives you an `n` where that sequence begins.

## Explanation

```
n/d**(n%d)%d-d/2
     (n%d)         least significant digit of n
n/d**(   )%d       get n%d-th digit of n
            -d/2   offset to get negative values

```

For example, for `n` in the range `3141592650` to `3141592659`, `d=10` and the last digit of `n` selects one of the other digits. Then we add `-d/2` to get negative values.

```
n%d:       0  1  2  3  4  5  6  7  8  9
f(n)+d/2:  0  5  6  2  9  5  1  4  1  3
f(n):     -5  0  1 -3  4  0 -4 -1 -4 -2

```

Standalone alternative, also 43 bytes:

```
n=input();d=len(`n`);print n/d**(n%d)%d-d/2

```

# Answer
> 5 votes
# Brachylog 2, 11 bytes

```
≜~×-₂ᵐ~ȧᵐ≜∋

```

Try it online!

I also tried an algorithm using additive partitions on a list, but it wasn't any shorter. This is a generator that produces an infinite stream of integers as output; the TIO link has a header to print the first ten thousand of them.

## Explanation

The program starts off by trying all possible integers in sequence ( tries all remaining possibilities, for integers by default). That's 0, 1, -1, 2, -2, etc. (although the negative integers don't reach the end of the program). This is the only "infinite" step of the program; all the others are finite.

then generates all possible factorisations of the integer, treating different orders as different, and using only values from 2 upwards (so there are only finitely many); note that composite numbers are allowed in the factorisation, not just primes. This means that all possible sequences of integers ≥ 2 will be generated by this step at some point in the execution of the function (as such a sequence necessarily has some product, and that product will be generated at some point by the initial ).

We then need to map the set of those sequences onto the set of all integer sequences, which is done in two steps: subtracting 2 (`-₂`) from each element (), giving us the set of all nonnegative integer sequences, then taking plus or minus (, i.e. "a value whose absolute value is") each element (). The latter step is obviously nondeterministic, so Brachylog treats it as a generator, generating all possible lists whose elements are plus or minus the corresponding element of the input list. This means that we now have a generator for all possible integer sequences, and it generates them in an order that means they're all generated (specifically, the order that you get if you take the absolute value of each element, add 2 to each element, and then order by the product of the resulting elements).

Unfortunately, the question wants a single sequence, not a sequence of sequences, so we need two more commands. First,  requests Brachylog to explicitly *generate* the sequence of sequences strictly (as opposed to producing a data structure describing the concept of a sequence generated via this method, and not actually generating the sequences until necessary); this both happens to make the program faster in this case, and ensures that the output is produced in the requested order. Finally,  causes the generator to output the elements of the individual sequences one at a time (moving onto the next sequence once it's output all elements of the previous one).

The end result: each possible integer sequence gets generated and output, one element at a time, and all concatenated together into a single universal sequence.

# Answer
> 4 votes
# Pyth - 11 bytes

`n`th power cartesian product of `[-n, n]`, for all `n`.

```
.V1js^}_bbb

```

Try it online here (finitely).

# Answer
> 4 votes
# Python 2, ~~100~~ 99 bytes

* Saved one byte thanks to ovs; iterating over an `itertools` built-in to indefinitely loop.

```
from itertools import*
for n in count():
 for P in permutations(range(-n,n)*n):
	for p in P:print p

```

Try it online!

Indefinitely prints all permutations of the `n`-times repeated integer range `[-n; n)` for all nonnegative integers `n`.
You can search for the first offset `k` for any subsequence using this modified version.

# Answer
> 2 votes
# Perl 6, 91 bytes

```
loop (my$i=1;;$i++){my@n=(-$i..$i);my@m=@n;loop (my$k=1;$k <$i;$k++){@m=@m X@n;};print @m;}

```

Try it online!

This uses a similar method to some of the other answers. It uses Cartesian products to print the elements of `(-1,0,1)`, then all ordered pairs of the elements in `(-2,-1,0,1,2)`, then all ordered triplets of the elements in `(-3,-2,-1,0,1,2,3)`, etc.

I'm new to Perl, so there might be more golfing that could be done.

More readable version:

```
loop (my $i = 1; ; $i++) {
  my @n = (-$i..$i);
  my @m = @n;
  loop (my $k=1; $k <$i; $k++) {
    @m = @m X @n;
  }
  print @m;
}

```

---
Tags: code-golf, math, sequence, integer
---


title: Tips for golfing in Applescript

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

# Answer
The `of` operator is used to get a property from an object:

```
log words of "Hello World"

```

But in many cases you can use `'s` as a shortcut to save 1 character:

```
log "Hello World"'s words

```
> 6 votes

# Answer
Some words have shorter synonyms. For example, `application` can be written as `app`\*, and `string` can be written as `text`.

Also, `every <noun>` can be written as simply the plural, as in `characters of "hello world"` (or `"foo"'s characters`).

\*Although Script Editor's compiler will change it back.
> 5 votes

# Answer
The Applescript Editor is a handy little IDE which syntax-highlights and beautifies your code. However, for the purposes of golfing, it is counterproductive as it adds indentation and superfluous keywords, e.g. after `end` statements. For example:

```
repeat with w in "Hello World"'s words
log w
end

```

becomes the following when pasted into the Applescript Editor and compiled/run:

```
repeat with w in "Hello World"'s words
    log w
end repeat

```

Obviously the first snippet is better for the purposes of golfing.
> 4 votes

# Answer
`tell` blocks are common in Applescript:

```
tell application "TextEdit"
    activate
end tell

```

However to save space the following is equivalent, when the inside of the `tell` block is just one line:

```
tell application "TextEdit" to activate

```
> 4 votes

# Answer
### Quotation Required Operation

For any operation that requires a quote to do something, i.e.

```
log "Hello World!"
```

You can shorten to

```
log"Hello World!"
```

### Repeating

In repeat loops, one can entirely remove the word "times".

```
repeat x times
end
```

versus

```
repeat x
end
```

### \<= and \>=

Any time these operators are called, you can replace them with  and , respectively. While this may not reduce byte count (unless special byte counting conventions are implemented, which I suggest), it *does* reduce character count.

### Grabbing from STDIN

You can grab from STDIN in with the following characters:

```
on run argv
end
```

### Exiting quickly

If you need to exit a code quickly (for whatever reason, i.e. preventing excessive `if`s)...

```
quit
```
> 3 votes

# Answer
Applescript allows some extra keywords to be inserted to help readability:

```
log the words of "Hello World"

```

But the `the` here is completely superfluous and may be omitted for a 4 character saving:

```
log words of "Hello World"

```
> 2 votes

# Answer
### Bracket Shortening

Similar to the post about quotations, I realized later that you can also shorten things like this:

```
if "a"=character 1 of (x as string) then return {true, true}
```

to

```
if"a"=character 1 of(x as string)then return{true,true}
```

It'll space out brackets for you too. In this example, I save 5 bytes.
> 2 votes

# Answer
## Considering...

In questions that require case sensitivity, it can be difficult to actually deal with cases.

### UNTIL NOW:

```
considering case
    (something to do with case sensitive stuff)
end considering
```

I didn't actually know this keyword until I really needed it. Using the other tips in this tips page, we can reduce this down to:

```
considering case
(something to do with case sensitive stuff)
end
```

It does require a full statement, as far as I know. (I've tried a lot of things.) See this page for more details.
> 2 votes

# Answer
In a few exceptional cases, the «double angle brackets» or «double chevrons» might be shorter than the English name of a command, parameter, or constant.

The chevron-encoded form would shrink the AppleScript to delete the clipboard from 20 to 16 characters:

```
set the clipboard to  -- 20
«event JonspClp»      -- 16

```

It would drop 2 characters when fetching text from a dialog (as happens in metronome and Pi Day):

```
(display dialog""default answer"")'s text returned  -- 46
(display dialog""default answer"")'s«class ttxt»    -- 44

```

(You might prefer to avoid the dialog and use the command-line arguments of osascript(1), if you have at least Mac OS X 10.4.)

With a US keyboard, « is option-\ and » is option-shift-\\. A command `«event abcdefgh»` has 16 characters. A parameter or constant `«class abcd»` has 12 characters.

The chevron-encoded form is almost always too long for golf. Here is an example without double angle brackets:

```
set x to open for access"output"write permission 1
write"One line of text
"to x
close access x

```

And the same with them:

```
set x to«event rdwropen»"output"given«class perm»:1
«event rdwrwrit»"One line of text
"given«class refn»:x
«event rdwrclos»x

```

Changing `_open for access` (16) to `«event rdwropen»` (16) was neutral. Changing `write permission_` (17) to `given«class perm»:` (18) cost 1 character. The other double angle brackets cost more.

To use double angle brackets, you need to know the magic 4-letter or 8-letter code. I found some codes by saving a script file from Script Editor, then opening it in a hex editor. I ran `emacs` in a terminal and used `M-x hexl-find-file`. I found and edited some codes, like `JonspClp` into `JanspClp`, and `ttxt` into `atxt`. I then saved the file and reopened it in Script Editor. `«event JanspClp»` and `«class atxt»` appeared in the script.

A document titled *AppleScript Terminology and Apple Event Codes Reference* lists some codes. I found a copy of it at https://applescriptlibrary.wordpress.com/

Script Editor will translate double angle brackets to English before saving your script. For chevron deference, you must write your script in another text editor, like TextEdit. Save the script as a plain text file in the Mac OS Roman (or MacRoman) encoding. Mac OS X prefers that you name the file with an .applescript suffix.

If you count bytes, MacRoman has 1 byte per character, so each « or » counts as 1 byte.
> 2 votes

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


# Question
Title: Make two numbers co-prime while preserving their least common multiple
Given two positive integers `a` and `b`, output two positive integers `c` and `d` such that:

* `c` divides `a`
* `d` divides `b`
* `c` and `d` are co-prime
* the least common multiple of `c` and `d` equals the least common multiple of `a` and `b`.

If there are more than one possible answers, you can output only one or all of them.

Test cases:

```
 a  b  c  d
12 18  4  9
18 12  9  4
 5  7  5  7
 3  6  1  6 or 3 2
 9  9  9  1 or 1 9
 6 15  2 15 or 6 5
 1  1  1  1

```

This is . Shortest answer in bytes wins.

# Answer
# Jelly, ~~21~~ 13 bytes

```
ÆEz®0iṂ$¦€ZÆẸ

```

Try it online!

> If **a = 2A · 3B · 5C · …** and **b = 2α · 3β · 5γ · …**, then we compute
>
> * **c = 2A\>α?A:0 · 3B\>β?B:0 · 5C\>γ?C:0 · …**
> * **d = 2A\>α?0:α · 3B\>β?0:β · 5C\>γ?0:γ · …**
>
> Now **lcm(c, d) = 2max(A\>α?A:0, A\>α?0:α) · … = 2max(A, α) · 3max(B, β) · … = lcm(a, b)**
>
> and **gcd(c, d) = 2min(A\>α?A:0, A\>α?0:α) · … = 20 · 30 · 50 · … = 1**.

In other words: start from **(c, d) = (a, b)**. Then, for each prime, divide that prime *all the way out* of the factorization of either **c** or **d**: whichever has the smallest exponent for that prime. (In this implementation, in case of a tie, **c** loses its exponent.)

So if **a = 2250 = 21 · 32 · 53** and **b = 360 = 23 · 32 · 51**,

then **c = 20 · 30 · 53 = 125** and **d = 23 · 32 · 50 = 72**.

Jonathan Allan golfed down a whopping 8 bytes! Thank you~
> 7 votes

# Answer
# R, ~~143~~ ~~139~~ 123 bytes

```
f=function(a,b,q=1:(a*b))for(i in 1:a)for(j in 1:b)if(!a%%i+b%%j&max(q[!i%%q+j%%q])<2&i*j==min(q[!q%%a+q%%b]))cat(i,j,"\n")

```

(Thanks to @Giuseppe for those 19 bytes off!)

With indentations, newlines and some explanations:

```
f=function(a,b,
           q=1:(a*b)) #Defined as function arguments defaults to avoid having to use curly brackets
    for(i in 1:a)
        for(j in 1:b)
            if(!a%%i + b%%j & #Is a divided by c and b divided by d
               max(q[!i%%q+j%%q])<2 & #Are c and d coprimes
               i*j==min(q[!q%%a+q%%b])) #Is this the same lcm
                   cat(i,j,"\n") #Then print

```

Test cases:

```
> f=function(a,b,q=1:(a*b))for(i in 1:a)for(j in 1:b)if(!a%%i+b%%j&max(q[!i%%q+j%%q])<2&i*j==min(q[!q%%a+q%%b]))cat(i,j,"\n")
> f(5,7)
5 7
> f(12,18)
4 9
> f(6,15)
2 15
6 5
> f(1,1)
1 1

```
> 4 votes

# Answer
# Husk, 10 bytes

```
→ÖF§-⌋⌉ΠmḊ

```

Brute force. Takes and returns lists, and works for more than two numbers too. Try it online!

## Explanation

```
→ÖF§-⌋⌉ΠmḊ  Implicit input, say [6,15]
        mḊ  Map divisors: [[1,2,3,6],[1,3,5,15]]
       Π    Cartesian product:[[1,1],[2,1],[1,3],[2,3],[3,1],[1,5],[3,3],[6,1],[1,15],[2,5],[3,5],[6,3],[2,15],[6,5],[3,15],[6,15]]
 Ö          Sort by
  F         reduce by
     ⌉      lcm
   -⌋       minus gcd: [[1,1],[3,3],[2,1],[1,3],[3,1],[6,3],[1,5],[2,3],[6,1],[2,5],[3,15],[1,15],[3,5],[6,15],[2,15],[6,5]]
→           Get last element: [6,5]

```
> 4 votes

# Answer
# Mathematica, 82 bytes

```
#&@@Select[Subsets[Flatten@Divisors[{t=#,r=#2}],{2}],GCD@@#==1&&LCM@@#==t~LCM~r&]&

```
> 3 votes

# Answer
# MATL, ~~17~~ 16 bytes

```
&YFt&X>2:!=*^!Xp

```

Try it online!

Same method as Lynn's Jelly solution

It's been a while since I've used any MATL (or matlab for that matter) so many improvements are likely possible.
> 3 votes

# Answer
# JavaScript (ES6), ~~90~~ ~~84~~ 80 bytes

Takes input in currying syntax `(a)(b)` and returns an array of 2 integers.

```
a=>g=(b,c=1)=>(G=(a,b)=>b?G(b,a%b):a)(c,d=a*b/G(a,b)/c)-1|a%c|b%d?g(b,c+1):[c,d]

```

### Test cases

```
let f =

a=>g=(b,c=1)=>(G=(a,b)=>b?G(b,a%b):a)(c,d=a*b/G(a,b)/c)-1|a%c|b%d?g(b,c+1):[c,d]

console.log(JSON.stringify(f(12)(18))) // [ 4,  9 ]
console.log(JSON.stringify(f(18)(12))) // [ 9,  4 ]
console.log(JSON.stringify(f( 5)( 7))) // [ 5,  7 ]
console.log(JSON.stringify(f( 3)( 6))) // [ 1,  6 ] or [ 3, 2 ]
console.log(JSON.stringify(f( 9)( 9))) // [ 9,  1 ] or [ 1, 9 ]
console.log(JSON.stringify(f( 6)(15))) // [ 2, 15 ] or [ 6, 5 ]
console.log(JSON.stringify(f( 1)( 1))) // [ 1,  1 ]
```

### How?

```
a =>                            // a = first input
  g = (                         // g = recursive function that takes:
    b,                          //   b = second input
    c = 1                       //   c = first output divisor, initially set to 1
  ) =>                          //
    (G = (a, b) =>              // G = function that takes a and b
      b ? G(b, a % b) : a       //     and returns the greatest common divisor
    )(                          // we call it with:
      c,                        //   - c
      d = a * b / G(a, b) / c   //   - d = LCM(a, b) / c = a * b / GCD(a, b) / c
    ) - 1 |                     // if the result is not 1 (i.e. c and d are not coprime)
    a % c |                     // or c does not divide a
    b % d ?                     // or d does not divide b:
      g(b, c + 1)               //   do a recursive call with c + 1
    :                           // else:
      [c, d]                    //   return [c, d], a valid factorization of the LCM

```
> 3 votes

# Answer
# Haskell, ~~50~~ ~~48~~ ~~47~~ ~~45~~ 42 bytes

```
(?)=gcd;a!b|c<-div a$a?b=(c*c?b,div b$c?b)

```

Idea: I noticed that `c*d = a*b/gcd(a,b)`. So the algorithm performs two steps:

1. Begin with `c' = a/gcd(a,b)` and `d' = b`. This fulfils all requirements except that `c'` and `d'` have to be co-prime.
2. To make them co-prime, I calculate `e = gcd(c',d')` and then set `c = c'*e` and `d = d'/e`. This keeps all properties (since the combined factors stay the same), but since I remove all shared factors from `d`, I make `c`and `d` coprime.

In my implementation, `c'` is just called `c`.

Try it online!

-3 bytes thanks to Laikoni
> 3 votes

# Answer
# 05AB1E, 12 bytes

```
Ñ`âʒ.¿I.¿Q}н

```

Try it online! or as a Test suite
> 2 votes

# Answer
# Haskell, ~~91~~ 74 bytes

```
a!b=[(x,y)|x<-[1..a],y<-[1..b],rem a x+rem b y+gcd x y<2,lcm a b==lcm x y]

```

Try it online!

*Saved **17** bytes thanks to Laikoni*
> 2 votes

# Answer
# , 126 bytes

```
function(a,b,g=function(x,y)ifelse(o<-x%%y,g(y,o),y),l=a*b/g(a,b))matrix(c(C<-(1:l)[!l%%1:l],D<-l/C),,2)[g(C,D)<2&!a%%C+b%%D,]

```

Try it online!

This takes a different (and apparently less golfy) approach to finding the values than the other R answer.

Explanation:

```
function(a,b){
 G <- function(x,y)ifelse(o<-x%%y,G(y,o),y) #gcd function, vectorized for x,y
 l <- a*b/g(a,b)                            #lcm of a,b
 C <- (1:l)[!l%%1:l]                        #divisors of l
 D <- l/C                                   #l/C is the other half of the pair
 rel_prime <- G(C, D) < 2                   #pairs where C,D are relatively prime, lol, GCD
 a_div <- !a%%C                             #divisors of a
 b_div <- !b%%D                             #divisors of b
 C <- C[rel_prime & a_div & b_div]
 D <- D[rel_prime & a_div & b_div]          #filter out the bad pairs
 matrix(c(C,D),,ncol = 2)                   #matrix of pairs, returned
}

```

except I shoehorn all the definitions as default arguments and do all the calculations on one line for the golfiness.
> 2 votes

# Answer
# , 19 bytes

```
(*/:"1)&.|:&.(_&q:)

```

Try it online!

Based on @Lynn's solution.

## Explanation

```
(*/:"1)&.|:&.(_&q:)  Input: [a, b]
              _&q:   Get exponenets of each prime
         |:&         Transpose
  /:"1 &             Grade each row
 *                   Multiply elementwise
       &.|:          Transpose
           &. _&q:   Convert exponents back to numbers

```
> 2 votes

# Answer
# Python 2, 75 bytes

```
def f(x):n=1;exec'n+=1;j=k=1\nwhile x[j]%k<1:k*=n**j;j^=1\nx[j]/=k/n;'*x[0]

```

Input is taken as a list, which the function modifies in place.

Try it online!
> 2 votes

# Answer
# Python 3, 129 bytes

```
lambda a,b:[[c,d]for c in range(1,-~a)for d in range(1,-~b)if((gcd(c,d)<2)*a*b/gcd(a,b)==c*d/gcd(c,d))>a%c+b%d]
from math import*

```

Try it online! or Try the test suite.

Outputs all possible combinations in the form of a nested list.
> 1 votes

# Answer
# Jelly,  ~~19 15~~  14 bytes

-4 with pointer from Leaky Nun (use divisor built-in)

I am almost 100% certain this is not the way to actually do this one, but here is a first attempt.
Let's see who outgolfs it with a seven or eight byter!
Yep... see Lynn's answer with explanation!

```
g/÷æl/
ÆDp/ÇÐṂ

```

A monadic link taking a list of the two numbers and returning a list of lists of the possibilities.

**Try it online!**

### How?

```
g/÷æl/  - Link: gcd divided by lcm: list [x, y]
g/      - reduce by gcd = gcd(x, y)
   æl/  - reduce by lcm = lcm(x,y)
  ÷     - divide

ÆDp/ÇÐṂ - Main link: list [a, b]    e.g. [160, 90]
ÆD      - divisors (vectorises)          [[1,2,4,5,8,10,16,20,32,40,80,160],[1,2,3,5,6,9,10,15,18,30,45,90]]
  p/    - reduce by Cartesian product    [[1,1],[1,2],...,[1,90],[2,1],[2,2],...,[2,90],....,[160,90]]
     ÐṂ - entries for which this is minimal:
    Ç   -   call the last link (1) as a monad

```
> 1 votes

# Answer
# Python 2 \+ sympy, 148 bytes

```
from sympy import*
a,b=input()
c=d=z=1
while(a/c*c+b/d*d<a+b)+gcd(c,d)-1+(lcm(c,d)!=lcm(a,b)):E=c==d==z;Q=c==z;d=+E or Q+d;c=+Q or-~c;z+=E
print c,d

```

Try it online!

-1 thanks to Jonathan Frech.

This answer works in Python 2 (not Python 3), using `sympy.gcd` and `sympy.lcm` instead of `math.gcd` and `math.lcm` which are only available in Python 3. And yes, this is brute force :)
> 1 votes

# Answer
# 05AB1E, ~~32~~ ~~26~~ ~~24~~ ~~22~~ ~~20~~ 19 bytes

```
Ó0ζεD`›0sǝ}øεā<ØsmP

```

Try it online! I still have no idea how to write in this language, but at least it's not a brute-force algorithm. Explanation:

```
Ó                       Get exponents of prime factors (vectorised)
 0ζ                     Zip, filling with 0
   ε      }             For each prime
    D`                  Extract the pair of exponents
      ›0sǝ              Overwrite the smaller with 0
           ø            Zip back into two lists of prime exponents
            ε           For each list (} implied)
             ā<Ø        Get a list of primes
                sm      Raise each prime to the exponent
                  P     Take the product

```
> 1 votes

# Answer
# Perl 6, 72 bytes

```
{([X] map {grep $_%%*,1..$_},@^a).grep:{([lcm] @a)==([lcm] $_)==[*] $_}}

```

Try it online!

Takes a list (a, b). Returns a list of all possible lists (c, d).

Explanation:

```
-> @ab {
    # Generate all pairs (c, d)
    ([X]
         # where c divides a and d divides b.
         map { grep $_%%*, 1..$_ }, @ab)
    # Only keep pairs with lcm(a, b) = lcm(c, d) and lcm(c, d) = c * d.
    # The latter implies gcd(c, d) = 1.
    .grep: { ([lcm] @ab) == ([lcm] $_) == [*] $_ }
}

```
> 1 votes

# Answer
# Python 2, ~~126~~ 121 bytes

```
def f(a,b):
 c=[1,1];p=2
 while p<=a*b:
	t=m=1
	while(a*b)%p<1:m*=p;t=b%p<1;a/=p**(a%p<1);b/=p**t
	p+=1;c[t]*=m
 return c

```

Try it online!
> 1 votes

# Answer
# Jelly, 13 bytes

```
Ụ€’×
ÆEz0ÇZÆẸ

```

Try it online! My first Jelly answer! Edit: `ÆEz0µỤ€’×µZÆẸ` also works for 13 bytes. Explanation:

```
ÆE              Get prime factor exponents of both values (vectorises)
  z0            Zip but fill the shorter array with 0
    µ           New monadic link
     Ụ€         Grade up each pair (1-indexed)
       ’        Convert to 0-indexing (vectorises)
        ×       Multiply each pair by its grade (vectorises)
         µ      New monadic link
          Z     Zip back into separate lists of prime factor exponents
           ÆẸ   Turn prime exponent lists back into values (vectorises)

```
> 1 votes

# Answer
# PARI/GP, 86 bytes

This just does what Lynn says in her answer:

```
f(a,b)=forprime(p=2,a*b,v=valuation(a,p);w=valuation(b,p);if(w<v,b/=p^w,a/=p^v));[a,b]

```

If I do not count the `f(a,b)=` part, it is 79 bytes.
> 1 votes

---
Tags: code-golf, arithmetic, number-theory
---


title: What's assignable to what?

text:
# Question
Title: What's assignable to what?
*related*

---

# What's assignable to what?

In this challenge you will be given two types, `A` and `B` and determine if `A` is assignable to `B`, `B` is assignable to `A`, or neither.

## The Type System

(I will use `t` to represent any type)

### Basic Types

Basic types are represented by a single capital letter, such as `X`. They are basically classes.

* `X` is assignable to `Y` if `Y` is either the same as, or a parent class of `X`.

### Intersection Types

Intersection types are represented by `intersect<X, Y>`, and can have any number of types between the `<`'s (e.g. `intersect<X, Y, Z, D, E>`).

* `t` is assignable to `intersect<X1, X2... Xn>` if `t` is assignable to all `X`.
* `intersect<X1, X2... Xn>` is assignable to `t` if any `X` is assignable to `t`.

### Union Types

Union types are represented by `union<X, Y>` and can have any number of types between the `<`'s (e.g. `union<X, Y, Z, D, E>`).

* `t` is assignable to `union<X1, X2... Xn>` if `t` is assignable to any `X`.
* `union<X1, X2... Xn>` is assignable to `t` if all `X` are assignable to `t`.

---

## Input

You will receive as input:

* The class hierarchy. You may choose the method of input for the class hierarchy. You can input a representation of a tree, or each type with a list of its parents, or anything else that accurately represents the class hierarchy.
* Two types (input is flexible, as long as the notation is consistent you may receive these types however you like).

---

## Output

You will output one of three consistent and distinct values, call them `X`, `Y`, and `Z`. Given two types `A` and `B`, output `X` if `A` is assignable to `B`, output `Y` if `B` is assignable to `A` and output `Z` otherwise (If `A` is assignable to `B` and `B` is assignable to `A`, you may output `X`, `Y`, both, or a fourth value).

---

## Test Cases

Format:

```
# of types
[type, parents...]
[type, parents...]
Type a
Type b

```

---

```
2
[A,B]
[B]
A
B
--
A is assignable to B

3
[A,B,C]
[B,C]
[C]
intersect<A,C>
A
--
A is assignable to intersect<A,C>

3
[A,B,C]
[B,C]
[C]
union<A,C>
A
--
A is assignable to union<A,C>

3
[A,B,C]
[B,C]
[C]
intersect<B,C>
A
--
A is assignable to intersect<B,C>

3
[A,B,C]
[X,Y,Z]
[T,U,V]
intersect<union<A,T,X>,intersect<A,B>,Y>
intersect<T,C,X>
--
intersect<T,C,X> and intersect<union<A,T,X>,intersect<A,B>,Y> are not assignable to each other

1
[A]
A
A
--
A is assignable to A

3
[A,B,C]
[X,Y,Z]
[T,U,V]
intersect<A,intersect<A,B>,Y>
intersect<T,C,X>
--
intersect<T,C,X> and intersect<A,intersect<A,B>,Y> are not assignable to each other

2
[A]
[B]
A
B
--
B and A are not assignable to each other

3
[A,B,C]
[X,Y,Z]
[T,U,V]
intersect<union<A,X>,intersect<A,B>,Y>
intersect<T,C,X>
--
intersect<T,C,X> and intersect<union<A,X>,intersect<A,B>,Y> are not assignable to each other

```

Here is a link to a working ungolfed Java solution you can use for testing (it takes input in the same way as the test cases)

---

This is code-golf, so least bytes in each language wins for that language!

# Answer
# Python 3, 177 bytes

`c` is a dictionary of the parents of each type, `a` and `b` are the two expression to check. Types are represented by strings, while intersects and unions are represented by lists with of expressions, with the first element set to `0`for intersect and `1` for union

Returns `0` if they are not assignable to each other, `1` if `a` is assignable to `b`, `2` if `b` is assignable to `a` and `3` if both are assignable to each other

```
lambda c,a,b:y(a,b,c)+2*y(b,a,c)
y=lambda a,b,c:(b in c[a]or a==b if b[0]in c else[all,any][b[0]](y(a,x,c)for x in b[1:]))if a[0]in c else[any,all][a[0]](y(x,b,c)for x in a[1:])

```

Try it online!
> 3 votes

# Answer
## JavaScript (ES6), 138 bytes

```
(p,a,b,g=(a,b)=>a==b||(p[a]||a.i||a.u||[])[a.u?'every':'some'](t=>g(t,b))||(b.i||b.u||[])[b.i?'every':'some'](t=>g(a,t)))=>g(a,b)||+g(b,a)

```

`p` is the parent map, which is a JavaScript object whose keys are the types with parents and whose values are arrays of parent(s). For example, if there are two types `A` and `B` and `B` is the parent of `A` then `p` would be `{A:['B']}`.

Intersection types are represented in `a` and `b` as a JavaScript object with a key of `i` whose value is an array of types, while union types have a key of `u`. For example, the intersection of two types `A` and `B` would be `{i:['A','B']}`.

The return value is `true` if `a` is assignable to `b`, `1` if `a` is not assignable to `b` but `b` is assignable to `a`, or `0` if neither is assignable to each other.
> 3 votes

# Answer
# C++17, 595 bytes

```
#include<type_traits>
#define p(x)template<class...T>class x;
#define d(a,b)disjunction<s<a,b>...>{};
#define c(a,b)conjunction<s<a,b>...>{};
#define u(x)u<x...>
#define i(x)i<x...>
#define k struct s
#define e ...A
#define t(a,b)template<class a,class b>
using namespace std;p(i)p(u)t(B,D)k:disjunction<is_base_of<B,D>,is_same<B,D>>{};t(a,e)k<a,u(A)>:d(a,A)t(a,e)k<a,i(A)>:c(a,A)t(a,e)k<u(A),a>:c(A,a)t(a,e)k<i(A),a>:d(A,a)t(e,...B)k<i(A),i(B)>:d(A,i(B))t(e,...B)k<u(A),u(B)>:c(A,u(B))t(e,...B)k<i(A),u(B)>:d(A,u(B))t(e,...B)k<u(A),i(B)>:c(A,u(B))t(A,B)int f=s<A,B>::value?-1:s<B,A>::value?1:0;

```

Try it online!

A variable template `f` that accepts as input some types and intersection `i<...>` or union `u<...>` of them and returns `-1` if `A` is assignable to `B` and `1` if `B` is assignable to `A` and `0` otherwise.

**Ungolfed:**

```
#include <type_traits>
using namespace std;

template<class...T>class Intersect;
template<class...T>class Union;

template<class A,class B>
struct is_assignable_to:
    disjunction<is_base_of<A,B>,is_same<A,B>>{};

template<class a,class...A>
struct is_assignable_to<a,Union<A...>>:
    disjunction<is_assignable_to<a,A>...>{};

template<class a,class...A>
struct is_assignable_to<a,Intersect<A...>>:
    conjunction<is_assignable_to<a,A>...>{};

template<class a,class...A>
struct is_assignable_to<Union<A...>,a>:
    conjunction<is_assignable_to<A,a>...>{};

template<class a,class...A>
struct is_assignable_to<Intersect<A...>,a>:
    disjunction<is_assignable_to<A,a>...>{};

template<class...A,class...B>
struct is_assignable_to<Intersect<A...>,Intersect<B...>>:
    disjunction<is_assignable_to<A,Intersect<B...>>...>{};

template<class...A,class...B>
struct is_assignable_to<Union<A...>,Union<B...>>:
    conjunction<is_assignable_to<A,Union<B...>>...>{};

template<class...A,class...B>
struct is_assignable_to<Intersect<A...>,Union<B...>>:
    disjunction<is_assignable_to<A,Union<B...>>...>{};

template<class...A,class...B>
struct is_assignable_to<Union<A...>,Intersect<B...>>:
    conjunction<is_assignable_to<A,Intersect<B...>>...>{};

template <class A,class B>
int f = is_assignable_to<A,B>::value?-1:is_assignable_to<B,A>::value?1:0;

```

**Usage:**

```
#include <iostream>
int main(){
    struct B{};
    struct C{};
    struct Y{};
    struct Z{};
    struct U{};
    struct V{};
    struct A:B,C{};
    struct X:Y,Z{};
    struct T:U,V{};
    std::cout << f<Intersect<A,Intersect<A,B>,Y>,Union<T,C,X>>;
}

```
> 2 votes

---
Tags: code-golf, graph-theory, classification
---


title: Standard atmosphere properties

text:
# Question
Title: Standard atmosphere properties
The International Standard Atmosphere (ISA) is a model of the Earth's atmosphere at "reference" conditions. It includes information on pressure, temperature, and density change vs. altitude.

The ISA tabulates these properties at various layers, and an estimation of the value of interest can by found by the following procedure:

1. Find the highest layer `A` which has a base altitude lower than or equal to the altitude of interest.
2. Linearly interpolate between layers `A` and `A+1` to find the properties at the altitude of interest.

For example, suppose you want to find the temperature at a geometric altitude above MSL of `40000m`. Thus, `A=3`, and the temperature is (in degrees `C`):

```
T = (-2.5+44.5)*(40000-32000)/(47000-32000)-44.5 = -22.1

```

The goal of this challenge is given a geometric altitude above MSL, find the standard temperature, pressure, and density at that altitude.

For the purposes of this challenge, use the table of the 1976 ISA model (presented on Wikipedia). Here is a link a Gist containing the data in CSV format. Note that the CSV file includes the missing density values from Wikipedia's page.

# Input

The input is a single finite real number representing the geometric altitude above MSL in meters. This number is guaranteed to be between `[-611,86000)` (i.e. it is greater than or equal to `-611`, and is strictly less than `86000`).

The input may come from any source desired (function input, stdio, etc.)

# Output

The output are the 3 real numbers representing the standard temperature, pressure, and density at the input altitude. The answer should be accurate to within `0.1%`. The answer may be in order desired, as long as it is obvious which value represents which quantity (ex.: the first number is always temperature, the second number is always density, and the third number is always pressure). Note that the magnitude of the quantity does not count as make it obvious what the value represents.

You are welcome to choose any units to output your answers in as long as they properly describe the quantity of interest. Ex.: you may output temperature in degrees Fahrenheit, Celsius, Kelvin, etc., but you can't output the temperature in meters. Your code does **not** need to output the units abbreviation if it is always the same for a given quantity, but you should specify in your answer what units your answer uses.

The output may be to any sink desired (stdio, return value, output parameter, etc.).

# Examples

All examples use meters for input, and output in the order temperature (C), pressure (Pa), density (kg/m^3).

```
-611
19, 108900, 1.2985

0
15.0335, 104368, 1.24943

12000
-56.5, 20771, 0.333986

47350
-2.5, 110.91, 0.0014276

71803
-58.502, 3.95614764, 6.42055e-5

```

# Scoring

This is code golf; shortest answer in bytes wins. Standard loopholes are prohibited. You may use any built-ins desired. If you are using any external resources to store the tabulated data, you must include the size of the resource (in bytes) as read into your program as part of your score.

Ex.: Say you read in a compressed version of the CSV table I linked which is `100` bytes long (uncompressed is `333` bytes), and your code is `126` bytes long. Then your net score is `100+126=226`.

# Answer
> 5 votes
# MATL, 152 bytes

```
'!Q%:5-aeo\!=XBf=H]3|X"Pj7#UGj{r_DH&!+.eFc;u4 kG9Q[rQA(^D1dW- @[E8{Ul0!AXC|MDi8}:&D(j&1_zMU.`[^HQvWoi5}*1UApz %Ld3A)N<$A*7!wBgm'F4Y2'- .;e'hZaU1&Z)i&1Yn

```

Output is in the same order as described in the challenge

Try it online! Or verify all test cases.

### Explanation

Most of the code, `'!Q%:5...!wBgm'`, is a compressed string containing the table. `F4Y2'- .;e'hZa` decompresses this into the string `-611 19 ... 6.961e-6`. Note that some decimals have been removed, as they are not needed to fulfill the 0.1% accuracy criterion.

The decompressed string is interpreted as an array with `U`. This produces the 8×4 table with the required data. The first column shown in the challenge is not needed. Then `1&Z)` separates the first column from the rest.

`i` takes a number as input, and `&1Yn` applies linear interpolation using the three types of data: first column of the table, remaining columns, input. The result of the interpolation is implicitly displayed.

The input can also be a column vector, and then each row of the output refers to one of the input values. This is used for verifying all test cases at once.

# Answer
> 0 votes
# Python 2, 372 bytes

```
h=-611,11019,20063,32162,47350,51413,71802,86000
i=input()
p=sum(x<=i for x in h)-1
a,b=h[p:p+2]
d=i-a+.0
d/=b-a
for e,f in[x[p:p+2]for x in[(19,-56.5,-56.5,-44.5,-2.5,-2.5,-58.5,-86.28),(108900,22632,5474.9,868.02,110.91,66.939,3.9564,0.3734),(1.29853103694,0.3639105,0.0880334745,0.0132247926,0.00142755556,0.000862248191,6.42095529e-05,6.96089485e-06)]]:print e+f*d-e*d

```

Try it online!

---
Tags: code-golf, math
---


title: Ratetod text fexir

text:
# Question
Title: Ratetod text fexir
I heva this wierd text where vewols seem to be ratetod :

> I'm a badly written text. Some lunatic guy played with the order of vowels. Please fix me !

So I'd need a pragrom which can rateto the vewols (and the 'y' letter as it seems) back so that the text is raadeble agian.

Ouy can choeso the lungaega of ouyr chieco privedod ouy meka a cempleto pragrom (so not just a finctoun). The yntre can be an unpit feild, a text feli, or the cammond leni. The uutpot mya olsa vyra as ouy leki.

Of cuerso I'll anvilid yna pragrom uutpitong bad texts. There's no vulea in a pragrom which mekas texts ouy can't endarstund. But ouy can wreti ouyr cemmonts and qeistouns in ratetod texts if ouy want.

---

### Clarifications

* Your program is only required to handle ASCII text.
* For the purposes of this question, the following characters are vowels: `aeiouy`
* The positions of the vowels within each word should be rotated. There is some flexibility in deciding what qualifies as a word: the minimum requirement is that two characters separated by a space are in different words, and that two alphabetic characters (`a-zA-Z`) separated only by alphabetic characters are in the same word.
* The desired direction of rotation should be inferred from the test cases below.

### Test cases

Input: `I'm a badly written text. Some lunatic guy played with the order of vowels. Please fix me !`
Output: `I'm a bydla wrettin text. Semo lanituc gyu plyead with the erdor of vewols. Plaese fix me !`

Input: `AeiOuy`
Output: `EioUya`

Input: `Hyphenated-word`
Output: `Hephanetyd-word` or `Hephanetod-wyrd`

# Answer
### GolfScript, 68 67 57 characters

```
" "/{..+{95&"AEIOUY"?)}:C,1>\{.C!!{96&\(31&@|}*}%\;}%" "*

```

Input must be given on STDIN. Example (online):

```
> You!!! I'm a badly written text. Some lunatic guy played with the order of vowels. Please fix me !
Ouy!!! I'm a bydla wrettin text. Semo lanituc gyu plyead with the erdor of vewols. Plaese fix me !

```
> 6 votes

# Answer
### Ruby, 91 90 characters

```
$><<gets.gsub(/\S+/){|x|x.gsub(r=/[aeiouy]/i){|y|z=$'[r]||x[r];y>?Z?z.downcase: z.upcase}}

```

### Coffeescript, 148 charectars

```
alert prompt().replace /\S+/g,(x)->x.replace r=/[aeiouy](?=(.*))/gi,(y,z)->((t=z.match r)&&t[0]||x.match(r)[0])[['toLow','toUpp'][y>'Z']+'erCase']()

```

No ussimtoans, except that "holf-cerract" is a word, and not my sulitoon.

Test:

```
> To test this program, simply enter a long sentence that appears half-broken
  To test this pragrom, sympli enter a long sentence that eppaars holf-brekan

> No MaTtEr HoW mUcH cAsE yOu uSe, It WoRkS
  No MeTtAr HoW mUcH cEsA oUy eSu, It WoRkS

```
> 5 votes

# Answer
## Haskell, 159 characters

Didn't end up quite as short as I'd hoped, but I decided to post it anyway:

```
import Data.Char
f s=let(v,t)=foldr g(v,[])s in t
g x(v,t)=last$(v,x:t):[(x,c v:t)|c<-[toUpper,toLower],x`elem`map c"AEIOUY"]
main=interact$unwords.map f.words

```

**Ungolfed version:**

```
import Data.Char

rotateVowels :: String -> String
rotateVowels word = result
  where (vowel, result) = foldr step (vowel, []) word
        step ch (vowel, rest)
          | ch `elem` "AEIOUY" = (ch, toUpper vowel : rest)
          | ch `elem` "aeiouy" = (ch, toLower vowel : rest)
          | otherwise          = (vowel, ch : rest)

main = interact $ unwords . map rotateVowels . words

```

This is a nice example of how lazy evaluation can let you do cool tricks. In `rotateVowels`, each time a new vowel is found, it is passed on to the left, while replacing it with the one coming from the right. This part of the output from the fold is fed back as the input so that the leftmost vowel becomes the replacement for the rightmost one.

```
(vowel, result) = foldr step (vowel, []) word
 ^^^^^                        ^^^^^
 this part of the output      is part of the input

```
> 2 votes

# Answer
# Python 2, 172 bytes

```
for w in input().split():p=[];q=list(w);z=filter(lambda c:c in'aeiouyAEIOUY',q);x=z[1:]+z[:1];print''.join(y in z and[str.upper,str.lower][y>'Z'](x.pop(0))or y for y in q),

```

Try it online!
> 1 votes

---
Tags: code-golf
---


title: Is this molecule polar?

text:
# Question
Title: Is this molecule polar?
> ### Disclaimer
>
> It is bad practice to draw out your molecules in 2 dimensions because that is not how they are. I chose to do this in 2D because it is easier to explain.
>
> Note that the bond angles are wrong too: the angle in CH4 is 109.5°, not 90° as I said and the bond angle in NH4 is 107°. BHCl2 does have a bond angle of 120° and is 2D, however.

## Challenge

Given the formula of a simple molecule as input, output a truthy value if the molecule is polar (asymmetrical) or a falsey value if the molecule is non-polar (symmetrical).

## Determining Polarity

To determine whether a molecule is polar or not, we will have to look at its shape. For the purposes of this challenge, we will assume that molecules are 2D.

To demonstrate how to determine the polarity of a molecule, let us use three examples: methane (CH4), ammonia (NH3) and BHCl2.

### CH4

Firstly, lets take the centre molecule, carbon. Carbon is in group four of the periodic table so it has four outer shell electrons, as shown below:

Now, we add the hydrogen atoms (each hydrogen atom supplies its own electron to make a pair):

Since there are no lone pairs of electrons, we can draw it with 90° between each bond since all bonds repel equally:

We can now see that methane is symmetrical so it is ***non-polar***.

### NH3

Like above, we take the centre molecule, nitrogen and draw out its outer shell electrons:

Adding the hydrogen atoms, we notice that there is a lone pair of electrons:

Since the lone pair is closer to the atom, it repels more than a bonding pair, so the angle between the bonds is smaller:

Evidently, NH3 is not symmetrical, so it is ***polar***.

### BHCl2

Taking boron as the centre molecule, we draw the three outer electrons:

We then add the hydrogen and the chlorines:

There are no lone pairs, so the bonds repel equally, forming an angle of 120°:

Although, the shape is symmetrical, the hydrogen atom makes the molecule asymmetrical, so BHCl2 is ***polar***.

## Rules

Built-ins which access molecule information are disallowed. You may access periodic table data using built-ins or without adding the file to your byte count. This data may be stored however you wish.

Input will only ever be a valid simple molecule: a single central atom (p-block element) which comes first in the formula and up to eight outer atoms (hydrogen, fluorine, chlorine, bromine, iodine, astatine) which only use single bonds.

You will never get a polyatomic ion or a molecule with co-ordinate (dative covalent) bonds as input. For example, with `NH4`, there would be a single unpaired electron, so the only for NH4 to form a stable molecule would be to lose the extra electron and become an ion (a polyatomic ion, since there is more than one atom in the ion).

If there are multiple lone pairs, they have to be spaced as far as possible from each other. For example, two lone pairs will have to be opposite from each other.

***If there are non-polar and polar isomers of a molecule (e.g. SiF2Cl2) you should assume the molecule is non-polar.***

## Examples

```
Input -> Output
OH2 -> Falsey
CCl4 -> Falsey
OF4 -> Truthy
CH4 -> Falsey
NH3 -> Truthy
BHCl2 -> Truthy

```

## Winning

Shortest code in bytes wins.

# Answer
# Python 3, 296 bytes

```
import P,re,itertools
r="[A-Z][a-z]?"
f=re.findall(r,re.sub("(%s)(\d)"%r,lambda g:g.group(1)*int(g.group(2)),input()))
print(all(any(any(q[:len(q)//i]*i==q for i in range(2,len(q)))for q in[j[i:]+j[:i]for i in range(len(j))])<1for j in itertools.permutations(f+['e']*-(len(f)-P.a[f.pop(0)]>>1))))

```

Try it online!

-29 bytes thanks to ovs

Prints `False` or `True`.

This requires a dict of all p-block element symbols to the number of valence electrons they have. `H` is not necessary since it will only be one of the surrounding atoms. The dict is stored in `P.py` as a variable named `a` (it's written in the input for TIO and then placed into a Python file by the header)
> 2 votes

---
Tags: code-golf, chemistry
---