# Landmine Number I

## Background

You have been given the task of calculating the number of landmines in a field.

You must calculate the landmine score given a list/string of numbers and the landmine number.

The landmine number tells you where landmines are.

For each digit:

1. if the left digit plus the right digit is equal to the landmine number, add one to the landmine score.
2. if the left digit times the right digit is equal to the landmine number, add two to the landmine score.
3. if both 1 and 2 are satisfied, add three to the landmine score.

Note: The very first and last digits cannot have landmines because there are no adjacent numbers to the left and right of them respectively.

• Sample Input: Two strings/numbers/lists. The length of the first number will be maximum 256 characters/numbers long. It will only contain numbers. The second number will tell you the landmine number.

• Output: Return the landmine score.

Explained Examples

Input => Output
18371 4 => 2


There are only two landmines here:

• One on 8, because 1+3 = 4.
• One on 7, because 3+1 = 4.
Input => Output
2928064 4 => 4


There are four landmines here:

• Three on 9, because 2+2 = 2x2 = 4.
• One on 6, because 0+4 = 4.
Input => Output
33333 9 => 6


There are six landmines here:

• Two on each of the second, third, and fourth threes.
Input => Output
9999999999 100 => 0


No combination of addition and multiplication will yield 100.

Input => Output
1234567890 8 => 4


There are four landmines here:

• Two on 3, because 2x4 = 8
• One on 4, because 3+5 = 8
• One on 9, because 8+0 = 8

Test Cases

Input ~> Output

18371 4 ~> 2
2928064 4 ~> 4
33333 9 ~> 6
9999999999 100 ~> 0
1234567890 8 ~> 4

22222 4 ~> 9
00000000000000 0 ~> 36
12951 10 ~> 4
123123123123 3 ~> 11
828828828 16 ~> 11


This is , so shortest answer wins.

...

Landmine Number Series

• The instructions seem unclear, in part because they're conflating "number" and "digit": I think it means "from the second digit to the second-last digit in the first number, run these tests on the digits immediately to the left and right of the selected digit." Also, the relevance of any of this to landmines is lost on me, I'm afraid. Commented Jul 8, 2023 at 17:14
• @DewiMorgan Thanks for the reply! Changed some wording related to digits. Using landmines as a metaphor because "Check if adding or multiplying adjacent digits matches a number" sounded boring. Commented Jul 8, 2023 at 17:26
• That's fair :) And the edits definitely help me, thanks! Commented Jul 8, 2023 at 17:29
• Shouldn't the second example be "Three on 9, because 2+2 = 2x2 = 4." instead of "Three on 8"? Commented Jul 10, 2023 at 8:04
• @KevinCruijssen Thanks, fixed. Commented Jul 10, 2023 at 10:29

# Husk, 13 bytes

#Σz§:+o´e*↓2¹


Try it online!

#             # how many times is arg 2 present in:
Σ            # flatten the results of
z           # zipping together
#   arg 1 and
↓2¹ #   arg 1 without its first 2 elements
# using the function
§:         #   join together
+        #     sum of each pair of elemnts
o´e     #     and 2 copies of
*    #     product of each pair of elements

• 2 bytes shorter by mapping a list of functions
– Leo
Commented Jul 11, 2023 at 1:48
• @Leo - That's beautiful. I was going to update my answer, but struggled for so long trying to work-through it to write an explanation that I realize I'd not have been able to make it without your help... So I think it's more than just an improvement, and you should post it yourself. Commented Jul 11, 2023 at 11:40
• @Leo - but, anyway, thanks for the lesson in constructing & mapping a list of curried zip-functions! Commented Jul 11, 2023 at 11:40
• In fact it did take me a while to get it right... Thanks, I'll post it as a new answer!
– Leo
Commented Jul 12, 2023 at 3:46

# 05AB1E, 13 bytes

Ð¦¦©+s®*D)QOO


Try it online!

I feel like at least one byte can be golfed, but I can't figure out how

• Nice approach! I originally had something like this, but your approach is better/shorter. :) And I also have the feeling a byte could be golfed somehow, but probably not. Although there are a lot of 13-byte alternatives using a somewhat similar approach, like D¦¦øDP€DsO«QO for example. Commented Jul 10, 2023 at 8:22

# JavaScript (ES6), 52 bytes

Expects (n)(array).

n=>a=>a.map(p=v=>s+=p+v==n|2*(p*(p=a,a=v)==n),s=0)|s


Try it online!

# Husk, 11 bytes

#ṁMzė+**↓2¹


Try it online!

Inspired by Dominic van Essen's answer, with some added functional trickery to make it shorter.

## Explanation

A necessary introduction: z+ is a function that vectorizes the + operation to sum two lists element by element. If a list is longer than the other, extra elements are dropped. z* does the same thing with multiplication.

For example (in pseudocode) z+[1,2][3,6,9] = [4,8]

#ṁMzė+**↓2¹   Example input: [1,2,3,2] 4
ė+**      A) a list of three functions: [+,*,*]
↓2¹   B) the first input without its first two values: [3,2]
Mz          For each function f in A, do zfB
this will result in a list of partially-applied functions
missing the second argument for the vectorized sum (or multiplication):
[z+[3,2], z*[3,2], z*[3,2]]
ṁ            Apply each of these functions to the (implicit) first input:
[z+[3,2][1,2,3,4], z*[3,2][1,2,3,4], z*[3,2][1,2,3,4]] =
[[4,4], [3,4], [3,4]]
and concatenate the results: [4,4,3,4,3,4]
#             Count how many times the (implicit) second input appears in this list: 4


# Racket - 251 bytes

#!racket
(let*([L(map(λ(c)(-(char->integer c)48))(filter char-numeric?(string->list(read-line))))][M(read)][R(curry list-ref L)])(for/sum([i(range 1(-(length L)1))])(let*([l(R(- i 1))][r(R(+ i 1))][m(=(* l r)M)])(count(λ(c)c)(list(=(+ l r)M)m m)))))


Input must be on separate lines, first input is the landscape, and the second input is the number representing the landmine.

Try it online!

## Explanation

### Input, filtering, mapping

First the program splits the landscape string into a list of characters. It filters out any characters that aren't digits then proceeds to map over the list, turning all the characters into their respective numeric digits.

### Looping

We then create a for/sum loop that iterates over the list from indices 1 through length - 2 (length - 1 is the last index of the list, but it can't have a landmine). As the loop iterates, it collects the landmine count for each digit. Once it has completed the iteration, the loop returns the summed-up counts.

### Counting landmines

The way we count the landmines for a digit is simple. We create a boolean list that contains the results of two different equality checks: addition of the left and right digits and the multiplication of the left and right digits must both be the same as the number representing the landmine in order to return #t. Since the multiplication of the left and right digits give two points instead of one, we repeat the check.

(list (= (+ left right) landmine)
(= (* (left right) landmine)
(= (* (left right) landmine))


Once we have created the list, we can pass it to the count function. But there is still one ingredient we need because count requires two inputs, a proc and a list. The proc function returns a boolean value as count iterates the loop. If the value is #t, then count adds it to the total count.

But we already have the #t and #f values, and we don't need to change them. That is where the identity function comes in handy. The identity function takes a value and returns it the same way as it is. This is how the function looks like in Python:

def identity(value):
return value


### Putting it all together and testing

This is the final resulting code:

#lang racket

(require (only-in rackunit check-eq?))

; count-landmines: String Number -> Number
; Counts the number of landmines in a string.
(define (count-landmines landscape landmine)
(let* ([-landscape (map (lambda (char) (- (char->integer char) 48))
(filter char-numeric? (string->list landscape)))])
(for/sum ([index (range 1 (sub1 (length -landscape)))])
(let* ([left (list-ref -landscape (sub1 index))]
[multeq (= (* left right) landmine)])
(count identity (list (= (+ left right) landmine) multeq multeq))))))

(displayln "Tests are running...")
(check-eq? (count-landmines "18371" 4) 2 "18371 4")
(check-eq? (count-landmines "2928064" 4) 4 "2928064 4")
(check-eq? (count-landmines "33333" 9) 6 "33333 9")
(check-eq? (count-landmines "9999999999" 100) 0 "9999999999 100")
(check-eq? (count-landmines "1234567890" 8) 4 "1234567890 8")

(check-eq? (count-landmines "22222" 4) 9 "22222 4")
(check-eq? (count-landmines "00000000000000" 0) 36 "00000000000000 0")
(check-eq? (count-landmines "12951" 10) 4 "12951 10")
(check-eq? (count-landmines "123123123123" 3) 11 "123123123123 3")
(check-eq? (count-landmines "828828828" 16) 11 "828828828 16")
(displayln "Tests are complete!")


## Conclusion

Hope you enjoyed reading my explanation! I had fun with both writing the code and the answer :D

Have a wonderful weekend ahead everyone!

# Vyxals, 75 bitsv2, 9.375 bytes

3lƛy$₍Π∑⁰=B  Try it Online! Takes long number as a list of digits then landmine number. Didn't almost accidentally call it a landline number. ## Explained 3lƛy$₍Π∑⁰=B­⁡​‎‎⁪⁡⁪⁠⁪⁡⁪‏⁠‎⁪⁡⁪⁠⁪⁢⁪‏⁠⁪⁪‏​⁡⁠⁡‌⁢​‎‎⁪⁡⁪⁠⁪⁣⁪‏⁠⁪⁪‏​⁡⁠⁡‌⁣​‎‎⁪⁡⁪⁠⁪⁤⁪‏⁠‎⁪⁡⁪⁠⁪⁢⁡⁪‏⁠⁪⁪‏​⁡⁠⁡‌⁤​‎‎⁪⁡⁪⁠⁪⁢⁢⁪‏⁠‎⁪⁡⁪⁠⁪⁢⁣⁪‏⁠‎⁪⁡⁪⁠⁪⁢⁤⁪‏⁠⁪⁪‏​⁡⁠⁡‌⁢⁡​‎‎⁪⁡⁪⁠⁪⁣⁡⁪‏⁠‎⁪⁡⁪⁠⁪⁣⁢⁪‏⁠⁪⁪‏​⁡⁠⁡‌⁢⁢​‎‎⁪⁡⁪⁠⁪⁣⁣⁪‏⁠‎⁪⁡⁪⁠⁪⁣⁤⁪‏⁠‎⁪⁡⁪⁠⁪⁤⁡⁪‏⁠‎⁪⁡⁪⁠⁪⁤⁢⁪‏‏​⁡⁠⁡‌⁢⁣​‎‏​⁢⁠⁡‌­
3l           # ‎⁡Get all overlapping windows of size 3 of the long input
ƛ          # ‎⁢To each window:
y$# ‎⁣ Remove the middle item ₍Π∑ # ‎⁤ Push a list of [product, sum]. I love parallel apply. ⁰= # ‎⁢⁡ And check whether each item equals the landmine number B # ‎⁢⁢Convert from binary # ‎⁢⁣The s flag sums the resulting list 💎 Created with the help of Luminespire at https://vyxal.github.io/Luminespire  • We’re you thinking of the landline number 00 44 20 7946 0857? Don’t call it it’s a fake Commented Jul 8, 2023 at 13:39 • @Iamkindofalanguagedev More importantly, don't answer calls from it either. – Neil Commented Jul 8, 2023 at 15:35 # Charcoal, 26 bytes ＮθＩΣＥＥΦη‹¹κ⁺ι§ηκ№⟦ΣιΠιΠι⟧θ  Try it online! Link is to verbose version of code. Takes the landmine number as the first input. Explanation: Ｎθ First input as a number η Second input Φ Filtered where ¹ Literal integer 1 ‹ Is less than κ Current index Ｅ Map over digits ι Current digit ⁺ Concatenated with η Second input § Indexed by κ Current index Ｅ Map over digit pairs ι Current pair Σ Digital sum ι Current pair Π Digital product ι Current pair Π Digital product ⟦ ⟧ Make into list № Count matches of θ First input Σ Take the sum Ｉ Cast to string Implicitly print  # C (clang), 64 bytes f(*a,l,n){return--l>1?(*a+a[2]==n)+2*(*a*a[2]==n)+f(a+1,l,n):0;}  Try it online! • iterative alternative: also 64 bytes, but with unsequenced modification and access to 'a' – c-- Commented Jul 8, 2023 at 17:47 # Thunno 2S, 12 bytes D2ỵZıçpS¹=2ḋ  Try it online! #### Explanation D2ỵZıçpS¹=2ḋ # implicit input D # duplicate the first input 2ỵ # remove the first two items Z # zip them together ı # map: ç # parallelly apply: p # product S # sum ¹= # equals second input? 2ḋ # convert from binary # implicit output  # JavaScript (V8), 57 bytes x=>k=>x.reduce((r,t,i)=>r+(t+x[i+=2]==k)+2*(t*x[i]==k),0)  Try it online! map and reduce same length # Python 3, 98 75 58 bytes lambda n,l:sum((x+y==l)+2*(x*y==l)for x,y in zip(n,n[2:]))  Try it online! The inputs are the string of numbers (as a list of ints) and the landmine number (as an int). The function loops through each each pair of valid (i, i+2) indices in the list and calculates the landmine score using boolean addition. Edit: used zip to save 17 bytes (credit to c--) • Welcome to Code Golf, and nice answer! I believe taking the list of ints is allowed Commented Jul 8, 2023 at 19:09 • 58 bytes using zip() – c-- Commented Jul 8, 2023 at 19:43 # Haskell, 51 bytes n%(a:t@(b:c:l))=0^(a+c-n)^2+2*0^(a*c-n)^2+n%t _%_=0  Try it online! Uses 0^(x-y)^2 as an arithmetic version of the indicator function sum[1|x==y]. Recursing turned out shorter than my attempts to use zip. 53 bytes n%l=sum$do(a,c)<-zip l$drop 2l;[1|a+c==n]++[2|a*c==n]  Try it online! 53 bytes n%l=sum[1|(a,c)<-zip l$drop 2l,x<-[a+c,a*c,a*c],x==n]


Try it online!

# Raku, 59 bytes

->$_,\n{sum n X==m:ov/(.).(.)/».&{|(.sum,[*] @$_)[0,1,1]}}


Try it online!

• m:ov/(.).(.)/ finds all overlapping matches for sequences of three digits in the input number.
• ».&{ ... } passes each match object to the brace-delimited code block. (It's one byte shorter than using map.)
• (.sum, [*] @$_) produces a two-element list of the sum and product of the first and last digits in each match. • [0, 1, 1] slices into that list, to append an extra copy of the second element (the product). • | flattens that list into the map output. • n X== ... crosses the landmine number with each sum and product using the numeric equality operator ==, producing a list of booleans. Each product contributes two of the same boolean, thanks to the slice above. • sum sums those booleans, treating True as 1 and False as 0. • rather than the slice to add an extra copy, you can do base 2: :2[n X==[*](@$_),.sum]
– Jo King
Commented Jul 10, 2023 at 5:12

# Nial, 39 36 bytes

++mate team[+,[+,*,*][2drop,-2drop]]


Try it online!

• First time using Nial, so this is probably improvable
– ovs
Commented Jul 8, 2023 at 13:36

# R, 50 47 bytes

Edit: -3 bytes thanks to @Dominic van Essen.

\(x,n){h=t=x[-1:-2];h[]=x;sum(h+t==n,2*!h*t-n)}


Attempt This Online!

Defines explicitly both head and tail to add/multiply, because of usually handy (and here annoying) R recycling of vectors.
Uses also a trick that !a-b is the same as a==b with the same byte-count, but due to precedence, we can multiply the former without extra parentheses.

• 47 bytes... Commented Jul 9, 2023 at 5:26
• @DominicvanEssen nice hack, thanks! Commented Jul 9, 2023 at 18:22

# Swift 5.9, 11210610392 81 bytes

Edit: First solution was actually 112 bytes, not 114.

(1...m.count-2).reduce(0){$0+(m[$1-1]+m[$1+1]==n ?1:0)+(m[$1-1]*m[$1+1]==n ?2:0)}  Where m is an [Int] representing the minefield, and n is an Int representing the mine number. Ungolfed (plus header): func landmineScore(mines: [Int], mineNumber: Int) -> Int { (1...(mines.count - 2)).reduce(0) { result, index in result + (mines[index - 1] + mines[index + 1] == mineNumber ? 1 : 0) + (mines[index - 1] * mines[index + 1] == mineNumber ? 2 : 0) } }  I can't remove the spaces to the left of the ?s, because a trailing ? is interpreted as an optional-chain. • Removed 6 bytes (from 112 to 106). Used a range instead of m.indices. Commented Jul 11, 2023 at 19:02 • Removed 3 bytes (from 106 to 103). Replaced endIndex with count. Commented Jul 11, 2023 at 19:31 • Removed 9 bytes (from 103 to 92). Realized I was an idiot and no longer needed the if statement. Commented Jul 11, 2023 at 19:43 • Removed 11 bytes (from 92 to 81). Replaced the for-in loop with a call to reduce. Also eliminated the let statement, which saved 7 bytes, surprisingly enough. Commented Jul 11, 2023 at 20:01 • Comments are relatively ephemeral, so if you want to preserve explanations of your golfing process, it's conventional to have them in the answer body. Commented Jul 11, 2023 at 20:05 # Retina 0.8.2, 83 bytes  \d+|\d ,;,$&$* &(,?;)?,(1*),;,1*,;,((1)*),;,(1*,;,)*(?(1)(?<-4>\2)*(?(4)^)|\3\2)$


Try it online! Link includes test cases. Explanation:

 \d+|\d
,;,$&$*


Convert the landmine number and each of the numbers in the list to unary. Each unary number is preceded by three characters to allow three places for the following expression to match for each number, one for when the two numbers sum to the landmine number and two for when their product equals the landmine number.

&


Count all overlapping matches.

(,?;)?,(1*),;,1*,;,((1)*)


For each interior number, match the numbers on the left and right. The number on the right is matched in two different ways so it can be both added and multiplied. Also allow the match to start up to three separator characters before the left number.

,;,(1*,;,)*


Skip ahead to the landmine number.

(?(1)(?<-4>\2)*(?(4)^)|\3\2)$ If there were at least two separator characters then check that the product of the two matched numbers equals the landmine number otherwise check that the sum does. The regular expression would be 84 bytes without the conditional, but it still needs .NET capture groups in order to perform the multiplication:  \d+|\d ,;,$&$* &(,?;?,)(1*),;,1*,;,((1)*)(,;,1*)*(,?\1(?<-4>\2)*(?(4)^)|,;\1\3\2)$


Try it online! Link includes test cases.

# Arturo, 63 bytes

$[a n][0i:0loop drop a 2'x[if=x+a\[i]n[1+]if=x*a\[i]n[2+]'i+1]]  Try it! $[a n][                 ; a function taking a list a and integer n
0                   ; push landmine score
i:0                 ; assign 0 to i
loop drop a 2'x[    ; loop over a sans first 2 elements; assign current elt to x
if=x+a\[i]n[1+] ; add 1 to score if x + a[i] equals n
if=x*a\[i]n[2+] ; add 2 to score if x * a[i] equals n
'i+1            ; increment i in place
]                   ; end loop
]                       ; end function


# Excel, 84 bytes

=SUM(TOCOL(LET(a,LAMBDA(b,MID(A1,ROW(A:A)+b,1)),(a(0)+a(2)=B1)+2*(a(0)*a(2)=B1)),2))


String in A1; landmine number in B1.

# Pyth, 17 bytes

/smmvXk1d.:z3"**+


Try it online!

### Explanation

/smmvXk1d.:z3"**+"Q    # implicitly add "Q
# implicitly assign Q = eval(input)
#                   z = input() (second input)
m          "**+"     # map lambda d over "**+"
m     .:z3          #   map lambda k over all substrings of length 3 in z
Xk1d              #     replace the middle char of k with d
v                  #     and evaluate
s                     # flatten nested list
/                 Q    # count occurrences of Q


# Q, 33 bytes

implemented as a function with two implicit arguments, x and y. x is a list of ints (the "field") and y is an int (the landmine score).

{sum(y=sum x)+2*y=prd x:2 -2_\:x}
q) f: {sum(y=sum x)+2*y=prd x:2 -2_\:x}
q) f[10 vs 1234567890; 8]
4
q) f[1 2 3 1 2 3 1 2 3 1 2 3; 3]
11


# BQN, 25 bytes

+´((+˝∾×˝∾×˝)0‿2⊏·⍉3⊸↕)⊸=


Try it at BQN online!

### Explanation

+´((+˝∾×˝∾×˝)0‿2⊏·⍉3⊸↕)⊸=
(                    )⊸   Using the left argument (array of digits):
3⊸↕       Get all windows (contiguous subarrays) of length 3
as rows of a 2D array
⍉         Transpose rows and columns
0‿2⊏·           Keep the first and last rows
(+˝∾×˝∾×˝)                 Make a 1D array containing their sums, products, and
products again
=  Equality with the right argument (1s when equal, 0s
otherwise)
+´                          Sum


# Desmos, 319 bytes

https://www.desmos.com/calculator/n5dzd6tvqr

Input is a list of numbers.

f(a,b)=\sum_{n=1}^{\operatorname{length}(a)}\left[\left\{i=1:0,\left\{i=\operatorname{length}(a):0,\left\{a\left[i-1\right]+a\left[i+1\right]=b:1,0\right\}+\left\{a\left[i-1\right]a\left[i+1\right]=b:2,0\right\}\right\}\right\}\ \operatorname{for}\ i\ =\ \left[1,...\operatorname{length}(a)\right]\right]\left[n\right]

• How did you get 319 bytes? Please include the source text of the code in your answer. Commented Jul 24, 2023 at 0:18
• Fixed! thanks for pointing that out Commented Aug 19, 2023 at 22:56

# Nekomata, 12 bytes

ᵉpttᵋ+*:,,$Ĉ  Attempt This Online! ᵉ Parallelly apply the following two unary functions: p Choose a prefix tt Tail of tail ᵋ Parallelly apply the following two binary functions: + Add * Multiply (This step forces the prefix to have the same length as the tail of tail) :, Duplicate and join , Join$     Swap
Ĉ    Count


# Uiua, 21 bytes

/+♭×1_2=⊟⊃/+/×↘1↻1⍉◫3


Try it!

/+♭×1_2=⊟⊃/+/×↘1↻1⍉◫3
◫3  # windows of length three
⍉    # transpose
↻1     # rotate one
↘1       # drop one
⊃/+/×         # sum and product of columns
⊟              # couple
=               # where is it equal to input?
×1_2                # multiply by [1 2]
♭                    # deshape
/+                     # sum


# Scala, 170 163 bytes

Golfed version. Try it online!

(f,m)=>(0/:f.zipWithIndex.slice(1,f.size-1)){case(s,(n,i))=>val l=f(i-1)-48;val r=f(i+1)-48;if((l+r==m)&&(l*r==m))s+3 else if(l+r==m)s+1 else if(l*r==m)s+2 else s}


Ungolfed version. Try it online!

object Main {
def landmineScore(field: String, mineNumber: Int): Int = {
field.zipWithIndex.slice(1, field.length - 1).foldLeft(0) {
case (score, (num, idx)) =>
val left = field(idx - 1).asDigit
val right = field(idx + 1).asDigit
val current = num.asDigit

if ((left + right == mineNumber) && (left * right == mineNumber))
score + 3
else if (left + right == mineNumber) score + 1
else if (left * right == mineNumber) score + 2
else score
}
}

def main(args: Array[String]): Unit = {
println(landmineScore("18371", 4)) // Output: 2
println(landmineScore("2928064", 4)) // Output: 4
println(landmineScore("33333", 9)) // Output: 6
println(landmineScore("9999999999", 100)) // Output: 0
println(landmineScore("1234567890", 8)) // Output: 4
println(landmineScore("22222", 4)) // Output: 9
println(landmineScore("00000000000000", 0)) // Output: 36
println(landmineScore("12951", 10)) // Output: 4
println(landmineScore("123123123123", 3)) // Output: 11
println(landmineScore("828828828", 16)) // Output: 11

}
}


# Java, 120 112 Bytes

var l=range(2,n.length).filter(i->n[i-2]+n[i]==t).count()+range(2,n.length).filter(i->n[i-2]*n[i]==t).count()*2;`

-8 Thanks to @ceilingcat