title: Detect heat waves

text:
# Question
Title: Detect heat waves
# Background

The Royal Netherlands Meteorological Institute defines a heat wave* as a series of **at least** 5 **consecutive** days of ≥25°C weather (“summery weather”), such that **at least** 3 of those days are ≥30°C (“tropical weather”).

The tropical weather doesn't have to be measured consecutively: for example: `30, 25, 30, 26, 27, 28, 32, 30` is a 8-day long heat wave with 4 days of tropical weather.

\*(Well, by Dutch standards.)

# Challenge

Given a non-empty list of positive integers representing Celsius temperature measurements from successive days, decide whether that list contains a heat wave (as per the above definition).

The shortest answer in bytes wins.

# Test cases

Falsey:

```
[30]
[25, 30, 25, 60, 25]
[29, 29, 29, 47, 30]
[31, 29, 29, 28, 24, 23, 29, 29, 26, 27, 33, 20, 26, 26, 20, 30]
[23, 31, 29, 26, 30, 24, 29, 29, 25, 27, 24, 28, 22, 20, 34, 22, 32, 24, 33]
[23, 24, 25, 20, 24, 34, 28, 32, 22, 20, 24]
[24, 28, 21, 34, 34, 25, 24, 33, 23, 20, 32, 26, 29, 29, 25, 20, 30, 24, 23, 21, 27]
[26, 34, 21, 32, 32, 30, 32, 21, 34, 21, 34, 31, 23, 27, 26, 32]
[29, 24, 22, 27, 22, 25, 29, 26, 24, 24, 20, 25, 20, 20, 24, 20]
[23, 33, 22, 32, 30]
[28, 21, 22, 33, 22, 26, 30, 28, 26, 23, 31, 22, 31, 25, 27, 27, 25, 28]
[27, 23, 42, 23, 22, 28]
[25, 20, 30, 29, 32, 25, 22, 21, 31, 22, 23, 25, 22, 31, 23, 25, 33, 23]

```

Truthy:

```
[30, 29, 30, 29, 41]
[1, 1, 25, 30, 25, 30, 25, 25, 25, 25, 25, 25, 25, 25, 40, 1, 1]
[31, 34, 34, 20, 34, 28, 28, 23, 27, 31, 33, 34, 29, 24, 33, 32, 21, 34, 30, 21, 29, 22, 31, 23, 26, 32, 29, 32, 24, 27]
[26, 29, 22, 22, 31, 31, 27, 28, 32, 23, 33, 25, 31, 33, 34, 30, 23, 26, 21, 28, 32, 22, 30, 34, 26, 33, 20, 27, 33]
[20, 31, 20, 29, 29, 33, 34, 33, 20]
[25, 26, 34, 34, 41, 28, 32, 30, 34, 23, 26, 33, 30, 22, 30, 33, 24, 20, 27, 23, 30, 23, 34, 20, 23, 20, 33, 20, 28]
[34, 23, 31, 34, 34, 30, 29, 31, 29, 21, 25, 31, 30, 29, 29, 28, 21, 29, 33, 25, 24, 30]
[22, 31, 23, 23, 26, 21, 22, 20, 20, 28, 24, 28, 25, 31, 31, 26, 33, 31, 27, 29, 30, 30]
[26, 29, 25, 30, 32, 28, 26, 26, 33, 20, 21, 32, 28, 28, 20, 34, 34]
[34, 33, 29, 26, 34, 32, 27, 26, 22]
[30, 31, 23, 21, 30, 27, 32, 30, 34, 29, 21, 31, 31, 31, 32, 27, 30, 26, 21, 34, 29, 33, 24, 24, 32, 27, 32]
[25, 33, 33, 25, 24, 27, 34, 31, 29, 31, 27, 23]

```

# Answer
# C (gcc), ~~88~~ ~~75~~ 73 bytes

```
h,e,a;t(int*_){for(h=e=a=0;*_;h+=e>4&a>2)e=*_<25?a=0:++e,a+=*_++>29;e=h;}

```

Try it online!
> 31 votes

# Answer
# Jelly, 15 bytes

```
:5_5Ṡ‘ẆP«LƊ€>4Ṁ

```

A monadic link accepting a list of numbers which returns `1` if a heatwave was detected else `0`.

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

### How?

The criteria is the existence of a run of more than four values greater than or equal to 25, of which more than two must be greater than or equal to 30.

If we divide through by five the criteria becomes the existence of a run of more than four values greater than or equal to five, of which more than two must be greater than or equal to six.

If we subtract five from these values the criteria becomes the existence of a run of more than four values greater than or equal to zero, of which more than two must be greater than or equal to one.

If we take the sign of these values (getting -1, 0, or 1) the criteria becomes the existence of a run of more than four values not equal to -1, of which more than two must be equal to one.

If we add one to these values (getting 0, 1, or 2) the criteria becomes the existence of a run of more than four values not equal to zero, of which more than two must be equal to two.

The product of a list containing any zeros is zero and the product of a list containing more than two twos (and the rest being ones) is more than four. This means that the criteria on this adjusted list becomes that the minimum of the product and the length is greater than 4.

```
:5_5Ṡ‘ẆP«LƊ€>4Ṁ - Link: list of numbers
:5              - integer divide by five (vectorises)
  _5            - subtract five (vectorises)
    Ṡ           - sign {negatives:-1, zero:0, positives:1} (vectorises)
     ‘          - increment (vectorises)
      Ẇ         - all sublists
          Ɗ€    - last three links as a monad for €ach:
       P        -   product
         L      -   length
        «       -   minimum
            >4  - greater than four? (vectorises) -- 1 if so, else 0
              Ṁ - maximum -- 1 if any are 1, else 0

```
> 20 votes

# Answer
# C (clang), 64 bytes

```
h;o(*t){for(h=1;*t;++t)h=h&&*t<25?1:h*(*t<30?2:6)%864;return!h;}

```

The function o() returns 1 for a heatwave or 0 else.

Thanks to the magic number 864 and to Udo Borkowski and Mathis for their ideas.

How does if work? Each sequence of numbers is iterated with a reduce operation starting at the reduce value 1. If a number \>= 25 is seen the reduce is multiplied by 2. If a number \>= 30 is seen the reduce is multiplied by 2 and by 3 = 6. If a number \< 25 is seen the reduce starts again at 1. If the reduce is divisible by 864=2\*2\*2\*2\*2\*3\*3\*3 then a heatwave is found, and the result of the modulo operation is 0 which results in a reduce value of 0 and in a return value of true.

Try it online!
> 10 votes

# Answer
# Haskell, ~~73~~ ~~72~~ ~~71~~ ~~69~~ ~~67~~ 66 bytes

```
any(\a->sum[1|x<-a,x>29,take 4a<a]>2).scanl(\a t->[0|t>24]>>t:a)[]

```

Thanks to @flawr and @Laikoni for two bytes each and @xnor for a byte!

Try it online!

Equal length:

```
any(\a->take 4a<a&&sum a>2).scanl(\a t->[0|t>24]>>sum[1|t>29]:a)[]

```

Try it online!
> 9 votes

# Answer
# Python 3, 79 bytes

```
lambda T:any(len(s)>4<sum(s+s)for s in bytes(t>29or(t<25)*9for t in T).split())

```

Try it online!
> 7 votes

# Answer
# APL (Dyalog Classic), ~~21~~ 20 bytes

```
1∊8≤4↓⍉×\25 30⍸↑,⍨\⎕

```

Try it online!

uses `⎕io←1`

`25 30⍸x` is 0 if x\<25, 1 if 25≤x\<30, or 2 otherwise

we compute cumulative products of these starting from (or equivalently: ending at) all possible locations, discard the first 4 products, and detect the presence of products ≥8 (which is 23)
> 7 votes

# Answer
# Japt, ~~19~~ 18 bytes

```
ô<25 d_Ê¨5©3§Zè¨30
ô                  // Partition the input at every item
 <25               // where the value is less than 25.
     d_            // Then, return whether any resulting subarray
       Ê¨5         // is at least five items long
          ©        // and
           3§      // has at least three items
             Zè¨30 // with a value of at least 30.

```

I hope I got all the discussions in the comments correctly.
Shaved off one byte thanks to Shaggy.

Try it online!
> 6 votes

# Answer
# JavaScript (ES6), ~~63~~ 51 bytes

Returns a boolean.

```
a=>a.some(n=>(n>24?y+=++x&&n>29:x=y=0)>2&x>4,x=y=0)

```

Try it online!
> 5 votes

# Answer
# PowerShell, 121 bytes

```
param($a)$b="";($a|%{if($_-ge25){$b+="$_ "}else{$b;$b=""}})+$b|?{(-split$_).count-ge5-and(-split$_|?{$_-ge30}).count-ge3}

```

Try it online! or Verify all test cases

PowerShell doesn't have the equivalent of a `.some` or `.every` or the like, so this is rolled by hand.

We take input `$a` as an array of integers. Set helper variable `$b` to the empty string. Then, loop through every integer in `$a`. Inside the loop, if the integer is `-g`reaterthanor`e`qual to `25`, add it to our potential string `$b`, otherwise put `$b` on the pipeline and set it to the empty string.

Once outside the loop, array-concatenate the pipeline results with `$b`, and put those through a `Where-Object` clause `|?{...}`. This pulls out those strings that have an element length of `-ge5` (based on splitting on whitespace) and a count of temps greater than `30` being `-ge3`. Those strings are left on the pipeline, so a truthy value is non-empty (see the "verify all test cases" link for truthy/falsey distinction).
> 5 votes

# Answer
# Jelly, ~~17~~ 16 bytes

```
:5_5Ṡṣ-ḤS«LƊ€Ṁ>4

```

Try it online!

### How it works

```
:5_5Ṡṣ-ḤS«LƊ€Ṁ>4  Main link. Argument: T (array of temperatures)

:5                Divide each item of T by 5 (integer division).
  _5              Subtract 5 from each quotient.
    Ṡ             Take the signs.
                  This maps (-oo,25) to -1, [25,30) to 0, and [30,+oo) to 1.
     ṣ-           Split at occurrences of -1.
       Ḥ          Double, replacing 1's with 2's.
           Ɗ€     Map the three links to the left over each chunk.
        S             Take the sum.
          L           Take the length.
         «            Take the minimum of the results.
             Ṁ    Take the maximum.
              >4  Test if it's larger than 4.
                  Note that the sum is larger than 4 if and only if there are more
                 than two 2's, which correspond to temperatures in [30,+oo).

```
> 5 votes

# Answer
# Python 2, 86 bytes

```
lambda l:any(2<s.count('2')*(len(s)>14)for s in`[(t>24)+(t>29)for t in l]`.split('0'))

```

Try it online!
> 5 votes

# Answer
# APL (Dyalog Unicode), 29 bytes

```
∨/(5≤≢¨a)∧3≤+/30≤↑a←e⊆⍨25≤e←⎕

```

Try it online!

`∨/` are there *any* elements such that

`(5≤≢¨a)` 5 \< the tally  of days in each series (`a` has all the possible series of days)

and

`3≤+/30≤` 3 ≤ the total `+/` number of elements that are ≥ 30 in

`↑a←` the matrix formed by

`e⊆⍨25≤e←⎕` the series of consecutive elements that are ≥ 25
> 4 votes

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

```
a=>a.some(x=>x>24?++A>4&(B+=x>29)>2:A=B=0,A=B=0)

```

Try it online!

quite bad one
> 4 votes

# Answer
# 05AB1E, 20 bytes

```
Œʒ24›DPsO4›*}29›O2›Z

```

Try it online!

**Explanation**

```
Œ                     # push sublists of input
 ʒ          }         # filter, keep the lists where:
           *          # the product of:
     DP               # the product and
       sO4›           # the sum compared using greater-than to 4
  24›                 # for the elements greater than 24
                      # is true
                      # the result is:
                   Z  # the maximum from the remaining lists where
                O     # the sum of
             29›      # the elements greater than 29
                 2›   # is greater than 2

```
> 4 votes

# Answer
## Batch, 119 bytes

```
@set h=0
@for %%t in (0 %*)do @if %%t lss 25 (set/as=5,t=3)else set/a"t+=!!t*(29-%%t)>>9,s-=!!s,h+=!(s+t+h)
@echo %h%

```

Takes input as command-line arguments and outputs 1 for a heatwave otherwise 0.
> 4 votes

# Answer
# Python, 67 bytes

```
f=lambda l:l>l[:4]and(min(l)>24<sorted(l)[~2]-5)|f(l[1:])|f(l[:-1])

```

Try it online!

Times out on the longer test cases due to exponential growth. Finds contiguous sublists by repeatedly chopping the first or last element. That 3 days are ≥30°C is checked by looking at the third-largest value `sorted(l)[~2]`. The base cases could perhaps be shorter by taking advantage of truthy/falsey or terminating with error.
> 4 votes

# Answer
# Haskell, 64 bytes

```
f l=or$drop 4l>>[sum[1|x<-l,x>29,all(>24)l]>2,f$tail l,f$init l]

```

Try it online!
> 4 votes

# Answer
# Kotlin, 57 bytes

```
{var r=1;it.any{r*=2;if(it>29)r*=3;if(it<25)r=1;r%864<1}}

```

(-1 Byte by replacing the explicit Parameter *v-\>* with the implicit parameter *it*)

~~```
{var r=1;it.any{v->r*=2;if(v>29)r*=3;if(v<25)r=1;r%864<1}}

```~~

(-16 bytes using the any{} operation as seen in the Ruby Solution by G B)

~~```
{it.stream().reduce(1){r,v->if(r*25>r*v)1 else(r*if(v<30)2 else 6)%864}<1}

```~~

(-1 byte thanks Lynn: replaced r\>0&&v\<25 with r\*25\>r\*v)

~~```
{it.stream().reduce(1){r,v->if(r>0&&v<25)1 else(r*if(v<30)2 else 6)%864}<1}

```~~

This lambda expression takes a List and returns true for a heatwave or false else.

Thanks to the magic number 864 and to Udo Borkowski and Mathis for their ideas.

How does if work? Each sequence of numbers is iterated with an *any{}* operation starting at the reduce value 1. The reduce is multiplied by 2 and multiplied with 3 (2\*3=6) if the number is greater or equal 30. If a number \< 25 is seen the reduce starts again at 1. If the reduce is divisible by 864=2\*2\*2\*2\*2\*3\*3\*3 then a heatwave is found, and the result of the modulo operation is 0 which results in a true return value in the inner lambda called from the *any{}* operation which then stops iterating and returns value of true.

Try it online!
> 4 votes

# Answer
# Python 2, ~~66~~ 63 bytes

```
lambda a:reduce(lambda b,c:(b*(6,2)[c<30]%864,1)[b*25>b*c],a,1)

```

Try it online!

-3 bytes thanks to Lynn

How does if work? Each sequence of numbers is iterated with a reduce operation starting at the reduce value 1. If a number \>= 25 is seen the reduce is multiplied by 2. If a number \>= 30 is seen the reduce is multiplied by 2 and by 3 = 6. If a number \< 25 is seen the reduce starts again at 1. If the reduce is divisible by 864=2\*2\*2\*2\*2\*3\*3\*3 then a heatwave is found, and the result of the modulo operation is 0 which results in a reduce value of 0. Only when a heat wave was found the reduce can become 0. Once the reduce value is 0 it will be 0 for all future reduces, i.e. also for the end result.

A more readable, but longer version looks like this:

```
lambda a:reduce((lambda b,c: 1 if b>0 and c<25 else b*(2 if c<30 else 6)%864), a, 1)

```

Removing extra spaces/parenthesis and replacing `x if cond else y` by `(y,x)[cond]` gives

```
lambda a:reduce(lambda b,c:(b*(6,2)[c<30]%864,1)[b>0and c<25],a,1)

```

Lynn suggested to shorten the condition `b>0and c<25`:

`b>0and c<25` --\> `b*25>0 and b*c<b*25` --\> `b*25>0 and b*25>b*c` --\> `b*25>b*c`

resulting in

```
lambda a:reduce(lambda b,c:(b*(6,2)[c<30]%864,1)[b*25>b*c],a,1)

```
> 4 votes

# Answer
# Wonder, 34 bytes

```
(/>@(& <2!> '<29#0)*> '<24#0).cns5

```

Usage example:

```
((/>@(& <2!> '<29#0)*> '<24#0).cns5) [25 33 33 25 24 27 34 31 29 31 27 23]

```

# Explanation

Verbose version:

```
(some x\\(and <2 (fltr <29) x) (every <24) x) . (cns 5)

```

Take overlapping sequences of 5 consecutive items, then check if any of the sequences have all items \> 25 and more than 2 items \> 30.
> 3 votes

# Answer
# Jelly, 21 bytes

```
L5r⁸ṡẎ<25Ẹ$Ðḟ29<S€2<Ẹ

```

Try it online!
> 3 votes

# Answer
# Ruby, 89 bytes

```
->a{(0..a.size).map{|i|(b=a[i..-1].take_while{|t|t>24}).size>4&&b.count{|t|t>29}>2}.any?}

```

Try it online!
> 3 votes

# Answer
# Stax, 23 bytes

```
Æ7)║▄░Ä╟═╙hⁿ╧\ßY8÷K▌µ½x

```

Run and debug it at staxlang.xyz! This takes a long time to run, so I disabled auto-run.

### Unpacked (28 bytes) and explanation

```
:efc%4>nc{24>f=a{29>f%2>|&|&
:e                              Set of all contiguous subarrays
  f                             Filter, using the rest of the program as a predicate:
   c                              Copy subarray on the stack
    %4>                           Five or more elements?
                        |&        AND
       nc                         Copy subarray twice to top
         {   f                    Filter:
          24>                       Greater than 24?
              =                   Equals the original subarray?
                          |&      AND
               a                  Move subarray to top
                {   f             Filter:
                 29>                Greater than 30?
                     %2>          Length greater than two?
                                  Implicit print if all three conditions are met

```

This'll print all subarrays that can be counted as heat waves, which will be falsy if and only if none exist.
> 3 votes

# Answer
# Husk, 19 bytes

```
Vo≥3#≥30fo≥5Lġ(±≥25

```

Try it online!

Using filter (`f`) is one byte shorter than using checking with a logical and (`&`), also it would be really nice to get rid of the `±` \- costing 2 bytes :(

### Explanation

```
V(≥3#≥30)f(≥5L)ġ(±≥25)  -- example input: [12,25,26,27,28,29,18,24,32]
               ġ(    )  -- group by
                ( ≥25)  -- | greater or equal to 25: [0,1,2,3,4,5,6,0,0,8]
                (±   )  -- | sign: [0,1,1,1,1,1,1,0,0,1]
                        -- : [[12],[25,26,27,28,29,30],[18,24],[32]]
         f(   )         -- filter by
          (  L)         -- | length: [1,6,2,1]
          (≥5 )         -- | greater or equal to 5: [0,2,0,0]
                        -- : [[25,26,27,28,29,30]]
V(      )               -- does any element satisfy
 (  #   )               -- | count occurences where
 (   ≥30)               -- | | elements greater or equal to 30
 (      )               -- | : [1]
 (≥3    )               -- | greater or equal to 3: [0]
                        -- : 0

```
> 3 votes

# Answer
# , ~~111 93 71 67~~ 66 bytes

```
!Reduce(function(i,j)"if"(j<25,!!i,(i*(2+4*!j<30))%%864),scan(),1)

```

Try it online!

Shameless port of Roland Schmitz's answers. -4 bytes thanks to Roland and -1 thanks to Giuseppe.

TIO links to functional version.

Previous version extracted consecutive days\>25 using `rle` and saved a whopping 18 bytes thanks to Giuseppe!
> 3 votes

# Answer
# Java (JDK 10), 60 bytes

```
h->h.stream().reduce(1,(r,v)->r*25>r*v?1:r*(v<30?2:6)%864)<1

```

(-1 byte thanks Lynn: replaced r\>0&&v\<25 with r\*25\>r\*v)

~~```
h->h.stream().reduce(1,(r,v)->r>0&&v<25?1:r*(v<30?2:6)%864)<1

```~~

The lambda expression returns true for a heatwave or false else.

Thanks to the magic number 864 and to Udo Borkowski and Mathis for their ideas.

How does if work? Each sequence of numbers is iterated with a reduce operation starting at the reduce value 1. If a number \>= 25 is seen the reduce is multiplied by 2. If a number \>= 30 is seen the reduce is multiplied by 2 and by 3 = 6. If a number \< 25 is seen the reduce starts again at 1. If the reduce is divisible by 864=2\*2\*2\*2\*2\*3\*3\*3 then a heatwave is found, and the result of the modulo operation is 0 which results in a reduce value of 0 and in a return value of true.

Try it online!
> 3 votes

# Answer
# Swift 4, 50 bytes

```
{$0.reduce(1){$0>0&&$1<25 ?1:$0*($1<30 ?2:6)%864}}

```

Try it online!

The closure expression returns 0 for a heatwave or \>0 else.

Created in collaboration with Roland Schmitz and Mathis.

How does if work? Each sequence of numbers is iterated with a reduce operation starting at the reduce value 1. If a number \>= 25 is seen the reduce is multiplied by 2. If a number \>= 30 is seen the reduce is multiplied by 2 and by 3 = 6. If a number \< 25 is seen the reduce starts again at 1. If the reduce is divisible by 864=2\*2\*2\*2\*2\*3\*3\*3 then a heatwave is found, and the result of the modulo operation is 0 which results in a reduce value of 0. Only when a heat wave was found the reduce can become 0. Once the reduce value is 0 it will be 0 for all future reduces, i.e. also for the end result.
> 3 votes

# Answer
# \[JavaScript (ES6)\], 49 bytes

```
a=>a.reduce((b,c)=>b>0&c<25?1:b*(c<30?2:6)%864,1)

```

Try it online!

The arrow function returns 0 for a heatwave or \>0 else.

*(Port of the Swift solution to JavaScript)*

How does if work? Each sequence of numbers is iterated with a reduce operation starting at the reduce value 1. If a number \>= 25 is seen the reduce is multiplied by 2. If a number \>= 30 is seen the reduce is multiplied by 2 and by 3 = 6. If a number \< 25 is seen the reduce starts again at 1. If the reduce is divisible by 864=2\*2\*2\*2\*2\*3\*3\*3 then a heatwave is found, and the result of the modulo operation is 0 which results in a reduce value of 0. Only when a heat wave was found the reduce can become 0. Once the reduce value is 0 it will be 0 for all future reduces, i.e. also for the end result.
> 3 votes

# Answer
# Ruby, ~~50~~ 48 bytes

```
->a{b=1;a.any?{|r|1>b=[b*2,1,b*6][5<=>r/5]%864}}

```

Try it online!

Thanks to Roland Schmitz and Udo Borkowski for the idea and the magic number 864. And again to Roland for saving 2 bytes.
> 3 votes

# Answer
# Haskell, 60 bytes

```
f q|(a,~(_:t))<-span(>24)q=sum[1|x<-a,x>29,take 4a<a]>2||f t

```

Try it online!

This combines some ideas from previous Haskell answers in a new form along with exit by error code to come out ahead.

### How?

`(a,~(_:t))<-span(>24)q` puts the prefix of the list which is entirely \>24 into `a`, and then tries to match the remainder of the list to the pattern `h:t` (dropping one value `<= 24` and putting the remaining suffix into `t`). This pattern match might fail even on truthy inputs, if the heat wave is at the end of the list, which is where the `~` comes in: it forces Haskell to match the rest of the pattern even if `_:t` can't be matched (an "irrefutable pattern"), in which case `t` is undefined (i.e. set to `_|_`) and will error out if we ever try to use it.

Since Haskell has the usual short circuiting on `||`, we will only try to evaluate `f t` on undefined `t` if there was no heat wave in the list, in which case we exit high. If there was a heat wave, we'll find it and short circuit out, returning `True` and exiting low.

The irrefutable pattern saves one byte compared to `tail`, which will similarly fail if called on an empty list:

### Haskell, 61 bytes

```
f q|(a,b)<-span(>24)q=sum[1|x<-a,x>29,take 4a<a]>2||f(tail b)

```

Try it online!
> 3 votes

# Answer
# Pyth, 23 bytes

```
f&glT5&>T]25gePPT30SM.:

```

Try it here

```
f&glT5&>T]25gePPT30SM.:
f                  SM.:Q   Get the sorted subsequences of the (implicit) input...
 &qlT5                     ... with at least 5 elements...
      &>T]25               ... all at least 25...
            gePPT30        ... where the third to last is at least 30.

```
> 2 votes

# Answer
# Perl 6, ~~54~~ 52 bytes

```
{$_>5&.grep(*>29)>2}o{any kv classify $+=25>*,0,|$_}

```

Try it online!
> 2 votes

# Answer
# Befunge-98, 61 bytes

```
]&:46*`#;_$$$v\+1\;
 +1\_;#`+fe;#<\v
^_v#!`4:\_;#`2:<;\
>0>.@

```

Try it online!
> 2 votes

# Answer
# K (ngn/k), ~~38~~ ~~32~~ 30 bytes

```
{+/7<,/4_'*\'|:',\+/x>/:24 29}

```

Try it online!
> 2 votes

# Answer
# Julia 0.6, 49 bytes

```
T->reduce((x,y)->y>24?(2+4(y>29))x%864:x>0,1,T)<1

```

Try it online!

The popular `reduce` solution from Udo Borkowski. The final `<1` limits the output to true/false. We can remove it for 47 bytes, but the output will then be either `false` or `0` (varying) for, well, false, and a non-zero number for true.

Alternate version (equivalent) based on G B's Ruby implementation (1 byte longer):

```
T->(x=1;any(y->(x=y>24?(2+4(y>29))x%864:x>0)<1,T))

```

Try it online!

Explanation for either version:

```
function u_explained(temps)
  x = 1
  for y in temps
    if y > 24
      val = 2 + (y > 29 ? 4 : 0) #2 for 25 to 29, 6 for 30 and above
      x = val * x
      #If we've reached 5 "summery" days (2^5) of which at least 3 are
      # "tropical" (3^3), then x will be a multiple of 2^5*3^3
      # If we've reached there, make x 0. Else, keep as is.
      x = x % 864
    else
      #found non-summery day, reset non-zero values into 1 (true), but keep 0 as 0 (false)
      x = x > 0
    end
  end
  return x == 0
end

```

---

Older solution:

### 75 bytes

```
T->(l=endof(T))>4&&any(prod(1+sign(T[i:j]÷5-5))>7 for i=1:l-4 for j=i+4:l)

```

Try it online!

(*+13 bytes to fix buggy behaviour for test cases 2 and 9*)

Julia port of Jonathan Allan's brilliant Jelly solution. Probably not optimal, I just found the method used so neat that I had to try it.
> 2 votes

# Answer
# Regex (ECMAScript+`(?^=)`RME), 34 bytes

```
((:x{25,}){5,})(?^1=(:.*x{30}){3})

```

Takes its input in unary, as a concatenation of strings of `x` characters whose lengths represent the numbers, separated and enclosed on both sides by `:` characters. Example: `:xxx:x:xx:` represents `3,1,2`.

Try it on replit.com \- ECMAScript+`(?^=)` (RegexMathEngine `-xli`)

```
(                # \1 = the following:
    (
        :x{25,}  # Match and consume a list element that's ≥ 25
    ){5,}        # Loop the above at least 5 times, as many times as possible
)
(?^1=            # Lookinto - match against the contents of \1
    (
        :.*      # Skip to any list element (completing the match of any
                 # previously partially-consumed list element), putting it in tail
                 # (can start in the middle of it and this is still fine, because
                 # we only need to assert that it's ≥ 30)
        x{30}    # Assert tail ≥ 30; tail -= 30
                 # No need to consume the rest of tail if it's > 30, because the
                 # ":.*" part will make sure that we finish matching at the end
                 # of this list element before skipping to a subsequent one.
    ){3}         # Loop the above 3 times
)

```

# Regex (ECMAScript or better), 38 bytes

```
(?=(:x{25,}){5,}(.*))(:.*x{30}){3}.*\2

```

Try it online! \- ECMAScript (SpiderMonkey)
Try it online! \- ECMAScript 2018 (Node.js)
Try it online! \- Perl
Try it online! \- Java
Try it online! \- Boost
Try it online! \- Python
Try it online! \- Ruby
Try it online! \- PCRE
Try it online! \- .NET
Try it on replit.com \- ECMAScript (RegexMathEngine)

```
(?=
    (
        :x{25,}  # Match and consume a list element that's ≥ 25
    ){5,}        # Loop the above at least 5 times, as many times as possible
    (.*)         # \2 = the remainder of the string
)
(
    :.*          # Skip to any list element (completing the match of any
                 # previously partially-consumed list element), putting it in tail
                 # (can start in the middle of it and this is still fine, because
                 # we only need to assert that it's ≥ 30)
    x{30}        # Assert tail ≥ 30; tail -= 30
                 # No need to consume the rest of tail if it's > 30, because the
                 # ":.*" part will make sure that we finish matching at the end
                 # of this list element before skipping to a subsequent one.
){3}             # Loop the above 3 times
.*\2             # Assert that at some subsequent position, \2 can be matched,
                 # demonstrating that the 3 loop iterations above only matched
                 # list elements that occurred within the same range of the string
                 # as that matched by the 5 loop iterations at the beginning.

```

While golfing this, I found a bug in Ruby's regex engine triggered by 39 byte version: Try it online! / Attempt This Online! \- it gives false negatives on all of the truthy test cases, while working fine in all the other regex engines.
> 2 votes

# Answer
# JavaScript (ES6), 44 bytes

```
a=>a.reduce((b,c)=>c<25?!!b:b*(2^c<30)%72,1)

```

Try it online!

This is based on Udo Borkowski's JavaScript answer which is **49 bytes**. The extra golfs are:

1. Change `(c<30?2:6)` to `(c<30?2:3)`, because multiplying by both \\$2\\$ and \\$3\\$ simultaneously is redundant and doesn't keep track of any more information than if we just multiply by two different primes. Thus instead of `864`, we can use `108` as our magic number, as the sum of the multiplicities of \\$2\\$ and \\$3\\$ is now equal to the previous multiplicity of \\$2\\$.
2. Change `(c<30?2:3)` to `(c<30?3:2)`, thus getting `72` as our magic number instead of `108`, saving 1 byte.
3. Change `(c<30?3:2)` to `(2^c<30)`, taking advantage of bitwise `^` having a lower operator precedence than the `<` comparison operator. This saves another 2 bytes.
4. Move `b>0` from the ternary condition, to its truthy argument. This saves another 2 bytes.

This is still "inverted logic", returning falsey for a "Contains a Heat Wave" and truthy for "No Heat Wave". But as a result of change #3, the return value for "Contains a Heat Wave" is sometimes `0` and sometimes `false`. This can be cleaned up by `!`, taking it to **45 bytes**: Try it online!

The original explanation (edited to reflect the changes):

Each sequence of numbers is iterated with a reduce operation starting at the reduce value \\$1\\$. If a number \\$≥ 25\\$ is seen, the reduce is multiplied by \\$3\\$. If a number \\$≥ 30\\$ is seen, the reduce is multiplied by \\$2\\$. If a number \\$\< 25\\$ is seen the reduce starts again at \\$1\\$. If the reduce is divisible by \\$72=2×2×2×3×3\\$ then a heatwave is found, and the result of the modulo operation is \\$0\\$ which results in a reduce value of \\$0\\$. Only when a heat wave was found the reduce can become \\$0\\$. Once the reduce value is \\$0\\$ it will be \\$0\\$ for all future reduces, i.e. also for the end result.

# Python 2, 59 bytes

```
lambda a:reduce(lambda b,c:[b*(2+(c<30))%72,b>0][c<25],a,1)

```

Try it online!

A port of the above. 4 bytes shorter than Udo Borkowski's Python 2 answer which is **63 bytes**.

Clean `True`/`False` output is **61 bytes**: Try it online!

# Python 3.8+, ~~62~~ 59 bytes

```
lambda a,b=1:[b:=[b*(2+(c<30))%72,b>0][c<25]for c in a][-1]

```

Try it online! / Attempt This Online!

Unfortunately `reduce` was moved into the `functools` library in Python 3. So, this uses a list comprehension workaround to match the Python 2 version's length.

Clean `True`/`False` output is **61 bytes**: Try it online! / Attempt This Online!

# Python 2, 54 bytes

```
b=1
for c in input():b=[b*(2+(c<30))%72,b>0][c<25]
1/b

```

Try it online!

This full program outputs via its exit-code:

* `1` (the program raised a `ZeroDivisionError`) if the list contains a heat wave
* `0` (the program exited normally) if it does not

# Python 3+, 60 bytes

Try it online! \- Same as the Python 2 version above, but using `eval(input())` in place of `input()`.

# Python 3.8+, 59 bytes

```
for c in eval(input())+[b:=1]:b=[b*(2+(c<30))%72,b/b][c<25]

```

Try it online! / Attempt This Online!

Alternative 59 bytes:

```
b=1
for c in eval(input()):b=[b:=b*(2+(c<30))%72,b/b][c<25]

```

Try it online! / Attempt This Online!
> 2 votes

# Answer
# Perl 5 `-pa`, 52 bytes

```
map{$_<25?$w=$h=0:$w++;$h+=$_>29;$\|=$w>4&&$h>2}@F}{

```

Try it online!
> 1 votes

# Answer
# , 35 bytes

```
1#.(1,2~:/\24<])(2<1#.29<]*4<#);.1]

```

Try it online!

Returns `0` for `Falsy` and positive integer for `Truthy`

I feel it's too descriptive, so it's certainly golfable.

## Explanation:

I split `x u;.1 y`the input list of values into sublists that are smaller or greater/equal to 25. `x` is a binary mask denoting the intervals, y is the input list

`(1,2~:/\24<])` finds if each item is greater or equal to 25; then marks the boundaries of the intervals and prepends 1 to the list for the start.

```
    (1,2~:/\24<]) 1 1 25 30 25 30 25 25 25 25 25 25 25 25 40 1 1
1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0

    ((1,2~:/\24<])<;.1]) 1 1 25 30 25 30 25 25 25 25 25 25 25 25 40 1 1
┌───┬──────────────────────────────────────┬───┐
│1 1│25 30 25 30 25 25 25 25 25 25 25 25 40│1 1│
└───┴──────────────────────────────────────┴───┘

```

`(2<1#.29<]*4<#)` Checks if the length `#` of the sublist is at least 5 and sets all items to 0 if not by multiplying the list by the result of the check; then checks if there are 3 or more items that are greater or equal to 30.

```
   ((1,2~:/\24<])(2<1#.29<]*4<#);.1]) 1 1 25 30 25 30 25 25 25 25 25 25 25 25 40 1 1
0 1 0

```

`1#.` adds up the partial results
> 1 votes

# Answer
# Java 8, 91 bytes

```
h->{int e=0,a=0,t=0;for(int i:h)t=(e=i<25?0:e+1)>4&(a=i<25?0:i<30?a:a+1)>2?1:t;return t>0;}

```

Hopefully we'll have a heat wave here in The Netherlands soon, since it's currently 13 °C again (even though it was 24 °C this weekend..)

Try it online.

**Explanation:**

```
h->{              // Method with integer-array parameter and boolean return-type
  int e=0,        //  Amount of subsequent 25+ days, starting at 0
      a=0,        //  Amount of 30+ days in the current 'heat wave', starting at 0
      t=0;        //  Result-flag, starting at 0
  for(int i:h)    //  Loop over the input-array
    t=            //   Change the flag to:
      (e=i<25?    //    If the current temperature is below 25 °C
          0       //     Reset `e` to 0
         :        //    Else (temperature is 25+ °C):
          e+1)    //     Increase `e` by 1
       >4         //    Validate if `e` is at least 5 now
      &(a=i<25?   //    If the current temperature is below 25 °C
           0      //     Reset `a` to 0
          :i<30?  //    Else if the current temperature is [25,29] °C
           a      //     Leave `a` the same
          :       //    Else (temperature is 30+ °C):
           a+1)   //     Increase `a` by 1
       >2?        //    Validate if `a` is at least 3 now:
                  //    If there is a 'heat wave':
        1         //     Change the flag `t` to 1
       :          //    Else:
        t;        //     Leave the flag `t` unchanged
  return t>0;}    //  Return whether the flag `t` is 1 now

```
> 1 votes

# Answer
# \>\<\>, 64 bytes

```
00>l3(?^$:1+{:64*)?v~~~~
  ^<v?)4:+1$~$?)+fe<
)?v^>$:@2
;n<   0<

```

Keeps track of the current number of summer days and tropical days, resets when a regular day is encountered. For every summer day it checks if the requirements for a heat wave is met.
> 1 votes

# Answer
# Powershell, ~~75~~ 73 bytes.

*-2 bytes thanks to Veskah.*

based on Javascript by @Arnauld

```
$a=$b=0;$args|?{if($_-ge25){++$a-ge5-band($b+=$_-ge30)-ge3}else{$a=$b=0}}

```

returns an array or $null. Save as `get-heatWave.ps1` and test with script https://regex101.com/r/lXdvIs/2

```
$t = @(
    @(30, 29, 30, 29, 41),
    @(1, 1, 25, 30, 25, 30, 25, 25, 25, 25, 25, 25, 25, 25, 40, 1, 1),
    @(31, 34, 34, 20, 34, 28, 28, 23, 27, 31, 33, 34, 29, 24, 33, 32, 21, 34, 30, 21, 29, 22, 31, 23, 26, 32, 29, 32, 24, 27),
    @(26, 29, 22, 22, 31, 31, 27, 28, 32, 23, 33, 25, 31, 33, 34, 30, 23, 26, 21, 28, 32, 22, 30, 34, 26, 33, 20, 27, 33),
    @(20, 31, 20, 29, 29, 33, 34, 33, 20),
    @(25, 26, 34, 34, 41, 28, 32, 30, 34, 23, 26, 33, 30, 22, 30, 33, 24, 20, 27, 23, 30, 23, 34, 20, 23, 20, 33, 20, 28),
    @(34, 23, 31, 34, 34, 30, 29, 31, 29, 21, 25, 31, 30, 29, 29, 28, 21, 29, 33, 25, 24, 30),
    @(22, 31, 23, 23, 26, 21, 22, 20, 20, 28, 24, 28, 25, 31, 31, 26, 33, 31, 27, 29, 30, 30),
    @(26, 29, 25, 30, 32, 28, 26, 26, 33, 20, 21, 32, 28, 28, 20, 34, 34),
    @(34, 33, 29, 26, 34, 32, 27, 26, 22),
    @(30, 31, 23, 21, 30, 27, 32, 30, 34, 29, 21, 31, 31, 31, 32, 27, 30, 26, 21, 34, 29, 33, 24, 24, 32, 27, 32),
    @(25, 33, 33, 25, 24, 27, 34, 31, 29, 31, 27, 23)
)

$f = @(
    @(30),
    @(31, 29, 29, 28, 24, 23, 29, 29, 26, 27, 33, 20, 26, 26, 20, 30),
    @(29, 29, 29, 47, 30),
    @(23, 31, 29, 26, 30, 24, 29, 29, 25, 27, 24, 28, 22, 20, 34, 22, 32, 24, 33),
    @(23, 24, 25, 20, 24, 34, 28, 32, 22, 20, 24),
    @(24, 28, 21, 34, 34, 25, 24, 33, 23, 20, 32, 26, 29, 29, 25, 20, 30, 24, 23, 21, 27),
    @(26, 34, 21, 32, 32, 30, 32, 21, 34, 21, 34, 31, 23, 27, 26, 32),
    @(29, 24, 22, 27, 22, 25, 29, 26, 24, 24, 20, 25, 20, 20, 24, 20),
    @(23, 33, 22, 32, 30),
    @(28, 21, 22, 33, 22, 26, 30, 28, 26, 23, 31, 22, 31, 25, 27, 27, 25, 28),
    @(27, 23, 42, 23, 22, 28),
    @(25, 20, 30, 29, 32, 25, 22, 21, 31, 22, 23, 25, 22, 31, 23, 25, 33, 23)
)

"Should be $true"
$t | % {
    [bool](.\get-heatWave.ps1 @_)
}

"Should be $false"
$f | % {
    [bool](.\get-heatWave.ps1 @_)
}

```
> 1 votes

# Answer
# 05AB1E, 18 bytes

```
.γ25@}ʒg5@}30@O3@à

```

Try it online or verify all test cases.

**Explanation:**

```
.γ   }              # Group the (implicit) input-list by sections of:
  25@               #  >= 25
      ʒ   }         # Then only leave groups of:
       g5@          #  At least 5 items
           30@      # Check for each remaining value if its >= 30 (1 if truthy; 0 if falsey)
              O     # And get the amount of truthy values per group by taking the sum
               3@   # Check if that amount is >= 3 for each
                 à  # And check if any are truthy by taking the maximum
                    # (which is output implicitly as result)

```
> 1 votes

# Answer
# APL(NARS), 100 char, 200 bytes

```
∇r←f w;c;C;k;i;x
r←i←c←C←0⋄k←≢w
→0×⍳k<i+←1⋄→3×⍳∼25>x←i⊃w⋄c←C←0⋄→2
c+←1⋄C+←x≥30⋄→2×⍳∼(c≥5)∧C≥3
r←1
∇

```

I find useful traslate program construct if() with "→LineNumber×⍳∼" test:

```
  f¨(,30)(29,29,29,47,30)(31,29,29,28,24,23,29,29,26,27,33,20,26,26,20,30)(23,31,29,26,30,24,29,29,25,27,24,28,22,20,34,22,32,24,33)(23,24,25,20,24,34,28,32,22,20,24)(24,28,21,34,34,25,24,33,23,20,32,26,29,29,25,20,30,24,23,21,27)(26,34,21,32,32,30,32,21,34,21,34,31,23,27,26,32)(29,24,22,27,22,25,29,26,24,24,20,25,20,20,24,20)(23,33,22,32,30)(28,21,22,33,22,26,30,28,26,23,31,22,31,25,27,27,25,28)(27,23,42,23,22,28)(25,20,30,29,32,25,22,21,31,22,23,25,22,31,23,25,33,23)
0 0 0 0 0 0 0 0 0 0 0 0
  f¨(30,29,30,29,41)(1,1,25,30,25,30,25,25,25,25,25,25,25,25,40,1,1)(31,34,34,20,34,28,28,23,27,31,33,34,29,24,33,32,21,34,30,21,29,22,31,23,26,32,29,32,24,27)(26,29,22,22,31,31,27,28,32,23,33,25,31,33,34,30,23,26,21,28,32,22,30,34,26,33,20,27,33)(20,31,20,29,29,33,34,33,20)(25,26,34,34,41,28,32,30,34,23,26,33,30,22,30,33,24,20,27,23,30,23,34,20,23,20,33,20,28)(34,23,31,34,34,30,29,31,29,21,25,31,30,29,29,28,21,29,33,25,24,30)(22,31,23,23,26,21,22,20,20,28,24,28,25,31,31,26,33,31,27,29,30,30)(26,29,25,30,32,28,26,26,33,20,21,32,28,28,20,34,34)(34,33,29,26,34,32,27,26,22)(30,31,23,21,30,27,32,30,34,29,21,31,31,31,32,27,30,26,21,34,29,33,24,24,32,27,32)(25,33,33,25,24,27,34,31,29,31,27,23)
1 1 1 1 1 1 1 1 1 1 1 1

```

If it is better I write less test space someone say that to me...
> 1 votes

# Answer
# C# (Visual C# Compiler), 114 bytes

```
using System.Linq;s=>s.Select((a,b)=>s.Skip(b).TakeWhile(c=>c>24)).Any(a=>a.Count()>4&&a.Where(b=>b>29).Count()>2)

```

Try it online!
> 0 votes

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

Without LINQ.

```
a=>{int b=0;foreach(int i in a){b+=i<25?-b:i>29?11:1;if(b>34)return 1;}return 0;}

```

Try it online!
> 0 votes

---
Tags: code-golf, math, array, decision-problem
---


title: Highlight a Wordle guess

text:
# Question
Title: Highlight a Wordle guess
In Wordle, you try to guess a secret word, and some letters in your guess are highlighted to give you hints.

If you guess a letter which matches the letter in the same position in the secret word, the letter will be highlighted green. For example, if the secret word is `LEMON` and you guess `BEACH`, then the `E` will be highlighted green.

If you guess a letter which is present in the secret word, but not in the correct corresponding position, it will be highlighted yellow.

If a letter appears more times in the guess than it does in the secret word, only upto as many occur in the secret may be highlighted. If any of the occurrences are in the same place, they should be preferentially highlighted green, leaving earlier letters unhighlighted if necessary.

For example, with the secret `LEMON` and the guess `SCOOP`, the second `O` will be green, because it is in the right place, but the first `O` will be unhighlighted, because there is only one `O` in the secret, and one `O` has already been highlighted.

Any of the remaining letters in the secret may be highlighted yellow if they match, as long as the right number are highlighted in total. For example, with the secret `LEMON` and the guess `GOOSE`, only one of the `O`s should be highlighted; it does not matter which.

## Task

Given two five-letter strings, a secret and a guess, highlight the letters in the guess according to the rules above.

You can "highlight" the letters using any reasonable output format. For example:

* a length-`5` list of highlight values
* a list of 5 pairs of `(letter, highlight value)`
* a mapping from indices `0`-`4` or `1`-`5` to the highlight at that position

You can choose any three distinct values to represent unhighlighted, yellow, and green. (For example, `0`/`1`/`-1`, or `""`/`"Y"`/`"G"`...)

If in doubt about the "reasonable"ness of your output format, please ask. It must be unambiguous about the ordering of highlighting in case of double letters.

## Rules

* You may assume the inputs are both of length 5 and contain only ASCII letters
* You may choose whether to accept input in uppercase or lowercase
* You may take input as a string, a list of character codes, or a list of alphabet indices (in \\$ \[0, 25\] \\$ or \\$ \[1, 26\] \\$)
* You may use any standard I/O method
* Standard loopholes are forbidden
* This is , so the shortest code in bytes wins

## Test cases

All using the secret word `HELLO`: \\$ \require{color} \newcommand{\qG}\[1\]{\colorbox{##0f0}{$ \mathtt #1 $}} \newcommand{\qY}\[1\]{\colorbox{##ff0}{$ \mathtt #1 $}} \newcommand{\qW}\[1\]{\colorbox{ ##eee}{$ \mathtt #1 $}} \\$

* `SCRAP` -\> \\$ \qW S \qW C \qW R \qW A \qW P \\$
* `HELLO` -\> \\$ \qG H \qG E \qG L \qG L \qG O \\$
* `EPOCH` -\> \\$ \qY E \qW P \qY O \qW C \qY H \\$
* `CIVIL` -\> \\$ \qW C \qW I \qW V \qW I \qY L \\$
* `BELCH` -\> \\$ \qW B \qG E \qG L \qW C \qY H \\$
* `ZOOMS` -\> \\$ \qW Z \qY O \qW O \qW M \qW S \\$ or \\$ \qW Z \qW O \qY O \qW M \qW S \\$
* `LLAMA` -\> \\$ \qY L \qY L \qW A \qW M \qW A \\$
* `EERIE` -\> \\$ \qW E \qG E \qW R \qW I \qW E \\$
* `HALAL` -\> \\$ \qG H \qW A \qG L \qW A \qY L \\$
* `LLLXX` -\> \\$ \qY L \qW L \qG L \qW X \qW X \\$ or \\$ \qW L \qY L \qG L \qW X \qW X \\$
* `LLLLL` -\> \\$ \qW L \qW L \qG L \qG L \qW L \\$

Copy and paste friendly format

# Answer
# BQN, ~~19~~ 18 bytesSBCS

Improved after getting some new ideas from trying this in K.

```
=+5>≠{⊒⌾(∾⊸⊔)˝}≍

```

Run online!

---

# BQN, ~~27~~ 24 bytesSBCS

Returns 0 for white, 1 for yellow and 2 for green.

```
+`⊸×∘≠⊏2∾(≠/⊣)(⊒<≠∘⊣)≠/⊢

```

Run online!

This is a golfed version of my `Judge` function from the Wordle solver challenge, with an improvement suggested by Marshall.
There might another approach more suitable for .

This is a tacit function taking the guess on the right and the secret on the left.
`≠/⊢` / `≠/⊣` Remove fully correct letters from the guess / secret.
Progressive indices of the shortened guess inside the shortened secret. *Progressive* means that no index is output twice and if a value is not available, the length of the vector is returned.
`<≠∘⊣` For each index, is this less than the length of the shortened secret?
`2∾` Prepend a 2 to this boolean vector.
`+`⊸×∘≠` 0s at the green positions, positive integers in increasing order at the other positions.
Index with that into the vector.

The part `+`⊸×∘≠⊏2∾` is mostly there to invert the `≠/`, it would be nice if `≠/⁼` would work instead.

```
"HELLO" (≠/⊢) "LLLXX"
# "LLXX"
"HELLO" (≠/⊣) "LLLXX"
# "HELO"
"HELO" (⊒) "LLXX"
# ⟨ 2 4 4 4 ⟩
"HELO" (⊒<≠∘⊣) "LLXX"
# ⟨ 1 0 0 0 ⟩
"HELLO" (+`⊸×∘≠) "LLLXX"
# ⟨ 1 2 0 3 4 ⟩
1‿2‿0‿3‿4⊏2∾1‿0‿0‿0
# ⟨ 1 0 2 0 0 ⟩

```
> 14 votes

# Answer
# Perl 5 \+ `-pF`, 57 bytes

Returns `2` for green, `1` for yellow and leaves others as they were.

This example pretty prints using ANSI escape codes!

```
$_=<>;s/./$F[pos]=~s!$&!#!?2:$&/ge;eval's/$F[$-++]/1/;'x5
```

Try it online!

## Explanation

Initial (implicit via `-p`) input (the target word) is stored in `$_` and split into `@F` and the guess is then stored in `$_` instead. `s///`ubstitute each letter with: if `s///`ubstituting `$&` (the current match) with `#` is successful, `2`, otherwise itself. Then `s///`ubstitute each index of `@F` left in `$_` (`s///` works on `$_` by default) with 1.
> 10 votes

# Answer
# 05AB1E, 14 bytes

```
øDÆĀ*ø`0Kvy®.;

```

Input as a list of 1-based alphabet indices; modifies the list to change green to `0` and yellow to `-1` (grey values remain the same).

Try it online or verify all test cases.

**Explanation:**

```
ø              # Zip the two (implicit) input-lists together, creating pairs
 D             # Duplicate this list of pairs
  Æ            # Reduce each inner pair by subtracting
   Ā           # Check for each that it's NOT 0 (0 if 0; 1 otherwise)
    *          # Multiply that to the pairs
     ø         # Zip/transpose; swapping rows/columns
      `        # Pop and push both lists separated to the stack
       0K      # Remove all 0s from the top list
         v     # Foreach `y` over the remaining values:
          y®.; #  Replace the first `y` with -1 in the other list
               # (after which the result is output implicitly)

```
> 9 votes

# Answer
# Retina 0.8.2, 45 bytes

```
+`(\w)(.{5})\1
+$2+
+`(\w)(.*,.*)\1
-$2-
,.*

```

Try it online! Link includes test cases. Takes input as two comma-separated words. Matching letters are changed to `+` and near-misses are changed to `-`. Explanation:

```
+`(\w)(.{5})\1
+$2+

```

Change all matching letters to `+`s (in the secret word too, so that it doesn't match later.)

```
+`(\w)(.*,.*)\1
-$2-

```

Change all near misses to `-`s.

```
,.*

```

Delete the secret word.
> 7 votes

# Answer
# , ~~84~~ 80 bytes

```
function(s,g){e=s!=g;for(i in 1:5)s[x]=g[i]=1+is.na(x<-which(s*e==g[i])[1]);g*e}

```

Try it online!

My golfing skills are quite rusty after a long break, but here it goes anyway.

Takes input as a vector of codepoints, outputs 0 for exact match, 1 for inexact match, 2 - for miss (the reverse of what is given in test cases).
> 7 votes

# Answer
# K (ngn/k), ~~32~~ 31 bytes

```
{g-(x~':x{x_x?y}\y@>g)@<>g:x=y}

```

Try it online!

Minor reordering and syntax change from the original answer below (and it returns the negation of the one below).

---

# K (ngn/k), 32 bytes

```
{(x~':x{x_x?y}\y@>g)[<>g]-g:x=y}

```

Try it online!

I saw the task being discussed in the arraylang discord, so I gave it a try myself.

Returns an array where 1 represents gray, -1 green, and 0 yellow.

```
{(x~':x{x_x?y}\y@>g)[<>g]-g:x=y}   x: correct answer, y: guess
                          g:x=y    g: green positions mask (1=green)
               y@>g     reorder the guess so that greens come first
      x{     }\         seeded scan starting with x: for each char in y,
        x_x?y             delete one copy of the char from x if it exists
  x~':              for each position, test if the output is the same as input
                    (1=gray, 0=green or yellow)
 (                 )[<>g]    reorder the result back to the original position
                             (for permutation p, <p is the inverse permutation)
                         -   (1=gray, 0=other) - (1=green, 0=other)
                             = (1=gray, 0=yellow, -1=green)

```
> 7 votes

# Answer
# K (ngn/k), 30 bytes

Takes the guess as first argument and the secret as second. Returns a list with -1 for not highlighted, 0 for yellow and 1 for green.

```
{e-^(,/(=x@>e)@'<'=y)?<>e:x=y}

```

Try it online!

```
e:x=y  booleans mask with 1s where the two words are equal
         "HALAL"="HELLO" -> 1 0 1 0 0
 >     grade down; this gives an order that would sort the equal indices to the front
         > 1 0 1 0 0     -> 0 2 1 3 4
<      grade up; inverts this permutation
         < 0 2 1 3 4     -> 0 2 1 3 4
(  )?  for each of those indices, find it in the list on the left
       Returns 0N (null) for indices that are not present in the list.
         (0 1 4 0N 0N 0N)?0 2 1 3 4 -> 0 0N 1 0N 2
^      Is null? Returns a boolean mask which has 1s for non-higlighted positions.
       ^a?b is basically "b not in a"
         ^0 0N 1 0N 2  -> 0 1 0 1 0

,/(=x@>e)@'<'=y  inner part that generates a list of indices for yellow and green highlights,
                 where the green highlights have been sorted to the front.

=y     group the secret word
         ="HELLO"    ->    "HELO"!(,0;,1;2 3;,4)
<'     grade up the indices of each group
       As the indices are sorted within each group,
       this converts each to a range from 0 to length-1.
         <'="Hello"  ->    "HELO"!(,0;,0;0 1;,0)

x@>e   sort matching values to the front in the guessed word.
         "HALAL"@>1 0 1 0 0 -> "HLAAL"
=      group this reordered string
         ="HLAAL" -> "HLA"!(,0;1 4;2 3)

Now we have two dictionaries:
  - "char in secret!0 .. number of times that char appears-1",
  - "char in guess!indices of that char, when greens are sorted to the front"

@'     pair up matching keys in the two dicts,
       and apply @ between their values.
       @ performs indexing, where out of bounds indices return nulls.
       when a key is only present in one of the dicts,
this will generate a new one with a list of nulls as value.
         ("HLA"!(,0;1 4;2 3))@"HELO"!(,0;,0;0 1;,0) -> "HLAEO"!(,0;1 4;,0N;,0N;,0N)

,/     flatten the values into a list
         ,/"HLAEO"!(,0;1 4;,0N;,0N;,0N) -> 0 1 4 0N 0N 0N

```
> 7 votes

# Answer
# Haskell, 112 bytes

```
import Data.List
f(x:y,z)=[0^x|elem x z]:f(y,delete x z)
f _=[]
x?z|x==z=(0,0)|1>0=(x,z)
((f.unzip).).zipWith(?)

```

Try it online!

Takes input as a list of integers on the range \\$\[1,26\]\\$. Outputs a list of `[]` for no match `[1]` for perfect match and `[0]` for imperfect match.

This feels like it could be shorter. Having to import `delete` is costly.
> 6 votes

# Answer
# K (ngn/k), ~~52~~ ~~46~~ 45 bytes

```
{@[g;&[#'(=x)^\:&g;#'y]#'y:(=y)^\:&g:x=y;2+]}

```

Try it online!

-1 byte from ngn (thanks!).

Starting with a list of positions showing letters that do (green `1`) and don't (grey `0`) match in the secret and guess, amend it as follows:

Ignoring the positions that are green, take the first n positions of each letter in the guess (where n is the fewer of the frequency of that letter in the secret versus in the guess), and add `2` to those positions (yellow).
> 6 votes

# Answer
# Python 3, 113 bytes

```
lambda g,w:[g[i]-w[i]and~((g[:i]+[a-b or b for a,b in zip(w,g)][i:]).count(g[i])<w.count(g[i]))for i in range(5)]

```

Try it online!

Uses `-1` for gray, `-2` for yellow and `0` for green. A further 3 bytes can be saved if `-1` is replaced by False and `-2` by True, but I dislike this output format, since `False==0`.

Input is a list of charcodes
> 4 votes

# Answer
# JavaScript,  ~~76b~~   ~~72b~~  69b

Solution found by @subzey and me while golfing the MiniWordle project.

Thanks to @emanresu for the further improvements

```
// a is the correct word (array of letters)
// b is the guessed word (array of letters)

a=>b=>b.map((s,i)=>s==a[i]?a[i]=0:s).map(s=>s?a[x=a.indexOf(s)]=~x:1)

```

Returns an array of 5 digits. 0 = black, 1 = green, anything else = yellow

For example: `f([..."TEETH"])([..."EERIE"]) == [-3, 1, 0, 0, 0]`
> 4 votes

# Answer
# K (ngn/k), 29 bytes

```
{u+^?/{x@&'x=,\x}'x*\:u:~=/x}

```

Try it online!

in: `("HELLO";guessedword)`, out: `0`=bull, `1`=cow, `2`=neither

`{` `}` function with implicit argument `x`

`~=/x` mask of where letters of the two words differ

`u:` assign to `u`

`x*\:` multiply by each left - zero out the matching letters

`{` `}'` map

`,\x` prefixes (of one of the words)

`x=,\x` masks of where letter x\[i\] occurs in x\[0...i\]

`&'x=,\x` where (masks -\> lists of indices)

`x@&'x=,\x` indexing of x with the above, i.e. for any letter `"a"`, the first occurrence turns into `,"a"` (a string of length 1), the second occurrence into `"aa"`, the third into `"aaa"`, etc.

let's call the above *rep-letters* for "replicated letters"

`?/` for each rep-letter of the guessed word, find its position among the rep-letters of the secret word; for "not found", use the special null value `0N`

`^` mask of nulls

`u+` add to `u`
> 4 votes

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

```
s=>g=>g.map((u,i)=>s[i]-u&&s.some((v,j)=>g[j]==v|u-v?0:s[j]=1))

```

Try it online!

Input array of code points, Output array of 0 = Green, true = Yellow, false = Unhighlighted.
> 3 votes

# Answer
# Charcoal, 33 bytes

```
⭆θ⎇⁼ι§ηκ+§.-‹№Ｅ…θκ⁻λ§ημι№Ｅη⁻λ§θμι

```

Try it online! Link is to verbose version of code. Outputs `+` for exact match, `-` for near miss and `.` for mismatch. Explanation:

```
 θ                                  Guessed word
⭆                                   Map over letters
    ι                               Current letter
   ⁼                                Equal to
      η                             Secret word
     §                              Indexed by
       κ                            Current index
  ⎇                                 If true then
        +                           Literal string `+` else
          .-                        Literal string `.-`
         §                          Indexed by
             №                      Count of
                       ι            Current letter in
                θ                   Guessed word
               …                    Truncated to length
                 κ                  Current index
              Ｅ                     Map over letters
                   λ                Inner letter
                  ⁻                 Remove match of
                     η              Secret word
                    §               Indexed by
                      μ             Inner index
            ‹                       Is less than
                        №           Count of
                                ι   Current letter in
                          η         Secret word
                         Ｅ          Map over letters
                            λ       Inner letter
                           ⁻        Remove match of
                              θ     Guessed word
                             §      Indexed by
                               μ    Inner index
                                    Implicitly print

```
> 3 votes

# Answer
# , 39 31 bytes

```
=(+{.e.&(,.1#.%=%\)/@i.])=|"1,:

```

Try it online!

*-8 bytes thanks to Bubbler!*

The above is Bubbler's excellent golf of the "alternate idea" I included in my original post:

```
(~:*[)(=+i.~e.&(,.1#.]=]\)&:>:]i.])~:*]

```

# , 37 bytes

```
<@(~:*[)(_*])`i.`[} ::[~&.>/@,~~:<@*]

```

Try it online!

* Input: 1-indexed integers representing index within the alphabet.
* Output: boxed list with the following scheme:
    + `0` = green
    + `_` = yellow
    + positive integers = gray

## idea

* Turn perfect matches of both target and guess into 0 by multiplying by the "not-equal" vector `~:`.
* Starting with the guess as our "previous value", reduce the letters of the target as follows:
    + If target letter not found in guess, return guess unaltered
    + If target letter found, update the first matching index of the guess to infinity `_`. This both "marks" the yellow partial match and ensures the same index won't be found again.
    + If letter found is a 0 (ie, already marked as a perfect match), update it to 0 (ie, leave it unchanged). Ensures that the reduction only touches yellow matches.
> 3 votes

# Answer
# C (gcc), ~~125~~ ~~122~~ 117 bytes

```
#define F for(i=5;i--;)g[i]
i;f(s,g,p)char*s,*g,*p;{F==s[i]?s[i]=1,g[i]=2:0;F,(p=index(g,s[i]))?*p=3:0;F>3?g[i]=4:0;}

```

Try it online!

*Saved 5 bytes thanks to tsh!!!*

Inputs a secret and a guess as two strings.
Returns the "highlights" as a list of \\$2\\$s, \\$3\\$s, and \\$4\\$s in the second input string.
With \\$2\\$ for green, \\$3\\$ for yellow, and \\$4\\$ for unhighlighted.
> 3 votes

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

```
a=>b=>b.map(y=(x,i)=>x-(c=a[i])&&(y[c]=-~y[c]*2,x)).map((x,i)=>x&&!(y[x]>>=1))

```

Try it online!

Input charcode/\[1,26\], output `true`(no), `0`(green), `false`(yellow)

# JavaScript (Node.js), 82 bytes

```
a=>b=>b.map(y=(x,i)=>x!=(c=a[i])&&(y[c]=-~y[c],x)).map((x,i)=>x&&~~y[x]&&!!y[x]--)

```

Try it online!

`0`(no match), `false`(green), `true`(yellow)
> 2 votes

# Answer
# Python 3.8 (pre-release), 92 bytes

Returns a list of `-1` for *Green*, `False` for *Yellow* and `True` for not highlighted.

```
lambda*r,c='':[-(a==b)or(c:=c+b).count(b)>sum(y!=x==b for x,y in zip(*r))for a,b in zip(*r)]

```

Try it online!
> 2 votes

# Answer
# Jelly, ~~18~~ 17 bytes

```
o@=
çW;œ-\⁻Ɲʋç@+=

```

Try it online!

*-1 because there was a completely extraneous `ɗ`*

Target on left, guess on right; `0` for gray, `1` for yellow, `2` for green.

Absolutely dreadful... There ought to be some sort of -based solution, but I've had no luck yet.

```
o@=    Dyadic helper link: mask out exact matches
  =    For each pair of corresponding elements, are they equal?
o@     Replace 0s with elements from the left argument, leaving 1s unchanged.

çW;œ-\⁻Ɲʋç@+=    Main link
ç                Mask matches out of the target,
         ç@      mask matches out of the guess,
        ʋ        and with those on the left and right:
 W;  \           Scan across the guess, starting with the masked target, by
   œ-            multiset difference;
       Ɲ         for each pair of adjacent scan results,
      ⁻          are they not equal?
           +=    Add that to the mask of exact matches.

```
> 2 votes

# Answer
# Vyxal `t`, ~~24~~ ~~23~~ 21 bytes

```
Z⁰¹-ḃ*∩÷$£0o(¥nuøḞ£)¥

```

Try it Online!

or Run all the test cases (it took me way longer to write the code to run the test cases than the program itself lol)

Port of 05AB1E answer. Can probably be golfed down a ton.

*-1 byte thanks to Aaroneous Miller*
> 2 votes

# Answer
# Julia 1.6, 72 bytes

```
a\b=(* =.==;c=a*b;b[c]=a[c].=0;c-[sum(b[i]b[1:i])>sum(b[i]a) for i=1:5])
```

Attempt This Online!

Fixed and improved version of mbeltagy's answer

Needs version 1.6+ for `(*) = (.==)`. 73 bytes in Julia 1.0
Inputs are vectors of characters, and the output is a vector with `1` for green, `0` for yellow, and `-1` for uncolored
> 2 votes

# Answer
# Python 2, 95 bytes

```
lambda g,t:[not a or a in t and t.remove(a)for a in[a[a==b:]or t.remove(a)for a,b in zip(g,t)]]

```

Try it online!

Loops over the guess twice, while removing characters from the target. Direct matches are removed in the first loop, indirect matches in the second. Requires two `list`s as input. Outputs a `list` containing 5 elements: `True` for direct match, `None` for indirect match and `False` for no match.
> 1 votes

---
Tags: code-golf, string, game, word-puzzle
---


# Question
Title: Greatest Number in a Range When The Sum of Squares of its Prime Factors are Subtracted
**The formula**

Take for instance the number 300

* The prime factors of 300 are `[2, 3, 5]` (unique numbers that are factors of 300 and prime)
* Squaring each of those numbers will give you `[4, 9, 25]`
* Summing that list will give you `4 + 9 + 25 = 38`
* Finally subtract that sum (38) from your original number `300-38 = 262` (this is the result)

---

**Input**

Your input will be a positive integer greater than 2. You must check all numbers from 2 to the input value (inclusive) and find the number that produces the greatest result with the formula above.

---

**Output**

Your output will be two numbers separated by a space, comma, newline or whatever you language allows (the separation is necessary to distinguish the two numbers). These can be output to a file, stdout, or whatever your language uses. Your goal is to find the number in the range that produces the maximum output when run through the formula above. The first number displayed should be the starting number (like 300) and the second number should be the output that the formula produced (like 262)

---

**Test Cases**
```
Input: 3       Output: 2, -2
Input: 10      Output: 8, 4
Input: 50      Output: 48, 35
Input: 1000    Output: 1000, 971
Input: 9999    Output: 9984, 9802

```

---

**Worked Through Example**

Consider the input of 10, we must run the formula for all numbers from 2-10 (inclusive)

```
Num PrimeFacs PrimeFacs^2 SumPrimeFacs^2 Result
2   [2]       [4]         4              -2
3   [3]       [9]         9              -6
4   [2]       [4]         4               0
5   [5]       [25]        25             -20
6   [2, 3]    [4, 9]      13             -7
7   [7]       [49]        49             -42
8   [2]       [4]         4               4
9   [3]       [9]         9               0
10  [2, 5]    [4, 25]     29             -19

```

As you can see the greatest result is `4`, which was a result of inputting the value `8` into the formula. That means the output for an input of `10` should be `8, 4`

---

**Scoring & Rules**

The default rules for inputs and outputs apply: Default for Code Golf: Input/Output methods
The standard loopholes are forbidden: Loopholes that are forbidden by default
Submissions can be functions or full programs

Shortest code in bytes wins

# Answer
# Pyth, ~~17~~ 15 bytes

```
_eSttm,-ds^R2{P

```

Test suite.
> 5 votes

# Answer
## Java 8 lambda, ~~247~~ ~~239~~ ~~233~~ ~~225~~ ~~224~~ ~~219~~ ~~198~~ 161 characters

I thought that must be possible in under 300 chars because... you know... Java!

And it is indeed possible even in under 200 chars!

```
m->{int n=1,u,f,F[],g,G=g=1<<31;for(;++n<=m;){u=n;F=new int[m+1];for(f=1;++f<=u;)u/=u%f<1?(F[f]=f--):1;f=0;for(int p:F)f+=p*p;g=n-f>g?(G=n)-f:g;}return G+","+g;}

```

~~I don't know whether this use of imports is legit but I assume, that it should be okay.~~ Here is the lambda ungolfed into a class:

```
public class Q80507 {
    static String greatestAfterReduction(int maxNumber) {
        int number = 1, upper, factor, primeFactors[], greatestResult, greatestNumber = greatestResult = 1 << 31; // <-- Integer.MIN_VALUE;
        for (;++number <= maxNumber;) {
            // get unique primefactors
            upper = number;
            primeFactors = new int[maxNumber + 1];
            for (factor = 1; ++factor <= upper;)
                upper /= upper % factor < 1 ? (primeFactors[factor] = factor--) : 1;

            factor = 0;
            for (int prime : primeFactors)
                factor += prime * prime;

            greatestResult = number - factor > greatestResult ? (greatestNumber = number) - factor : greatestResult;
        }
        return greatestNumber + "," + greatestResult;
    }
}

```

The primefactor-finding is based on this answer. The code uses the functionality of sets as they only save each value once, thus I don't have to care about added duplicates later on. The rest of the code is pretty straight forward, just following the question.

### Updates

Removed the newline from the output.

Thanks to @ogregoire for golfing the Integer.MIN\_VALUE to 1\<\<31!

After looking on the code again I found some more places where things could been golfed.

Thanks to @Blue for the ==0 to \<1 trick!

Removed some leftover whitespace. Also for separation only one char is needed so no need to waste one char.

Thanks again to @ogregoire for pointing out that I can return the value instead of printing it and putting together the declarations! This saved a lot!

Found out I can use a ternary instead of the second if to save one more char.

Thanks to @AstronDan for the **awesome** usage of an array which saves the import. That also gave me the possibility to shorten the first if into a ternary.
> 4 votes

# Answer
## Actually, 21 bytes

```
u2x;`;y;*@-`M;M;)@í@E

```

Try it online!

Explanation:

```
u2x;`;y;*@-`M;M;)@í@E
u2x;                   push two copies of range(2, n+1) ([2, n])
    `      `M          map:
     ;                   duplicate
      y;                 push two copies of prime divisors
        *                dot product of prime divisors lists (equivalent to sum of squares)
         @-              subtract from n
             ;M;)      duplicate, two copies of max, move one copy to bottom of stack
                 @í    get index of max element
                   @E  get corresponding element from range

```
> 3 votes

# Answer
# MATL, 18 bytes

```
:"@tYfu2^s-]v2#X>w

```

**Try it online!**

The last case takes too long for the online compiler, but it produces the correct result (it takes about 11 seconds in my computer, running on Matlab):

### Explanation

Straightforward application of the described procedure.

```
:         % Implicit input n. Range [1 2 ... n]
"         % For each
  @       %   Push that number
  tYfu    %   Duplicate. Prime factors. Unique values
  2^s-    %   Square. Sum of array values. Subtract
]         % End for each
v         % Concatenate stack contents into vertical vector
2#X>      % Max and arg max
w         % Swap. Implicit display

```
> 3 votes

# Answer
## 05AB1E, ~~19~~ ~~17~~ 16 bytes

**Code:**

```
L©f€n€O®-®)ø¦{¤R

```

**Explanation:**

```
L                    # make a list of 1..input [1,2,3,4,5,6]
 ©                   # save the list for reuse
  f                  # get primefactors of numbers in list [[],[2],[3],[2],[5],[2,3]]
   €n                # square each factor [[],[4],[9],[4],[25],[4,9]]
     €O              # sum the factors [0,4,9,4,25,13]
       ®-            # subtract from saved list [1,-2,-6,0,-20,-7]
         ®)ø         # zip with saved list [[1,1],[-2,2],[-6,3],[0,4],[-20,5],[-7,6]]
            ¦        # drop the first item (n=1) [[-2,2],[-6,3],[0,4],[-20,5],[-7,6]]
             {       # sort [[-20,5],[-7,6],[-6,3],[-2,2],[0,4]]
              ¤      # get last item [0,4]
               R     # reverse [4,0]

```

Try it online
> 3 votes

# Answer
# Bash + GNU utilities, 74

```
seq 2 $1|factor|sed -r 's/:?( \w+)\1*/-\1*\1/g'|bc|nl -v2|sort -nrk2|sed q

```
* `seq` generates all integers 2 to n
* `factor` gives the number followed by a colon, then a space separated list of all prime factors, including duplicates. e.g. the result for 12 is `12: 2 2 3`
* `sed` removes the colon and duplicate factors, then generates the required arithmetic expression. e.g. for 12: `12- 2* 2- 3* 3`
* `bc` evaluates this
* `nl` prefixes n back in (starting at 2)
* `sort` by the second column, numerically, in descending order
* `seq` prints the first line and quits.

Ideone.
> 3 votes

# Answer
## C#, 194 bytes

My first Code Golf :). I used my favorite language despite its verbosity. I started this as a C# function port of @Frozn's Java but found several ways to shrink the code further with optimizations.

```
string R(int a){int u,f,g,N=g=1<<31;for(int n=1;++n<=a;){u=n;int[]P=new int[a+1];for(f=1;++f<=u;){if(u%f<1){u/=f;P[f]=f--;}}f=0;foreach(var p in P){f+=p*p;}if(n-f>g){g=(N=n)-f;}}return N+","+g;}

```

This uses an array to store the prime factors. Because it is indexed by the factor it will replace repeated factors with copies of the factor. This allows the function to have no imports. This does not even require System.
> 3 votes

# Answer
# Brachylog, 48 bytes

```
:2:{eI$pd:{:2^.}a+:I--:I.}fF$\hor:0m:Ir.r~m[F:J]

```

### Explanation

```
Main predicate:

:2:{}fF                     Unify F with the list of all binding for which predicate 1 is
                            true, given [Input, 2] as input.
       $\hor:0m             Retrieve the max of F by diagonalizing it, taking the
                            first row, sorting that row and reversing the sorted row.
               :Ir.         Unify the Output with [I, Max],
                   r~m[F:J] [I, Max] is in F at index J (the index is unimportant)

Predicate 1:

eI                          I is an integer in the range given in Input
  $pd                       Get the list of prime factors of I, with no duplicates
     :{:2^.}a               Apply squaring to each element of that list
             +              Sum the list
              :I-           Subtract I from the sum
                 -          Multiply by -1 (let's call it Result)
                  :I.       Unify the Output with [Result, I]

```
> 2 votes

# Answer
# Jelly, 13 bytes

```
ÆfQ²S_@,µ€ḊṀṚ

```

Try it online! or verify all test cases.

### How it works

```
ÆfQ²S_@,µ€ḊṀṚ  Main link. Argument: n

        µ      Combine the chain to the left into a link.
         €     Apply it to each k in [1, ..., n].
Æf               Yield k's prime factors as a list.
  Q              Unique; deduplicate the prime factors.
   ²             Square each unique prime factor.
    S            Compute their sum.
     _@          Subtract the result from k.
       ,         Pair with k, yielding [result(k), k].
          Ḋ    Dequeue; discard the first pair which corresponds to k = 1.
           Ṁ   Get the maximum (lexicographical order).
            Ṛ  Reverse the pair.

```
> 2 votes

# Answer
# Julia, 56 bytes

```
!n=maximum(k->(k-sumabs2(k|>factor|>keys),k),2:n)[[2,1]]

```

Try it online!

### How it works

Given an input **n**, for each integer **k** such that **2 ≤ k ≤ n**, we generate the tuple **(f(k), k)**, where **f(k)** is the difference between **k** and the sum of the squares of its prime factors.

**f(k)** itself is calculated with `k-sumabs2(k|>factor|>keys)`, which factors **k** into a Dict of prime keys and exponent values, extracts all the keys (prime factors), takes the sum of their squares and subtracts the resulting integer from **k**.

Finally, we take the lexicographical maximum of the generated tuples and reverse it by accesing it at indices **2** and **1**.
> 2 votes

# Answer
# 05AB1E, 13 bytes

*Ties Dennis's Jelly answer for #1.*

```
L¦DfnO-Z©kÌ®)

```

Try it online!

```
L¦DfnO-Z©kÌ®)  # full program
         k     # push 0-based index of...
       Z       # maximum of...
               # (implicit) list of...
     O         # sums of...
               # (implicit) each element of list of...
   f           # unique prime factors of...
               # (implicit) each element of...
L D            # [1, 2, 3, ...,
               # ..., implicit input...
L D            # ]...
 ¦             # excluding the first element...
               # (implicit) with each element...
    n          # squared...
               # (implicit) with each element...
      -        # subtracted from...
               # (implicit) corresponding element in...
L              # [1, 2, 3, ...,
               # ..., implicit input...
L              # ]...
 ¦             # excluding the first element...
         k     # in...
               # (implicit) list of...
     O         # sums of...
               # (implicit) each element of list of...
   f           # unique prime factors of...
               # (implicit) each element of...
L D            # [1, 2, 3, ...,
               # ..., implicit input...
L D            # ]...
 ¦             # excluding the first element...
               # (implicit) with each element...
    n          # squared...
               # (implicit) with each element...
      -        # subtracted from...
               # (implicit) corresponding element in...
L              # [1, 2, 3, ...,
               # ..., implicit input...
L              # ]...
 ¦             # excluding the first element...
          Ì    # plus 2
       Z©  ®   # push maximum of...
               # (implicit) list of...
     O         # sums of...
               # (implicit) each element of list of...
   f           # unique prime factors of...
               # (implicit) each element of...
L D            # [1, 2, 3, ...,
               # ..., implicit input...
L D            # ]...
 ¦             # excluding the first element...
               # (implicit) with each element...
    n          # squared...
               # (implicit) with each element...
      -        # subtracted from...
               # (implicit) corresponding element in...
L              # [1, 2, 3, ...,
               # ..., implicit input...
L              # ]...
 ¦             # excluding the first element
            )  # push stack
               # implicit output

```

**Note:** If only the calculated number needed to be output, then 5 bytes could be saved by removing `©kÌ®)`.
> 2 votes

# Answer
## Clojure, 215 bytes

```
(fn j[x](apply max-key second(map(fn[w][w(- w(let[y(reduce +(map #(* % %)(set(flatten((fn f[q](let[c(filter(fn[r](=(mod q r)0))(range 2 q))](if(empty? c)q(map f c))))w)))))](if(= y 0)(* w w)y)))])(range 2(inc x)))))

```

Just follows the rules. Calculates prime factors of each number, put them to square and sum them. After that generate a list of vectors of 2 elements: initial number and its result and find the element with maximum value of second element.

You can see it online here: https://ideone.com/1J9i0y
> 1 votes

# Answer
# CJam, 32 bytes

```
ri({))_mf_|2f#:+-}/]_:e>_@#))\]p

```

Try it online!
> 1 votes

# Answer
## R 109 bytes

```
y=sapply(x<-2:scan(),FUN=function(x)x-sum(unique(as.numeric(gmp::factorize(x))^2)));c(x[which.max(y)],max(y))

```

I cheated and used a package, `gmp`.
> 1 votes

# Answer
## PowerShell v2+, ~~124~~ ~~120~~ 117 bytes

```
2..$args[0]|%{$y=$z=$_;2..$_|%{$y-=$_*$_*!($z%$_)*('1'*$_-match'^(?!(..+)\1+$)..')};if($y-gt$o){$o=$y;$p=$_}}
"$p $o"

```

The first line calculates the values, the second is just output.

We start with creating a range from `2` up to our command-line argument `$args[0]` and loop that `|%{...}`. Each loop we set helper variables equal to our current value with `$y=$z=$_`. We then loop through every number from `2` up to our current number. Each inner loop we check whether that number is a divisor `!($z%$_)` and whether it's prime `('1'*$_-match'^(?!(..+)\1+$)..')`, and if it's both we subtract the square from `$y` (the checks are done using Boolean multiplication).

Once we've gone through all prime divisors and subtracted the squares, if the number remaining is the largest we've seen so far `$y-gt$o`, we set our output variables `$o=$y;$p=$_`. After we've looped through the whole range, we simply output with a space between.
> 1 votes

# Answer
## Pyke, 17 bytes

```
FODP}mXs-)DSei@Oi

```

Try it here!
> 1 votes

# Answer
## JavaScript (ES6), ~~111~~ 105 bytes

```
f=n=>{r=n<2?[]:f(n-1);for(s=[],j=n,i=2;j>1;k%i?i++:j/s[i]=i);s.map(i=>j-=i*i,j=n);return j<r[1]?r:[n,j]}

```

No idea why I didn't think to do this recursively before.
> 1 votes

# Answer
# Python 2, ~~108~~ ~~105~~ 100 bytes

```
f=lambda n,m=2,p=1:m>n or-~f(n,m+1,p*m*m)-(n%m<p%m)*m*m
r=max(range(2,input()+1),key=f)
print r,f(r)

```

Test it on Ideone.
> 1 votes

# Answer
## Haskell, 91 bytes

```
f m=reverse$maximum[[n-sum[p^2|p<-[2..n],mod n p<1,mod(product[1..p-1]^2)p>0],n]|n<-[2..m]]

```

Usage example: `f 50`-\> `[48,35]`.

Prime factor functions are available only via `import Data.Numbers.Primes` which costs too many bytes, so I'm using @Lynn's prime checker. The rest is straight forward: for input `m` loop `n` through `[2..m]` and in an inner loop `p` through `[2..n]`. Keep all `p` that are prime and divide `n`, square and sum.
> 1 votes

# Answer
# J, 44 bytes

```
[:((],.~2+I.@e.)>./)@:}.1(-[:+/*:@~.@q:)@+i.

```

Straight-forward approach. Also returns all values of `n` that result in a maximum value.

## Usage

```
   f =: [:((],.~2+I.@e.)>./)@:}.1(-[:+/*:@~.@q:)@+i.
   f 3
2 _2
   f 10
8 4
   f 50
48 35
   f 1000
1000 971
   f 9999
9984 9802
   f 950
900 862
945 862

```
> 1 votes

# Answer
# Vyxal, 10 bytes

```
ḢλǏ²∑-;Z↑Ṅ

```

Try it Online!

Maximum by tail is useless they said. No one ever uses it they said. Well look who's laughing now.

## Explained

```
ḢλǏ²∑-;Z↑Ṅ
Ḣ      Z   # Create a list of [x, f(x)] from range(2, input + 1) where f(x) =
 λ    ;    # lambda x:
  Ǐ        #  prime factors
   ²       #  squared
    ∑      #  summed
     -     #  subtracted from x
        ↑  # maximum by tail
         Ṅ # joined on spaces

```
> 1 votes

# Answer
# Japt `-h`, 17 bytes

Tried a few different approaches but can't seem to do better than 17 :\

```
ô í ¤mÇ-k â x²ÃñÌ

```

Try it

```
õ@[XX-k â x²]ÃÅñÌ

```

Try it
> 0 votes

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