| Bytes | Lang | Time | Link |
|---|---|---|---|
| nan | Scala | 230708T143508Z | 138 Aspe |
| 021 | Uiua | 231116T044005Z | chunes |
| 012 | Nekomata | 230710T030136Z | alephalp |
| 319 | Desmos | 230711T185307Z | Jakdad J |
| 112 | Java | 230727T101712Z | Top Golf |
| 011 | Husk | 230712T040721Z | Leo |
| 025 | BQN | 230711T203501Z | DLosc |
| 081 | Swift 5.9 | 230711T182633Z | macOSist |
| 033 | Q | 230710T221151Z | scottste |
| 017 | Pyth | 230710T212040Z | CursorCo |
| 047 | R | 230708T194518Z | pajonk |
| 036 | Nial | 230708T133552Z | ovs |
| 012 | Thunno 2 S | 230708T202701Z | The Thon |
| 084 | Excel | 230709T061838Z | Jos Wool |
| 063 | Arturo | 230708T223021Z | chunes |
| 059 | Raku | 230708T213932Z | Sean |
| 051 | Haskell | 230708T210516Z | xnor |
| 058 | Python 3 | 230708T185223Z | Ethan C |
| 064 | C clang | 230708T174622Z | c-- |
| 026 | Charcoal | 230708T133635Z | Neil |
| 013 | Husk | 230708T120906Z | Dominic |
| 083 | Retina 0.8.2 | 230708T114605Z | Neil |
| 9375 | Vyxal s | 230708T055315Z | lyxal |
| 251 | Racket | 230708T100843Z | Ed The & |
| 052 | JavaScript ES6 | 230708T100714Z | Arnauld |
| 013 | 05AB1E | 230708T094959Z | Command |
| 057 | JavaScript V8 | 230708T065121Z | l4m2 |
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
}
}
Uiua, 21 bytes
/+♭×1_2=⊟⊃/+/×↘1↻1⍉◫3
/+♭×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
Nekomata, 12 bytes
ᵉpttᵋ+*:,,$Ĉ
ᵉ 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
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]
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
Husk, 11 bytes
#ṁMzė+**↓2¹
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
BQN, 25 bytes
+´((+˝∾×˝∾×˝)0‿2⊏·⍉3⊸↕)⊸=
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
Swift 5.9, 112 106 103 92 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.
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
Pyth, 17 bytes
/smmvXk1d.:z3"**+
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
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)}
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.
Thunno 2 S, 12 bytes
D2ỵZıçpS¹=2ḋ
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
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.
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]]
$[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
Raku, 59 bytes
->$_,\n{sum n X==m:ov/(.).(.)/».&{|(.sum,[*] @$_)[0,1,1]}}
m:ov/(.).(.)/finds alloverlapping 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 usingmap.)(.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.sumsums those booleans, treatingTrueas 1 andFalseas 0.
Haskell, 51 bytes
n%(a:t@(b:c:l))=0^(a+c-n)^2+2*0^(a*c-n)^2+n%t
_%_=0
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]
53 bytes
n%l=sum[1|(a,c)<-zip l$drop 2l,x<-[a+c,a*c,a*c],x==n]
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:]))
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--)
Charcoal, 26 bytes
NθIΣEEΦη‹¹κ⁺ι§ηκ№⟦ΣιΠιΠι⟧θ
Try it online! Link is to verbose version of code. Takes the landmine number as the first input. Explanation:
Nθ First input as a number
η Second input
Φ Filtered where
¹ Literal integer `1`
‹ Is less than
κ Current index
E Map over digits
ι Current digit
⁺ Concatenated with
η Second input
§ Indexed by
κ Current index
E 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
I Cast to string
Implicitly print
Husk, 13 bytes
#Σz§:+o´e*↓2¹
# # 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
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.
Vyxal s, 75 bitsv2, 9.375 bytes
3lƛy$₍Π∑⁰=B
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
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.
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))]
[right (list-ref -landscape (add1 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!
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
05AB1E, 13 bytes
Ц¦©+s®*D)QOO
I feel like at least one byte can be golfed, but I can't figure out how
JavaScript (V8), 57 bytes
x=>k=>x.reduce((r,t,i)=>r+(t+x[i+=2]==k)+2*(t*x[i]==k),0)
map and reduce same length