title: Ravenity of Cube Distance Numbers

text:
# Question
Title: Ravenity of Cube Distance Numbers
*Inspired by this Numberphile entry*

## Background

The ***cube distance numbers*** of an integer *n* are defined here as the set of integers that are  distance away for a given *x*. For a simple example, with `n=100` and `x=2`, the *cube distance numbers* are `{92,108}`.

This can be extended into a larger set simply by varying *x*. With `x ∈ {1,2,3,4}` and the same `n=100`, we have the resultant set `{36,73,92,99,101,108,127,164}`.

Let's define ***CD(n,x)*** as the set of all integers `n ± z³` with `z ∈ {1,2,3,...,x}`.

Now we can focus on some of the special properties of these *cube distance numbers*. Of the many special properties that numbers can have, the two properties we're interested in here are *primality* and *prime divisors*.

For the above example *CD(100,4)*, note that `73, 101, 127` are all prime. If we remove those from the set, we're left with `{36,92,99,108,164}`. All prime divisors of these numbers are (in order) `{2,2,3,3,2,2,23,3,3,11,2,2,3,3,3,2,2,41}`, which means we have 5 distinct prime divisors `{2,3,23,11,41}`. We can therefore define that *CD(100,4)* has ***ravenity***1 of `5`.

The challenge here is to write a function or program, in the fewest bytes, that outputs the *ravenity* of a given input.

### Input

* Two positive integers, `n` and `x`, in any convenient format.

### Output

* A single integer describing the *ravenity* of the two input numbers, when calculated with *CD(n,x)*.

### Rules

* Input/output can be via any suitable method.
* Standard loophole restrictions apply.
* For ease of calculation, you can assume that the input data will be such that *CD(n,x)* will only have positive numbers in the set (i.e., no *CD(n,x)* will ever have negative numbers or zero).
* The function or program should be able to handle input numbers so that `n + x³` fits in your language's native integer data type. For example, for a 32-bit signed integer type, all input numbers with `n + x³ < 2147483648` are possible.

### Examples

```
n,x   - output
2,1   - 0   (since CD(2,1)={1,3}, distinct prime divisors={}, ravenity=0)
5,1   - 2
100,4 - 5
720,6 - 11

```

---

### Footnotes

1 - So named because we're not interested in the *cardinal*ity of the set, but a different type of bird. Since we're dealing with "common" divisors, I chose to use the common raven.

# Answer
# Jelly, 16 bytes

```
ŒRḟ0*3+µÆfFœ-µQL

```

Takes **x** and **n** as command-line arguments, in that order. Try it online!

### How it works

```
ŒRḟ0*3+µÆfFœ-µQL  Main link. Arguments, x, n

ŒR                Range; yield [-x, ..., x].
  ḟ0              Filter out 0.
    *3            Cube each remaining integer.
      +           Add n to all cubes.
       µ          Begin a new, monadic link. Argument: A (list of sums)
        Æf        Factorize each k in A.
          F       Flatten the resulting, nested list.
           œ-     Perform multiset difference with A.
                  If k in A is prime, Æf returns [k], adding on k too many to the
                  flat list. Multiset difference with A removes exactly one k from
                  the results, thus getting rid of primes.
                  If k is composite (or 1), it cannot appear in the primes in the
                  flat list, so subtracting it does nothing.
             µ    Begin a new, monadic link. Argument: D (list of prime divisors)
              Q   Unique; deduplicate D.
               L  Compute the length of the result.

```
> 4 votes

# Answer
# Pyth - ~~21~~ ~~19~~ 18 bytes

I wonder if there's a trick.

```
l{st#mP+Q^d3s_BMSE

```

Test Suite.

```
l                   Length
 {                  Uniquify
  s                 Combine divisor lists
   t#               Filter by if more than one element
     PM             Take prime factorization of each number
       +RQ          Add each num in list to input
          s_BM      Each num in list and its negative (with bifurcate)
              ^R3   Cube each num in list
                 SE Inclusive unary range - [1, 2, 3,... n] to input

```
> 4 votes

# Answer
# Julia, 107 bytes

```
f(n,x)=endof(∪(foldl(vcat,map(k->[keys(factor(k))...],filter(i->!isprime(i),[n+z^3for z=[-x:-1;1:x]])))))

```

This is a function that accepts two integers and returns an integer.

Ungolfed:

```
function f(n, x)
    # Get all cube distance numbers
    cubedist = [n + z^3 for z = [-x:-1; 1:x]]

    # Filter out the primes and zeros
    noprimes = filter(i -> !isprime(i) && i > 0, cubedist)

    # Factor each remaining number
    factors = map(k -> [keys(factor(k))...], noprimes)

    # Flatten the list of factors
    flat = foldl(vcat, factors)

    # Return the number of unique elements
    return endof(∪(flat))
end

```
> 3 votes

# Answer
## J, 30 bytes

```
#@~.@(,@:q:-.0&,)@:+(|#^&3)@i:

```

This is a dyadic verb, used as follows:

```
   f =: #@~.@(,@:q:-.0&,)@:+(|#^&3)@i:
   100 f 4
5

```

Try it here.

## Explanation

```
#@~.@(,@:q:-.0&,)@:+(|#^&3)@i:
                            i:  Range from -x to x
                    (     )@    Apply this verb to the range:
                       ^&3        a) every item cubed
                     |            b) absolute value of every item
                      #           c) every item in a) repeated b) times; this removes 0
                                     and produces some harmless duplication
                   +            Add n to every element of the resulting list
     (          )@:             Apply this verb to the resulting vector:
             0&,                  a) the vector with 0 appended
      ,@:q:                       b) flat list of prime divisors in the vector
                                     (and some extra 0s since we flatten an un-even matrix)
           -.                     c) list b) with elements of a) removed; this gets rid of
                                     the extra 0s and all primes that were in the list
#@~.@                           Remove duplicates and take length

```
> 2 votes

# Answer
# MATL, 21 bytes

```
:3^t_h+tZp~)"@Yf!]vun

```

Input is `x`, `n` separated by a newline.

**Try it online!**

### Explanation

```
:       % take n implicitly. Generate [1,2,...,n]
3^      % raise to 3, element-wise
t_h     % duplicate, negate, concatenate horizontally: [1,2,...,n,-1,2,...-n]
+       % take x implicitly. Add to that array
t       % duplicate
Zp      % array that contains true for primes
~       % logical negate
)       % apply index to keep only non-primes
"       % for each number in that array
  @     %   push that number
  Yf!   %   prime factors, as a column array
]       % end for each
v       % concatenate vertically all factors
u       % remove repeated factors
n       % number of elements of that array. Implicitly display

```
> 2 votes

# Answer
# 05AB1E, ~~20~~ 19 bytes

Code:

```
L3mD(«-Dp_Ïvyf`})Úg

```

Input in the form `x`, `n`. Uses **CP-1252** encoding.

Try it online!
> 2 votes

# Answer
# Python 3.5, 218 198 bytes:

(*Thanks to @Blue for saving me 20 bytes.)*

```
lambda r,n:len({z for z in{v for f in{t for u in[[r-q**3,r+q**3]for q in range(1,n+1)]for t in u if any(t%g<1 for g in range(2,t))}for v in range(2,f)if f%v<1}if all(z%g>0 for g in range(2,z))})

```

A nice one-lined lambda function, although it may be a bit long. Since I was using Python, I had to come up with my own way of finding the composites for the first step, and then the prime divisors for the last step, so it was not very easy, and this was the shortest I, by myself. could get it to. Nonetheless, it does what it needs to, and I am proud of it. :) However, any tips for golfing this down a bit more are welcome.
> 2 votes

# Answer
# Ruby, ~~132~~ ~~120~~ 114 bytes

I'm well aware that this solution still needs a lot of golfing. Any golfing tips are welcome.

```
require'prime'
->n,x{(-x..x).map{|i|j=n+i**3;j.prime?||(j==n)?[]:j.prime_division.map{|z|z[0]}}.flatten.uniq.size}

```

**Ungolfing:**

```
require 'prime'

def ravenity(n, x)
  z = []
  (-x..x).each do |i|
    j = n + i**3
    m = j.prime_division
    if j.prime? || j == n
      z << []
    else
      z << m.map{|q| q[0]}
    end
  return z.flatten.uniq.size
end

```
> 1 votes

# Answer
# PARI/GP, 79 bytes

```
(n,x)->omega(factorback(select(k->!isprime(k),vector(2*x,i,n+(i-(i<=x)-x)^3))))

```

Here is my original straightforward implementation. The optimized version above combines the two vectors into a single, slightly more complicated vector.

```
(n,x)->omega(factorback(select(k->!isprime(k),concat(vector(x,i,n-i^3),vector(x,i,n+i^3)))))

```
> 1 votes

# Answer
## Ruby, 138 bytes

```
->(n,x){require'prime'
v=((-x..x).to_a-[0]).map{|i|n+i**3}.reject{|e|Prime.prime?(e)}
Prime.each(v[-1]).select{|i|v.any?{|e|e%i==0}}.size}

```

It was a *pun*y challenge. :-)
> 1 votes

# Answer
# Python 3.5 - ~~177~~ ~~175~~ 159 bytes

Any golfing tips welcome :)

```
a=range
p=lambda n:any(n%x<1for x in a(2,n))
r=lambda n,x:len(set(sum([[x for x in a(2,z+1)if z%x<1&1>p(x)]for z in filter(p,[n+z**3for z in a(-x,x+1)])],[])))

```

### Ungolfed:

```
def is_composite(n):
    return any(n % x == 0 for x in range(2, n))

def prime_factors(n):
    return {x for x in range(2, n+1) if n % x == 0 and not is_composite(x)}

def ravenity(n, x):
    nums = [n + z**3 for z in range(-x, x+1)]
    nums = filter(is_composite, nums)
    factors = map(prime_factors, nums)
    factors = sum(factors, [])
    #remove duplicates
    factors = set(factors)
    return len(factors)

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), 90 bytes

```
Tr[1^Union[First/@Join@@FactorInteger/@Select[z=Range@#2^3;Join@@{#-z,#+z},Not@*PrimeQ]]]&

```

Try it online!

un-golfed: the code is read mostly from right to left,

```
F[n_, x_] :=
  Length[Union[                                        (* number of unique elements   *)
    First /@                                           (* drop multiplicities         *)
      Join @@                                          (* join all prime factor lists *)
        FactorInteger /@                               (* compute prime factors       *)
          Select[                                      (* select those...             *)
            Join @@ {n - Range[x]^3, n + Range[x]^3},  (* ...candidates...            *)
            Not@*PrimeQ]]]                             (* ...that are not prime       *)

```
> 0 votes

---
Tags: code-golf, math, primes, set-partitions
---


title: Number in overlapping range

text:
# Question
Title: Number in overlapping range
You are given two integers between lets say 1 and 12, `one` and `two`
and a integer between lets say 0 and 4 which is called `range`.
The challange is to decide if `one` is inside or equal the range from `two` ± `range`.
**The range is restarting with 1 after 12 and vise versa.**

For example, if `one = 2`, `two = 11` and `range = 3`, the result is `true`, as `one` is the the range `[8, 9, 10, 11, 12, 1, 2]`.

The input has to be 3 seperated integers, the order doesn't matter. Input via string with seperators possible. But the Input has to consist of numbers reading as '10' and not 'A' e.g.

Test cases:

```
one=7  two=6  range=0   result=false
one=5  two=6  range=1   result=true
one=8  two=11 range=3   result=true
one=1  two=11 range=3   result=true
one=2  two=10 range=3   result=false
one=11 two=1  range=2   result=true
one=6  two=1  range=4   result=false
one=12 two=1  range=3   result=true

```

Shortest valid answer in bytes wins.

# Answer
# Stax, 7 bytes

```
₧╝g╙╖²╞

```

Run and debug it

It takes input as space separated `[range] [one] [two]` and outputs `0` for false, `1` for true.

In pseudo-code:

```
d = abs(one - two)
return min(d, 12 - d) <= range

```

Hm, that's probably almost a python submission.
> 2 votes

# Answer
# Jelly, ~~10~~ ~~8~~ 10 bytes

```
ŒR’+%12‘Ɠe

```

Try it online!

Saved 2 bytes thanks to Mr. Xcoder

+2 bytes due a bug if `one = 12`

I believe this meets the criteria. Takes `one` from STDIN, `range` as left argument and `two` as right argument
> 6 votes

# Answer
# JavaScript (ES6), 38 bytes

```
(a,b,r)=>((a=a<b?b-a:a-b)>6?12-a:a)<=r

```

Try it online!

---

# JavaScript (Node.js), 53 bytes

Silly branchless method. Expects BigInts. Returns \\$0\text{n}\\$ or \\$1\text{n}\\$.

```
(a,b,r)=>0x4C5C038B885n>>((a-=b)*a+347n*r)%282n%46n&1n

```

Try it online!
> 5 votes

# Answer
# Python 2, 52 bytes

```
lambda a,b,c:a in[i%12or 12for i in range(b-c,b-~c)]

```

Try it online!

# Python 2, 52 bytes

```
lambda a,b,c:any(set(range(b-c,b-~c))&{a,a-12,a+12})

```

Try it online!

---

# Python 3, 50 bytes

```
lambda a,b,c:any({*range(b-c,b-~c)}&{a,a-12,a+12})

```

Try it online!
> 4 votes

# Answer
# 05AB1E, ~~11~~ ~~8~~ 7 bytes

```
α6Ýûsè@

```

-3 bytes by porting *@Arnauld*'s JavaScript answer, so make sure to upvote him!
-1 byte thanks to *@Grimy*.

Inputs in the same order as the challenge description: `one`; `two`; `range`.

Try it online or verify all test cases.

**Explanation:**

```
α        # Take the absolute difference between the first two (implicit) inputs one & two
 6Ý      # Push the list [0,1,2,3,4,5,6]
   û     # Palindromize it: [0,1,2,3,4,5,6,5,4,3,2,1,0]
    sè   # Swap to get the earlier number again, and use it to index into the list
      @  # Then check if the (implicit) input range is larger than or equal to this value
         # (after which the result is output implicitly)

```
> 4 votes

# Answer
# Java 10, ~~70~~ 38 bytes

```
(o,t,r)->((o=o<t?t-o:o-t)>6?12-o:o)<=r

```

-32 bytes by porting *@Arnauld*'s JavaScript answer.

Try it online.

**Explanation:**

```
(o,t,r)->                  // Method with three integer parameters and boolean return-type
 ((o=o<t?t-o:o-t)          //  Replace `o` with abs(t-o)
   >6?                     //   And if it's smaller than 6:
      12-o                 //    Use 12-o
     :                     //   Else (it's larger than or equal to 6):
      o                    //    Use o itself
 )<=r                      //  And check if that is smaller than or equal to r

```
> 3 votes

# Answer
# Python 2, 31 bytes

```
lambda o,t,r:5-r<(o-t+6)%12<7+r

```

Try it online!

**Python 2, 33 bytes**

```
lambda o,t,r:abs((o-t+6)%12-6)<=r

```

Try it online!
> 2 votes

# Answer
# Julia 1.0, 35 bytes

```
f(o,t,r)=o in@.mod(t-1+(-r:r),12)+1

```

Try it online!
> 2 votes

# Answer
# JavaScript, 37 bytes

```
r=>b=>g=a=>a-12<b-r?g(a+12):a-12<=b+r

```

Try it online!
> 2 votes

# Answer
# Wolfram Language (Mathematica), 24 bytes

```
Abs@Mod[#-#2,12,-6]<=#3&

```

Try it online!
> 1 votes

# Answer
# Japt, 11 bytes

```
aV
aC mU §W

```

Try it
> 1 votes

# Answer
# Haskell, 42 bytes

```
t#r=(`elem`[1+(n-1)`mod`12|n<-[t-r..t+r]])

```

`two # range` returns a function which when applied to `one` returns a `Bool`.

Try it online!
> 1 votes

# Answer
# Ruby, 45 characters

```
->o,t,r{[*1..12].rotate(t-r-1)[0..r*2].any?o}

```

Nothing fancy, just a chance to use `Array#rotate`.

Sample run:

```
irb(main):001:0> ->o,t,r{[*1..12].rotate(t-r-1)[0..r*2].any?o}[2, 11, 3]
=> true

```

Try it online!
> 1 votes

# Answer
# Haskell, 27 bytes

```
o%t=(abs(mod(o-t+6)12-6)<=)

```

Try it online!
> 1 votes

# Answer
# Charcoal, 11 bytes

```
‹⁵⁺Ｎ↔⁻⁶↔⁻ＮＮ

```

Try it online! Link is to verbose version of code. Takes the size of the range as the first input. Output uses Charcoal's default Boolean format of `-` for true, nothing for false. Explanation:

```
         ＮＮ Two inputs
       ↔⁻   Absolute difference
      ⁶     Literal 6
    ↔⁻      Absolute difference
  ⁺Ｎ        Plus range
‹⁵          Is greater than 5

```
> 1 votes

# Answer
# , 48 bytes

```
function(a,b,r){a%in%c(9:12,1:12,1:4)[-r:r+b+4]}

```

Try it online!

Pretty straightforward, I struggled for a while to find the best way to test if a was in the given range. There is likely a method I haven't seen or tried yet.
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~78 bytes~~ ~~80 bytes~~ 72 bytes

```
(a,b,r)=>Enumerable.Range(b-r,2*r+1).Select(x=>(x+12)%12).Contains(a%12)

```

Try it online!

Edit: Range was incorrect, I forgot to count the item itself, adding 2 bytes. But I bit the bullet dealing with C#'s modulus actually being *remainder*, saving 8 bytes. Technically, this code actually treats 12 as 0, but this is still valid in this context.
> 1 votes

# Answer
# C#, 158 bytes

```
using System;public class P{public static void Main(string[]a){int w=Math.Abs(int.Parse(a[0])-int.Parse(a[1]));Console.Write((w>6?12-w:w)<=int.Parse(a[2]));}}

```

Try Online
> 1 votes

# Answer
# MathGolf, 7 bytes

```
-±_B,╓≥

```

Try it online!

Other valid 7-byters include:

```
-±7rñ§≥
-7rñ╡§≥

```

I found a **4-byter** which solves every test case, but doesn't solve the problem in general:

```
-±Σ≥

```

Try it online!

The approach of the 7-byters are basically ports of existing 7-byte solutions. The 4-byter relies on the fact that the digit sum of the absolute difference of the first two is less than the third input for all test cases. That correlates with the desired output for the test cases, but not in general.
> 1 votes

# Answer
# Perl 5, 63 bytes

```
sub f{grep$_[0]==$_%12,(1..36)[11+$_[1]-$_[2]..11+$_[1]+$_[2]]}

```

Try it online!

Ungolfed:

```
sub f {
  my($one, $two, $range) = @_;
  my @n = (1..36);
  return 0 + grep $one==$_%12, @n[ 11+$two-$range ..
                                   11+$two+$range ];
}

```
> 0 votes

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


title: Building a Metronome

text:
# Question
Title: Building a Metronome
# Introduction

Some days ago I needed a metronome for something. I had none available so I downloaded an app from the App Store. The app had a size of 71 MB!!!
**71 MB for making tic-toc...?!**
So code-golf came into my mind and I was wondering if some of you guys could improve this.

# Challenge

Golf some code that outputs some sound. It's pretty irrelevant what kind of sound. If required create some sound file... but a System beep will do the job as well. (Here is some sound I created... nothing special.)

**Input**: The beats per minute the metronome outputs.

# Example

This is a non-golfed Java-version! It's just to show you the task.

```
public class Metronome {
  public static void main(String[] args) throws InterruptedException {
    int bpm = Integer.valueOf(args[0]);
    int interval = 60000 / bpm;

    while(true) {
        java.awt.Toolkit.getDefaultToolkit().beep();
        // or start playing the sound
        Thread.sleep(interval);
        System.out.println("Beep!");

    }
  }
}

```

# Rules

You may not use external libaries, only tools of the language itself are allowed.
Only the bytes of the source code count... not the sound file.

This is , so the submission with the least amount of bytes wins!

### EDIT:

**Example output:** So something like this would be the output for *120 bps*: link

# Answer
> 19 votes
## Mathematica, 26 bytes

```
Pause[Beep[];60/#]~Do~∞&

```

`Do` is normally used as a "for" loop in the narrowest sense: repeat this piece of code for each `i` from `x` to `y`... or even just repeat this piece of code `n` times. Instead of a number `n` we can give it infinity though to create an infinite loop. The loop body is `Pause[Beep[];60/#]` which is just a golfy way of writing `Beep[];Pause[60/#]` where `#` is the function argument.

If it's admissible for the solution to blow up the call stack eventually, we can save one byte with a recursive solution:

```
#0[Beep[];Pause[60/#];#]&

```

# Answer
> 14 votes
# Pyth, ~~11~~ ~~10~~ 9 bytes

*Thanks to Adnan for reminding me about `#`.*

```
#C7.dc60Q

```

Forever (`#`), print `C`har code `7`. Then sleep (`.d`) `60` seconds divided by (`c`) input (`Q`).

# Answer
> 8 votes
# JavaScript, ~~36 45 42 41~~ 34 bytes

*Saved 1 byte thanks to @RikerW*

*Saved 1 byte thanks to @ETHproductions*

```
n=>{for(;;sleep(60/n))print("\7")}

```

This is a function.

If I use ``\7``, SpiderMonkey complains octal literals are deprecated.

## Alternative, 31 bytes

```
n=>{for(;;sleep(60/n))print``}

```

The problem is the unprintables are stripped but this should work.

# Answer
> 8 votes
# Bash, ~~53~~ ~~55~~ 41 bytes

Thanks to @Dennis for shaving off *14 bytes*1

Okay, truth time: I'm terrible at golfing bash. Any help would be so very appreciated.

```
echo " ";sleep `bc -l<<<60/$1`;exec $0 $1
      ^ That's ASCII char 7
```

1 Holy crap. No wonder nobody can outgolf Dennis.

# Answer
> 7 votes
# JavaScript ES6 (browser), 43 bytes

This may be stretching the rules:

```
x=>setInterval('new Audio(1).play()',6e4/x)

```

Give this function a name (e.g. `F=x=>...`) and enter it in the browser console on this page. Then call the function with your bps, e.g. `F(60)`, and wait for the magic to happen. :-)

Why does this work? Well, `b.html` is in the same folder as a file named `1`, which is the sample sound file from the OP. I'm not sure if this is within the rules (I guess it's like the shell version; it needs to be run in a specific environment), but it was worth a shot.

### Safer version, 57 bytes

If the above code isn't allowed for some reason, try this instead:

```
x=>setInterval('new Audio("//ow.ly/Xrnl1").play()',6e4/x)

```

Works on any page!

# Answer
> 6 votes
# Python, 68 67 57 bytes

*Saved 1 byte thanks to @FlagAsSpam*

*Saved 9 bytes thanks to @Adnan*

```
import time
a=input()
while 1:print"\7";time.sleep(60./a)

```

Also it took 2 bytes less after converting line endings to UNIX format.

Older version, that actually takes bpm as command line argument (66 bytes):

```
import sys,time
while 1:print"\7";time.sleep(60./int(sys.argv[1]))

```

# Answer
> 6 votes
# 05AB1E, 31 bytes

Code:

```
I60s/[7ç?D.etime.sleep(#.pop())

```

If I had a built-in for waiting N seconds, this could have been 11 bytes. Unfortunately, this is not the case. Here is the explanation:

```
I                               # Push input
 60                             # Push 60
   s                            # Swap the top 2 items
    /                           # Divide the top 2 items
     [                          # Infinite loop
      7ç                        # Push the character \x07
        ?                       # Output it, which give a sound
         .e                     # Evaluate the following as Python code
           time.sleep(       )  # Wait for N seconds
                      #         # Short for stack
                       .pop()   # Pop the last item

```

Uses the ISO 8859-1 encoding.

# Answer
> 6 votes
# osascript, 39 bytes

```
on run a
repeat
beep
delay 60/a
end
end
```

There is literally a command called beep? Sweeeet!

Runnable only on Mac OS X due to restricted license, but to run, do:

```
osascript -e "on run a
repeat
beep
delay 60/a
end
end" bpm
```

# Answer
> 4 votes
## AutoIt, 56 bytes

```
Func _($0)
While Sleep(6e4/$0)
Beep(900,99)
WEnd
EndFunc

```

# Answer
> 4 votes
# Vitsy, 14 bytes

```
a6*r/V1m
<wVO7
```

Verbose mode (interpreter coming soon):

```
0:                              // a6*r/V1m
push a; // 10
push 6;
multiply top two; // 60
reverse stack; // bpm on top
divide top two; // bpm/60
save/push permanent variable;
push 1;
goto top method; // goes to 1
1:                              // <wVO7
go backward; // infinite loop, from the bottom of 1
wait top seconds;
save/push permanent variable; // pushes the bpm in terms of seconds of delay
output top as character;
push 7;
```

Basically, I use the `w` operator to wait a certain number of seconds as specified by `bpm/60`, wrapped in an infinite loop. Then, I make noise with the terminal output of ASCII character 7 (`BEL`).

# Answer
> 4 votes
# C#, 118 bytes

```
class A{static int Main(string[]a){for(;;System.Threading.Thread.Sleep(60000/int.Parse(a[0])))System.Console.Beep();}}

```

Basic solution.

# Answer
> 4 votes
# Java, ~~103~~ 82 bytes

Thanks to @Justin for shaving off 21 bytes!

Oh, geez.

```
void x(int b)throws Exception{for(;;Thread.sleep(60000/b))System.out.print('\7');}
```

Method and golfed version of the sample program.

# Answer
> 3 votes
## GMC-4 Machine Code, 21.5 bytes

The GMC-4 is a 4-bit computer by a company called Gakken to teach the principles of assembly language in a simplified instruction set and computer. This routine takes input in data memory addresses `0x5D` through `0x5F`, in big-endian decimal (that is, one digit per nibble).

The algorithm is basically adding the input to memory and waiting 0.1s, until it's at least 600, and then subtracting 600 and beeping, in an infinite loop. Since the GMC-4 has a bunch of register swap functions but no register *copy* functions, this is done the hard way.

In hex (second line is position in memory):

```
A24A14A04 80EC AF5A2EF AE5A1EF AD5A0EF 8A6 F2AF09 86ADEEE9F09
012345678 9ABC DEF0123 4567890 ABCDEF0 123 456789 ABCDEF01234

```

In assembly:

```
    tiy 2     ;ld y, 0x2
    AM        ;ld a, [0x50 + y]
    tiy 1
    AM
    tiy 0
    AM
start:
    tia 0     ;ld a, 0x0
    cal timr  ;pause for (a+1)*0.1 seconds
    tiy F
    MA        ;ld [0x50 + y], a
    tiy 2
    cal DEM+  ;add a to [0x50 + y]; convert to decimal and carry.
    tiy E     ;do the same for the second digit
    MA
    tiy 1
    cal DEM+
    tiy D     ;and the third.
    MA
    tiy 0
    cal DEM+
    tia A
    M+
    jump beep
    jump start
beep:
    tia 6
    tiy D
    cal DEM-
    cal SHTS  ;'play short sound'
    jump start

```

*Disclaimer:*

I don't actually own a GMC-4. I've meticulously checked this program with documentation from online, but I may have made a mistake. I also don't know the endianness. It looks like the GMC-4 is big-endian, but I'm not sure. If anyone owns a GMC-4 and can verify this/tell me the endianness of the GMC-4, I'd much appreciate it.

# Answer
> 3 votes
## C, 48 bytes

```
void f(int b){while(printf(""))Sleep(60000/b);}
                            ^ literal 0x07 here

```

A Windows-only solution (Sleep() function, to be specific).

I also (ab)used the fact that printf() returns the number of characters printed to use it as infinite loop condition.

There IS a character between double-quotes in printf() call, but it is not displayed here for some reason. If in doubt, copy and paste into Sublime Text 2 or Notepad++, the character will be displayed as `BEL`.

This started as a C++ solution but it kinda fell into the C-subset of C++ (because, you know, `Sleep()` is a bit shorter than `std::this_thread::sleep_for(std::chrono::milliseconds())`) and `printf()` is shorter than `std::cout<<`).

# Answer
> 3 votes
## AppleScript 94 bytes

I know I'm pretty late, and this is my first post here, but whatever.

```
display dialog""default answer""
set x to 60000/result's text returned
repeat
beep
delay x
end
```

Ungolfed:

```
display dialog "" default answer ""
set x to 60000 / (result's text returned)
repeat
    beep
    delay x
end repeat

```

# Answer
> 2 votes
# VBScript, ~~113~~ 66 bytes

```
a=InputBox("")
Do
WScript.Echo(Chr(7))
WScript.Sleep(60000/a)
Loop

```

This program is simple enough; it takes input, echoes the BEL character, and waits. Thanks to Niel for shaving off almost half the program!

# Answer
> 2 votes
# Ruby, ~~37~~ 33 bytes

```
m=->b{loop{puts"\7"
sleep 6e1/b}}

```

Pretty straightforward.

This is a lambda function. If you wanted 60 bpm, you'd do: `m[60]`.

# Answer
> 2 votes
# Japt, 30 bytes

```
6e4/U i`?w Au¹o('../1').play()

```

The `?` should be the literal byte `9A`. Test it online! (Sorry about the pop-up delaying the first few beats; this will be removed soon.)

### How it works

```
6e4/U i"new Audio('../1').play()  // Implicit: U = input bps
6e4/U                             // Calculate 60000 / U.
      i                           // Set a timed event every that many milliseconds,
       "new Audio('../1').play()  // running this code every time.
                                  // ../1 is the path to the file used in my JS entry.

```

# Answer
> 2 votes
# Perl 5, 36 bytes

```
{{$|=print"\a";sleep 60/$_[0];redo}}

```

A subroutine; use it as

```
sub{{$|=print"\a";sleep 60/$_[0];redo}}->(21)

```

# Answer
> 2 votes
# Mumps, 18 bytes

```
R I F  H 60/I W *7

```

Read the BPM into variable I, then F {with two spaces after} is an infinate loop. Halt for 60 seconds / BPM, then write $CHR(7) {Ascii: BEL} to standard output, giving the audio output required, then restart at the infinite loop.

# Answer
> 2 votes
# Java, 321 chars

Sounds very good. Works only on systems with MIDI support.

```
import javax.sound.midi.*;import java.util.*;class A{public static void main(String[] a) throws Exception{int d=new Scanner(System.in).nextInt();Synthesizer b=MidiSystem.getSynthesizer();b.open();MidiChannel c=b.getChannels()[0];c.programChange(116);while(true){c.noteOn(0,100);Thread.sleep((int)(d/.06));c.noteOff(0);}}}

```

.

# Answer
> 2 votes
# ChucK, 90 bytes

White noise that is turned on and off every two ticks.

```
60./Std.atoi(me.arg(0))*1000=>float s;while(1){Noise b=>dac;s::ms=>now;b=<dac;s::ms=>now;}

```

# Explanation

```
60./Std.atoi(me.arg(0)) //Convert the input to an int and divide 60 by it
*1000                   //Multiply by 1000 (in order to avoid s::second)
=>float s;              //Store it as a float in variable s
while(1)                //Forever,
{Noise b=>dac;          //Connect a noise generator b to the audio output
s::ms=>now;             //Wait for s milliseconds
b=<dac;                 //Disconnect b from the audio output
s::ms=>now;}            //Wait for s milliseconds

```

This is made to turn on the sound on a beat, then turn it off on the beat after.

# ~~98~~ 93 byte version (fancier)

White noise played for 10 milliseconds per tick.

```
60./Std.atoi(me.arg(0))*1000-9=>float s;while(1){Noise b=>dac;10::ms=>now;b=<dac;s::ms=>now;}

```

This is made to be a click instead of constant noise being turned on and off.

# Answer
> 1 votes
# Jolf, 7 bytes, noncompeting

I added sounds after this very fine challenge was made.

```
TΑa/Αaj
T       set an interval
 Αa      that plays a short beep (Α is Alpha)
   /Αaj  every 60000 / j (the input) seconds. (Αa returns 60000)

```

If you so desire to clear this sound, take note of the output. Say that number is `x`. Execute another Jolf command `~CP"x"`, and the interval will be cleared.

# Answer
> 1 votes
# Zsh, 32 bytes

```
<<<$'\a'
sleep $[60./$1]
. $0 $1

```

Based on the leading bash answer, but `source`s instead of `exec`s. The TIO link sources `$0:a` because of how the original file is executed, but it will work without it.

Try it online!

# Answer
> 1 votes
# Stax, 17 bytes

```
ü7»♥O╚⌂╥☻≈OyM╜Δ∩`

```

or, unpacked:

```
4|A48*x/W2|A]pc{| }*

```

The program outputs bytes that, when fed through the command line tool aplay with default setting, produce a metronome noise. The input is used as bpm

example:

```
example-stax-interpreter metronome.stax -i "60" | aplay

```

You should hear a horrible beeping noise at the desired bpm

# Answer
> 0 votes
# Bash + bc + \>\<\>, 44 bytes

Playing on the fact that the \>\<\> interpreter lets you define a tick time :

```
python fish.py -t $(bc -l<<<"2/$1/60") -c 7o

```

The \>\<\> code is `7o` and should output the `BEL` character, producing a system beep. It will loop until interrupted.
The `-t` value is set to (2 / RPM ) / 60 so that the whole code is played RPM * 60 times per second.

# Answer
> 0 votes
# SmileBASIC, 26 bytes

```
INPUT B$BGMPLAY@8T+B$+"[C]

```

It can play any general midi instrument, though anything above 9 will use more bytes.

---
Tags: code-golf, music, audio
---


title: caN it be acrOnymised?

text:
# Question
Title: caN it be acrOnymised?
The Typical Way to Make an Acronym Out of a Phrase Is to Take the First Letter of Each Word: `TTWMAOPITFLEW`. howeveR, sometimEs, you can make an acronym of random leTters In a seNtence such As like this: `RETINA`. The only condition is that the letters have to be in the correct order. For instance:

* `LORD` can be acronymised from `Hello World`: `heLlO woRlD`
* `LEOD` cannot be acronymised from `Hello World`, as no `l`s are before `e`

Your task is to take two strings as input as to determine if one can be acronymised into the other.

The first input, the phrase, will only contain letters (`A-Z` or `a-z`) and spaces, and the second input, the acronym, will only contain letters (`A-Z` or `a-z`). The acronym will always be shorter, or of equal size, to the phrase, and both the acronym and the phrase will be, at minimum, 1 letter long. You may choose which case (upper or lower) you want the inputs to be.

You may choose any two values to represent `true` and `false`, as long as those values are consistent.

This is so the shortest code in bytes wins

## Examples

```
HELLO WORLD, LORD -> true
CODE GOLF AND CODING CHALLENGES, DANGLE -> true
SANDBOX FOR PROPOSED CHALLENGES, CODE -> false
HELLO WORLD, LLLD -> true
HELLO WORLD, LLDL -> false
NEW YORK POLICE DEPARTMENT, NOODLE -> false
MASSACHUSETTS INSTITUTE OF TECHNOLOGY, MUTTON -> true
BOB, BOB -> true
PRESIDENT OF THE UNITED STATES, I -> true

```

# Answer
# Brachylog, 1 byte

Try it online!
> 8 votes

# Answer
# Java 8, ~~46~~ ~~39~~ ~~38~~ 35 bytes

```
a->b->a.matches(b.replace("",".*"))

```

-7 bytes thanks to *@tsh*.
-1 byte thanks to *@NahuelFouilleul*.

Try it online.

**Explanation:**

```
a->b->         // Method with two String parameters and boolean return-type
  a.matches(   //  Check if the first input matches the regex:
   b           //   The second input,
    .replace("",".*"))
               //   where every character is surrounded with ".*"

```

*For example:*

```
a="HELLO WORLD"
b="LORD"

```

Will do the check:

```
"HELLO WORLD".matches("^.*L.*O.*R.*D.*$")

```

(The `^...$` will add the `String#matches` builtin implicitly, since it will always try to match the entire String.)
> 5 votes

# Answer
# C (gcc), 47 bytes

```
f(a,b)char*a,*b;{a=!*b||*a&&f(a+1,b+(*a==*b));}

```

Try it online!
> 4 votes

# Answer
# 05AB1E, 3 bytes

```
æIå

```

Try it online!

```
æ              # power set of the first input
 I             # second input
  å            # does a contain b?
               # implicit output

```
> 3 votes

# Answer
# Python 2, 48 bytes

```
lambda s,a:re.search('.*'.join(a),s)>0
import re

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog Unicode), 17 bytes

Full program. Prompts for phrase, then acronym.

```
0∊⊃(⍳⍨↓⊢)/⍞,⊂⌽0,⍞

```

Try it online!

prompt for phrase
`"HELLO WORLD"`
`"HELLO WORLD"`

`0,` prepend a zero
`[0,'H','E','L','L','O',' ','W','O','R','L','D']`
`[0,'H','E','L','L','O',' ','W','O','R','L','D']`

reverse
`['D','L','R','O','W',' ','O','L','L','E','H',0]`
`['D','L','R','O','W',' ','O','L','L','E','H',0]`

enclose (to treat as a whole)
`[['D','L','R','O','W',' ','O','L','L','E','H',0]]`
`[['D','L','R','O','W',' ','O','L','L','E','H',0]]`

`⍞,` prepend the prompted-for acronym:
`['L','L','L','D',['D','L','R','O','W',' ','O','L','L','E','H',0]]`
`['L','L','D','L',['D','L','R','O','W',' ','O','L','L','E','H',0]]`

`(``)/` reduce that list by the following tacit function:

`⍳⍨` the **ɩ**ndex of the first occurrence in the phrase (will return 1 + phrase length if unfound)

`↓⊢` drop that many characters from the phrase

We then use the shortened phrase to look for the next letter. If at any point a letter is unfound, we'll drop everything, including the final zero. This means that if our acronym is good, we'll still have a zero left.
`[0]`
`[]`

disclose (because the reduction reduced the number of dimensions from 1 to 0)

`0∊` is zero a member thereof?
> 3 votes

# Answer
# , 21 bytes

```
<@[e.]<@#~2#:@i.@^#@]

```

Try it online!

Note: Some of the longer test cases omitted because they this solution is O(2^n). They would pass with infinite memory.

Explanation: We create all 2 ^ (length of haystack) possible substrings, and check if the needle is an element of that list.
> 3 votes

# Answer
# Gaia, 5 bytes

```
$z@$Ė

```

Try it online!

Powerset approach.
> 2 votes

# Answer
# JavaScript, 26 bytes

Port of Kevin's Java solution so please `+1` him, too.

Takes the string as a string via parameter `s` and the acronym as a character array via parameter `a`. Outputs `false` for `true` and `true` for `false`.

```
s=>a=>!s.match(a.join`.*`)

```

Try it online! (Footer reverses output for easier verification)
> 2 votes

# Answer
# Python 3, ~~89~~ 68 bytes

-21 bytes thanks to AdmBorkBork

```
def a(b,c):
    for i in b:
        if i==c[:1]:
            c=c[1:]
    return len(c)==0

```

Takes input as a(string, acronym). Try it online!
> 2 votes

# Answer
# Japt, 4 bytes

```
à øV

```

Try it here
> 1 votes

# Answer
# Python 3, 63 bytes

```
f=lambda s,t:(t[:1]in{*s}and f(s[s.find(t[0]):],t[1:]))**len(t)

```

Try it online!

Recursive function. Will check for each letter in the acronym `t`, whether it is found in the string `s`. If it is, the function is called recursively with the part of the string *after* the current test character `t[0]` as the new input string `s`.

When the test character is *not* found, the final evaluation result (which at that point is always `0`) is raised to the power of the length of the remaining test string `t`. Since `0**0 == 1` and `0**x == 0` for any `x > 0`, the function returns `1` when all test characters have been found in order and `0` otherwise.
> 1 votes

# Answer
# C#, 152 bytes

```
public class P{public static void Main(string[]a){int q=0;int e=a[1].Length;foreach(char c in a[0])if(q!=e&&c==a[1][q])q++;System.Console.Write(q==e);}}

```

Try Online
> 1 votes

# Answer
# Stax, 4 bytes

```
äΦv>

```

Run and debug it
> 1 votes

# Answer
# Jelly, 4 bytes

```
eŒP}

```

Try it online!
> 1 votes

# Answer
# Zsh, 35 bytes

```
[[ $1 = *${~${(j:*:)${(s::)2}}}* ]]

```

Outputs via exit code. Try it online!

```
[[ $1 = *${~${(j:*:)${(s::)2}}}* ]]
                    ${     2}        # second parameter
                    ${(s::) }        # split into characters
            ${(j:*:)         }       # join with *
         ${~                  }      # enable globbing
        *${~${(j:*:)${(s::)2}}}*     # *A*C*R*O*N*Y*M*
[[ $1 =                           ]] # does it match the first parameter?

```
> 1 votes

# Answer
# JavaScript, 50 bytes

```
h=>n=>[...n].reduce((a,l)=>a+1?h.indexOf(l,a):a,0)

```

Try it online!

take input as `f(haystack)(needle)`

```
h=>n=>                                             // inputs
      [...n]                                       // transform n from string to array of char
            .reduce((a,l)=>                    ,0) // for each letter change the value of a, (a starting at 0)
                           a+1?h.indexOf(l,a):a    // if a === -1 keep it else replace it by the position of the letter l in the haystack h starting from position of previous letter

```
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 88 bytes

```
	T =INPUT
S	T LEN(1) . X REM . T	:F(M)
	M =M ARB X	:(S)
M	INPUT M	:F(END)
	OUTPUT =1
END

```

Try it online!

Prints 1 for Acronymizable, and does nothing for not.

```
	T =INPUT			;* read in the Target
S	T LEN(1) . X REM . T	:F(M)	;* extract the first letter of T
					;* and when T is empty, goto M
	M =M ARB X	:(S)		;* create a PATTERN: M, ARBitrary match, X
					;* then goto S
M	INPUT M	:F(END)			;* if M doesn't match the input, end
	OUTPUT =1			;* else print 1
END

```
> 1 votes

# Answer
# Emacs Lisp, 52 bytes

```
(lambda(a b)(string-match(mapconcat'string b".*")a))

```
> 1 votes

# Answer
# Pyth, 3 bytes

```
}Ey

```

Try it online!
> 1 votes

# Answer
# Haskell, 40 bytes

```
r@(a:c)#(b:d)|a==b=c#d|1>0=r#d
x#y=x==""

```

Try it online!
> 1 votes

# Answer
# Retina 0.8.2, ~~20~~ 19 bytes

```
+`(.)(.*¶)\1?
$2
¶$

```

Try it online! Takes the phrase and acronym on separate lines, but the link includes a header that formats the test suite appropriately. Explanation:

```
+`

```

Process all of the letters of the phrase.

```
(.)(.*¶)\1?
$2

```

For each letter of the phrase delete the next letter of the acronym if it is the same.

```
¶$

```

Check that all of the letters of the acronym were deleted.
> 1 votes

# Answer
# Python 3, 85 bytes

```
def f(s,w):
	for c in s:
		if c==w[0]:
			w.pop(0)
			if len(w)==0:return 1
	return 0

```

Try it online!
> 1 votes

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


title: Black and white shirts

text:
# Question
Title: Black and white shirts
This puzzle is based on this Math.SE post. A more complex version of this problem can be found over here.

Assume I have some number of black shirts and some number of white shirts, both at least 1. Both colors of shirt have a non-zero durability. All shirts of a given color start with the same durability.

Every day, I pick out a clean shirt to wear, and it becomes dirty. Once I run out of all clean black shirts or all clean white shirts, I wash all my dirty shirts of both colors and start over. Clean shirts do not get washed. Whenever a shirt gets washed, its durability goes down by one. Immediately after washing, if the durability of a shirt reaches 0, it must be thrown out.

When picking which shirt to wear of a particular color, I always choose a shirt with the highest durability of that color to ensure even wear and tear among shirts.

# Challenge:

Take in a sequence of two characters of infinite length (eg. b b b w b w w b...) representing my choice of shirt to wear on that day. Continue execution until either my last black shirt or my last white shirt is thrown out. Once this occurs, stop consuming input and halt execution immediately. Note that the program must not consume any more input than is required before halting.

## Inputs:

Number of black shirts, number of white shirts, durability of black shirts, durability of white shirts, and an infinite number of two single characters, your choice (eg. b and w)

Note: if your language of choice does not *support* reading input of an infinite length (i.e. from a stream), assume an input of arbitrary length that is at least long enough for one color of shirt to run out.

## Output:

None. The program must simply immediately halt when the last shirt of either color is thrown away.

Note: if your language does not support reading input of infinite length, then instead you should output the number of characters processed.

## Test cases:

The following test cases represent the amount of input the program should process before halting. The sequence of w’s and b’s is infinite. The parenthetical afterwards is not part of the input or output, but simply represents the end state of how many shirts of each color have not been thrown out.

```
1 1 1 1 b
(0 b, 1 w left)

1 999 1 999 b
(0 b, 999 w left)

1 999 1 999 w w w w w w w w b
(0 b, 999 w left)

2 999 1 999 b w w w b
(0 b, 999 w left)

2 999 2 999 b w w w b w b w w w b
(0 b, 999 w left)

5 6 3 1 w w w w w b b b b b b b b b b b b b b w
(5 b, 0 w left)

```

# General rules:

* This is , so shortest answer in bytes wins.
* Default input rules apply for the first four arguments. For the arbitrarily long input sequence after the first four arguments, input must come from a source which can provide input one character or byte at a time, of theoretically infinite length, such as STDIN or some other stream. If your language of choice does not support these features, see above.

# Answer
# 05AB1E, 14 bytes

```
*Š*‚[ICÓ-W_iõq

```

Try it online!

Uses `p` instead of `b`, because pink is prettier than black.

Explanation:

```
*             # number of white shirts * durability of white shirts
 Š            # swap
  *           # number of pink shirts * durability of pink shirts
   ‚          # pair the two products in a list
[             # infinite loop
 I            # get the next input
  =           # print (only in the TIO version, not actually needed)
   C          # convert from binary (this yields 51 for p and 58 for w, don't ask why)
    Ó         # list of exponents in the prime factorization
     -        # subtract from the durability list
      W_i     # if the minimum of the list is now 0
         õq   # exit without printing anything

```
> 4 votes

# Answer
## C(tcc), ~~117~~ ~~116~~ 90 bytes

Uses 0x01 instead of b, and 0x02 instead of w.

```
main(a,b,c,d){scanf("%d%d%d%d",&a,&b,&c,&d);a*=c;for(b*=d;a*b;~c?b-=!c:a--)c=getchar()-2;}

```

Try it online!
> 1 votes

# Answer
# 05AB1E, ~~28~~ 22 bytes

```
*U*V[XY*_iõq}©XαUY®≠-V

```

Inputs are separated by newlines in the order `amountOfWhiteShirts, whiteDurability, amountOfBlackShirts, blackDurability, shirtDigits...`, where white shirts are `1` and black shirts are `0`.

-3 bytes thanks to *@Grimy* by bringing to my attention that an input of `1`/`0` instead of `"w"`/`"b"` is allowed for the shirts.

Try it online or try it online with additional `=` to print shirts without popping to verify it works as intended.

**Explanation:**

```
*          # Multiply the first two (implicit) input-integers
 U         # Pop and store it in variable `X`
*          # Multiply the next two (implicit) input-integers
 V         # Pop and store it in variable `Y`
[          # Start an infinite loop:
 XY*_i  }  #  If either `X` or `Y` is 0:
      õ    #   Push an empty string, since we don't want any (implicit) output
       q   #   And stop the program
 ©         #  Store the next (implicit) input in variable `®` (without popping)
  Xα       #  Get it's absolute difference with `X` (basically `X-input`)
    U      #  Pop and store it as new value for `X`
  ®≠       #  Push `®` falsified (1→0; 0→1)
 Y  -      #  Then subtract it from `Y`: `Y-falsified(®)`
     V     #  And also pop and store it as new value for `Y`

```
> 1 votes

# Answer
# Charcoal, 22 bytes

```
Ｆ²⊞υ×ＮＮＷ∧⌊υＳ§≔υ℅ι⊖§υ℅ι

```

Try it online! Link is to verbose version of code. Requires both black shirt values, then both white shirt values, then a stream of `b` and `w` characters on separate lines, otherwise behaviour is undefined. On TIO if you don't provide enough shirts you can see Charcoal attempt to prompt for input; if you ran locally then you would be able to continue enter `b` and `w` characters until you ran out of shirts at which point the program would exit. Explanation:

```
Ｆ²⊞υ×ＮＮ

```

Calculate the lifetimes of each colour of shirt.

```
Ｗ∧⌊υＳ

```

Repeat until one colour is exhausted.

```
§≔υ℅ι⊖§υ℅ι

```

Reduce the lifetime of a shirt according to the worn colour.
> 1 votes

# Answer
# C# .NET, 260 bytes

```
class P{static void Main(string[]a){int b=int.Parse(a[0]);int g=int.Parse(a[1]);int q=g;int r=int.Parse(a[2]);int t=int.Parse(a[3]);int w=t;while(true){if(System.Console.ReadKey().KeyChar<104)q--;else w--;if(q<1){q=g;b--;}if(w<1){w=t;r--;}if(r<1|b<1)return;}}}

```

No TIO :(
Not the shortest but does the job great!
**EDIT: NOTE:** uses no spaces in input and (g)reen and (r)ed instead of (b)lack and (w)hite
> 1 votes

# Answer
# Perl 5, 205 bytes

```
sub f{@s=map[$_>$_[0]?'w':'b',$_>$_[0]?$_[3]:$_[2],1],1..$_[0]+$_[1];while(join('',map$$_[0],@s)=~/bw|wb/){$c=&{$_[4]};(@w=grep$$_[2]&&$$_[0]eq$c,@s)[0][2]=0;@s=grep$$_[2]||++$$_[2]&&--$$_[1],@s if@w<2}@s}

```

Try it online!

I assumed that picking the least worn out shirt each day doesn't actually influence the result. Any clean shirt of the chosen color will do. I also think that 2 shirts of durability 5 is the same as 1 shirt of durability 10, so we can simplify this to have just two shirts, one black and one white, but that affects the printed `(x b, y w left)` result so I didn't go that direction.

Ungolfed:

```
sub f0 {                                                     #as f() but ungolfed
  my($countb,$countw,$durb,$durw,$get_todays_color)=@_;      #inputs
  my @s=( (map{{col=>'b',dur=>$durb,clean=>1}}1..$countb),   #init @shirts
          (map{{col=>'w',dur=>$durw,clean=>1}}1..$countw) );
  while(join("",sort(map$$_{col},@s))=~/bw/){                #while still both colors available
    my $col = &$get_todays_color;                            #todays color
    my @w = grep $$_{clean} && $$_{col} eq $col, @s;         #wearable shirts
    my $s = (sort{$$b{dur}<=>$$a{dur}}@w)[0];                #pick shirt with most durability left for today
    $$s{clean}=0;                                            #dirty in the evening
    map{$$_{clean}=1;$$_{dur}--}grep!$$_{clean},@s if @w==1; #wash if there was only one this morning
    @s=grep$$_{dur}>0,@s;                                    #toss out worn outs
  }
  @s                                                         #return not worn out
}

```
> 0 votes

# Answer
# Python 2, 54 bytes

```
b,w,B,W=input()
l=[B*b,W*w]
while all(l):l[input()]-=1

```

Try it online!
> 0 votes

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


title: The Lucky House

text:
# Question
Title: The Lucky House
There's a minigame in Super Mario 3D World known as the *Lucky House*. It consists of a slot machine with 4 blocks.

Each block may be one of 5 different icons (Flower, Leaf, Bell, Cherry or Boomerang) and the goal of the player is to get as many identical icons as possible (see a video).

The player is rewarded with coins, which in turn may be converted into extra lives. **Your task is to compute the number of extra lives won.**

Depending on the number of icons that match, the amount of coins rewarded are as follows:

* No matches - 10 coins
* One pair - 100 coins
* Two pairs - 200 coins
* Three-of-a-kind - 300 coins
* Four-of-a-kind - 777 coins

**You win one extra life (1UP) every 100 coins**. Therefore, you're guaranteed to win exactly 1UP with *one pair*, 2UP with *two pairs* and 3UP with *3-of-a-kind*. However, the number of lives won with *no matches* or *4-of-a-kind* depends on your initial coin stock.

*Source: Super Mario Wiki*

## Input

You're given the initial coin stock \\$0 \le c \< 100\\$ and a list of four values \\$\[v\_1,v\_2,v\_3,v\_4\]\\$ representing the final icons on the slot machine.

## Output

The number of extra lives won: \\$0\\$, \\$1\\$, \\$2\\$, \\$3\\$, \\$7\\$ or \\$8\\$.

## Rules

* You may take the icons in any reasonable format: e.g. as a list, as a string or as 4 distinct parameters.
* Each icon may be represented by either a **single-digit integer** or a **single character**. Please specify the set of icons used in your answer. (But you don't have to explain how they're mapped to Flower, Leaf, Bell, etc., because it doesn't matter at all.)
* You are not allowed to remap the output values.
* This is .

## Test cases

In the following examples, we use a list of integers in \\$\[1..5\]\\$ to represent the icons.

```
coins  icons      output   explanation
-------------------------------------------------------------------------
  0    [1,4,2,5]    0      no matches  ->  0 +  10 =  10 coins -> nothing
 95    [3,1,2,4]    1      no matches  -> 95 +  10 = 105 coins -> 1UP
 25    [2,3,4,3]    1      one pair    -> 25 + 100 = 125 coins -> 1UP
 25    [4,5,5,4]    2      two pairs   -> 25 + 200 = 225 coins -> 2UP
  0    [2,5,2,2]    3      3-of-a-kind ->  0 + 300 = 300 coins -> 3UP
 22    [1,1,1,1]    7      4-of-a-kind -> 22 + 777 = 799 coins -> 7UP
 23    [3,3,3,3]    8      4-of-a-kind -> 23 + 777 = 800 coins -> 8UP
 99    [3,3,3,3]    8      4-of-a-kind -> 99 + 777 = 876 coins -> 8UP

```

# Answer
# x86-16 Assembly, ~~56~~ ~~41~~ 39 bytes

**Binary:**

```
00000000: b103 33ed ac8b fe51 f2ae 7503 45eb f983  ..3....Q..u.E...
00000010: fd03 7504 80c2 4d43 03dd 59e2 e592 7502  ..u...MC..Y...u.
00000020: 040a 3c64 7201 43                        ..<dr.C

```

**Unassembled:**

```
B1 03           MOV  CL, 3              ; set up loop counter for 3 digits
            DIGIT_LOOP:
33 ED           XOR  BP, BP             ; clear digit matches counter in BP
AC              LODSB                   ; load next digit char into AL
8B FE           MOV  DI, SI             ; start searching at next char
51              PUSH CX                 ; save outer digit loop counter
            MATCH_LOOP:
F2/ AE          REPNZ SCASB             ; search until digit in AL is found
75 03           JNZ  CHECK_FOUR         ; is end of search?
45              INC  BP                 ; if not, a match was found, increment count
EB F9           JMP  MATCH_LOOP         ; continue looping
            CHECK_FOUR:
83 FD 03        CMP  BP, 3              ; is four of a kind?
75 04           JNE  SCORE_DIGIT        ; if not, add number of matches to 1UP's
80 C2 4D        ADD  DL, 77             ; add 77 to coin count
43              INC  BX                 ; +1 1UP extra for four-of-a-kind
            SCORE_DIGIT:
03 DD           ADD  BX, BP             ; Add number of matches to total, set ZF if 0
59              POP  CX                 ; restore outer digit loop position
E2 E5           LOOP DIGIT_LOOP         ; keep looping
92              XCHG DX, AX             ; coin count to AX for shorter compare
75 02           JNZ  FINAL_SCORE        ; if 1UPs > 0, no consolation prize
04 0A           ADD  AL, 10             ; award 10 coins
            FINAL_SCORE:
3C 64           CMP  AL, 100            ; is coin score over 100?
72 01           JB   DONE               ; if not, no extra 1UP
43              INC  BX                 ; otherwise, increment 1UP
            DONE:

```

Input starting coin count in `DX`, `SI` pointing to start of "icon" bytes (which can be `'1'`-`'5'`, or any byte value). Output the number of 1UP's in `BX`.

**Explanation:**

The input of four bytes is iterated and compared to the remaining bytes to the right, counting the number of matches. The scores for each type of match are awarded and add up to the total. Since a four-of-a-kind is also three-of-a-kind and also a one-pair, the value of each score type can be decomposed as follows:

* 3 matches = 4 1UP's + 77 coins
* 2 matches = 2 1UP's
* 1 match = 1 1UP

***Examples:***

`[2, 2, 2, 2]` (four-of-a-kind) = 7 1UP's + 77 coins

```
2 [2, 2, 2] = 3 matches = 4 1UP's + 77 coins
   2 [2, 2] = 2 matches = 2 1UP's
      2 [2] = 1 match   = 1 1UP

```

`[2, 5, 2, 2]` (three-of-a-kind) = 3 1UP's

```
2 [5, 2, 2] = 2 matches = 2 1UP's
   5 [2, 2] = 0 matches
      2 [2] = 1 match   = 1 1UP

```

`[4, 5, 5, 4]` (two pair) = 2 1UP's

```
4 [5, 5, 4] = 1 match   = 1 1UP
   5 [5, 4] = 1 match   = 1 1UP
      5 [4] = 0 matches

```

`[2, 3, 4, 3]` (one pair) = 1 1UP

```
2 [3, 4, 3] = 0 matches
   3 [4, 3] = 1 match   = 1 1UP
      4 [3] = 0 matches

```

If number of earned 1UP's is 0 at the end, 10 coins are awarded. If total coins are greater than 100, an additional 1UP is awarded.

Here is a test program for PC DOS that includes extra routines to handle the integer value I/O:

Download and test LUCKY.COM for DOS.
> 9 votes

# Answer
# Jelly,  ~~23 22 20~~  19 bytes

-1 thanks to Erik the Outgolfer (use `³` in place of `ȷ2`) also used in newer version twice
-1 thanks to Grimy (subtract one before summing instead of subtracting four afterwards)

Maybe beatable?

```
ċⱮ`’SṚḌH×³«777»⁵+:³

```

A dyadic Link accepting a list and an integer which yields an integer.

**Try it online!** Or see a test-suite.

### How?

```
ċⱮ`’SṚḌH×³«777»⁵+:³ - Link: list a, integer n   e.g. [x,x,x,x], 22
 Ɱ`                 - map across a with:
ċ                   -   count occurrences in a       [4,4,4,4]
   ’                - decrement                      [3,3,3,3]
    S               - sum (call this s)              12
     Ṛ              - reverse (implicit toDigits)    [2,1]
      Ḍ             - un-decimal                     21
       H            - halve                          10.5
         ³          - 100                           100
        ×           - multiply                     1050
           777      - 777                           777
          «         - minimum                       777
               ⁵    - 10                             10
              »     - maximum                       777  (handles 0 -> 10)
                +   - add (n)                       799
                  ³ - 100                           100
                 :  - integer division                7

```

How the hand evaluation works for each type of hand:

```
           Hand:    no-pair     pair        2-pair      trips       4-of-a-kind
(sorted) counts:    [1,1,1,1]   [1,1,2,2]   [2,2,2,2]   [1,3,3,3]   [4,4,4,4]
      decrement:    [0,0,0,0]   [0,0,1,1]   [1,1,1,1]   [0,2,2,2]   [3,3,3,3]
            sum:    0           2           4           6           12
       reversed:    [0]         [2]         [4]         [6]         [2,1]
     un-decimal:    0           2           4           6           21
         halved:    0           1           2           3           10.5
      times 100:    0           100         200         300         1050
    min(x, 777):    0           100         200         300         777
     max(x, 10):    10          100         200         300         777

```

---

Alternative 20: `ĠẈị“¡ıKĖ‘S×4+E{»⁵+:³`
> 5 votes

# Answer
# Zsh, ~~117 ...~~ 60 bytes

***-13** by using a different criterion for differentiation, **-9** by combining cases, **-28** by changing the `case` statement to a nested arithmetic ternary, **-4** thanks to @JonathanAllan, **-1** by optimizing the ternaries, **-2** because I accidentally used `echo` when adding Jonathan's optimization.*

Takes coin count on stdin, and block inputs as arguments. Arguments can be numbers, characters, or even strings: `./foo.zsh flower leaf flower boomerang`

```
read c
for i;for j;((a+=i<j))
<<<$[!a?7+(c>22):a-6?6-a:c>89]

```

Try it online: ~~117 104 95 67 63 62~~  **60**

Here's the magic from the 67 byte answer:

```
read coins
for block                  # for each element
  (( a+=${#${@:#$block}} ))
#          ${@:#$block}      remove all elements which don't match
#       ${#            }     count the remaining elements
# (( a+=                 ))  add that number to the total
<<<$[a?(a-12?6-a/2:coins>89):7+(coins>22)]
#    a?                     :7+(coins>22)  4*0 (all elements match all elements)
#      (a-12?     :coins>89)               4*3 (all elements match exactly one)
#      (a-12?6-a/2         )               3*1 + 1*3 ->  6, 6 -  6/2 -> 3
#                                          2*2 + 2*2 ->  8, 6 -  8/2 -> 2
#                                          2*3 + 2*2 -> 10, 6 - 10/2 -> 1

```
> 4 votes

# Answer
# Python 2, 96 91 89 bytes

*-2 bytes thanks to @Kevin Cruijssen*

```
lambda x,a,b,c,d:(x+(100*sum((a==b,a==c,a==d,b==c,b==d,c==d))or 10)+177*(a==b==c==d))/100

```

Try it online!
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~123~~ ~~106~~ 90 bytes

```
a=>b=>(a+("Ĭ̉Èd\n"[(b=b.GroupBy(x=>x,(o,p)=>p.Count())).Count()*(b.Max()==3?0:1)]))/100

```

A port of my python answer, which is derived from @Dat's answer.

Try it online!
> 3 votes

# Answer
# Python 3, 68 bytes

```
def f(c,a):x=sum(map(a.count,a))//2;return[c//90,x-2,7+(c>22)][x//3]

```

Try it online!

A Python port of my C port of my Bash port of my Zsh answer, re-golfed with help from the "Tips for golfing in Python" page. Last port, I swear... I'm running out of languages I'm comfortable golfing in. I was curious how this strategy compared to the other Python answers. Again, there's probably some way to beat this.

This one turned out surprisingly good, so I added a table below summarizing what's happening so others can port or improve this.

```
Type          Example  map(a.count,a)  sum(__)   x=__//2  x//3   array lookup
----------------------------------------------------------------------------
none         [1,2,3,4]    [1,1,1,1]        4       2       0      c//90
pair         [1,1,2,3]    [2,2,1,1]        6       3       1      x-2 -> 1
two pair     [1,3,1,3]    [2,2,2,2]        8       4       1      x-2 -> 2
3-of-a-kind  [1,3,1,1]    [3,1,3,3]       10       5       1      x-2 -> 3
4-of-a-kind  [3,3,3,3]    [4,4,4,4]       16       8       2      7+(c>22)

```

## Python 3.8 (pre-release), 63 bytes

Praise the `:=` walrus!

```
lambda c,a:[2+c//90,x:=sum(map(a.count,a))//2,9+(c>22)][x//3]-2

```

Try it online!
> 3 votes

# Answer
# Python 2, 63 bytes

```
lambda x,l:int([3,1,7.77,2,.1][sum(map(l.count,l))%14%5]+x/1e2)

```

Try it online!

I had the same idea as GammaFunction to use `sum(map(l.count,l))` as a "fingerprint". But, instead of using an arithmetic formula on the result, I use a lookup table, first squishing the value to 0 through 4 using a mod chain `%14%5`. Dividing all the point values by 100 saved a few bytes.
> 3 votes

# Answer
# Perl 6, ~~48~~ 44 bytes

```
{*/100+((0,0,1,3,7.77)[.Bag{*}].sum||.1)+|0}

```

Try it online!

Curried function `f(icons)(coins)`.
> 3 votes

# Answer
# PHP, ~~153~~ 127 bytes

*@640KB* made some really clever changes to shorten it further:

```
function($c,$s){for(;++$x<6;$n+=$m>3?777:($m>2?300:($m>1)*100))for($m=!$y=-1;++$y<5;$m+=$s[$y]==$x);return($c+($n?:10))/100|0;}

```

Try it online!
> 3 votes

# Answer
# Python 3, ~~126~~ ~~111~~ ~~108~~ 103 bytes

```
def f(c,a):x=sorted([a.count(i)for i in set(a)]);return([300,777,200,100,10][len(x)*(x[-1]!=3)]+c)//100

```

Try it online!
> 2 votes

# Answer
# Perl 5 `-pF`, 46 bytes

```
map$q+=$$_++,@F;$_=0|<>/100+($q>5?7.77:$q||.1)

```

Try it online!

First of input is the spin result, using any 5 unique ASCII letters, except `q` (I suggest `abcde`). The second line of input is the current coin count.

## How?

```
-F     # CLI option splits the input into individual characters in @F
map
   $q+=   # $q holds the result of the calculation here
          # possible values are 0,1,2,3,6
   $$_    # This interprets $_ as a variable reference, thus if $_ is 'a', this variable is $a
   ++     # increment after adding it to $q
,@F;      # iterate over the elements of @F
$_=0|     # force the result to be an integer
   <>/100 # divide the current coin count by 100
   +($q>5?7.77  # if $q is over 5, then there must have been 4 of a kind
   :$q||.1)     # otherwise, use $q, unless it is 0, then use .1
-p        # CLI option implicitly outputs $_

```

All of the numbers involved are divided by 100, so the program is counting the number of lives (including partial ones) currently earned. The trick to this solution is in the `map`. If the possible entries are `abcde`, then each of `$a`, `$b`, `$c`, `$d`, and `$e` hold the count of the number of times this character had previously been seen. That gets added to a running total (`$q`) each time a character is seen. The running total is bumped up if there is a four of a kind (effectively a 177 coin bonus).
> 2 votes

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

```
lambda c,a:(ord("Ĭ̉Èd\n"[len(x:=[*map(a.count,{*a})])*(max(x)!=3)])+c)//100

```

Dat's answer, but golfed more.

Try it online!
> 2 votes

# Answer
# PHP, ~~89~~ 84 bytes

```
foreach(count_chars($argv[2])as$a)$b+=[2=>1,3,7.77][$a];echo$argv[1]/100+($b?:.1)|0;

```

Try it online!

Input from command line, output to `STDOUT`:

```
$ php lucky.php 99 3333
8

$ php lucky.php 0 2522
3

$ php lucky.php 0 abaa
3

```
> 2 votes

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

```
c=>a=>[,7.77,a.sort()[1]-a[2]?2:3,1,.1][new Set(a).size]+c*.01|0

```

Try it online!

I figured there had to be at least one JavaScript answer to an Arnauld challenge!

The concept here is mainly to use the number of distinct elements as a lookup key.

* 1 unique =\> 4 of a kind
* 2 unique =\> 2 pair or 3 of a kind
* 3 unique =\> 1 pair
* 4 unique =\> no matches

In order to distinguish between 2 pair and 3 of a kind, the input array is sorted and the middle 2 elements are compared.
> 2 votes

# Answer
# Bash, ~~76 75 71~~ 70 bytes

***-4** thanks to @JonathanAllan, **-1** by rearranging the ternary.*

```
read c
for i;{ for j;{ ((a+=i<j));};}
echo $[!a?7+(c>22):a-6?6-a:c>89]

```

Bash port of my Zsh answer. ~~Try it online! Try it online! Try it online!~~ Try it online!
> 1 votes

# Answer
# Stax, 23 bytes

```
¿^∩û:¶á☺ⁿ£z⌐└≤♂EM¥t(,5╓

```

Run and debug it

This program uses any arbitrary set of 5 integers for icons.

### Procedure:

1. Add up the number of occurrences of each element.
2. Divide by 2 and then mod 7.
3. The result is a number from 1..5. Use this to look up the coin prize in a fixed array.
4. Add to the initial coin count.
5. Divide by 100.

Here's the output from an experimental stack state visualizer I've been working on for the next release of stax. This is an unpacked version of the same code with the stack state added to comments.

```
c               input:[2, 3, 4, 3] 25 main:[2, 3, 4, 3]
{[#m            input:[2, 3, 4, 3] 25 main:[1, 2, 1, 2]
|+              input:[2, 3, 4, 3] 25 main:6
h7%             input:[2, 3, 4, 3] 25 main:3
":QctI*12A"!    input:[2, 3, 4, 3] 25 main:[300, 777, 10, 100, 200] 3
@               input:[2, 3, 4, 3] 25 main:100
a+              main:125 [2, 3, 4, 3]
AJ/             main:1 [2, 3, 4, 3]

```

Run this one
> 1 votes

# Answer
# C (gcc), ~~92 84 82 81 79~~ 78 bytes

***-1** by `x+=(..!=..)` **-5** by returning via assignment, **-4** thanks to Jonathan Allan by replacing `!=` with `<`, which saves bytes elsewhere, **-1** by rearranging the ternary.*

*From @ceilingcat: **-2** by declaring `i` and `x` outside the function, **-1** by setting `x=i` and decrementing `x` instead.*

```
i,x;f(c,a)int*a;{for(i=x=16;i--;)x-=a[i/4]>=a[i%4];c=x?x-6?6-x:c>89:7+(c>22);}

```

Another port of my Zsh answer. I'm unfamiliar with C golfing, there's probably another trick somewhere in here to reduce it further. ~~92 84 82 81 79~~ Try it online!
> 1 votes

# Answer
# APL+WIN, 42 bytes

Prompts for icons followed by coin stock.

```
  ⌊(.01×⎕)+.1⌈+/1 3 7.77×+⌿(+⌿⎕∘.=⍳5)∘.=1↓⍳4

```

Try it online! Courtesy of Dyalog Classic
> 1 votes

# Answer
# Retina 0.8.2, 72 bytes

```
O`\D
(\D)\1{3}
777¶
(\D)\1\1
300¶
(\D)\1
100¶
\D{4}
10¶
\d+\D*
$*
1{100}

```

Try it online! Link includes test cases. Takes input as 4 printable ASCII non-digits followed by the initial number of coins in digits. Explanation:

```
O`\D

```

Sort the non-digits so that identical symbols are grouped together.

```
(\D)\1{3}
777¶

```

Four-of-a-kind scores 777.

```
(\D)\1\1
300¶

```

Three-of-a-kind scores 300.

```
(\D)\1
100¶

```

Each pair scores 100, so two pairs will score 200.

```
\D{4}
10¶

```

If there were no matches then you still win!

```
\d+\D*
$*

```

Convert the values to unary and take the sum.

```
1{100}

```

Integer divide the sum by 100 and convert back to decimal.
> 1 votes

# Answer
# Retina, 56 bytes

```
(\D)\1{3}
777¶
w`(\D).*\1
100¶
\D{4}
10¶
\d+\D*
*
_{100}

```

Try it online! Link includes test cases. Takes input as 4 printable ASCII non-digits followed by the initial number of coins in digits. Explanation:

```
(\D)\1{3}
777¶

```

Four-of-a-kind scores 777.

```
w`(\D).*\1
100¶

```

Each pair scores 100. The `w` takes all pairs into consideration, so that they can be interleaved, plus three-of-a-kind can be decomposed into three pairs, thus automagically scoring 300.

```
\D{4}
10¶

```

If there were no matches then you still win!

```
\d+\D*
*

```

Convert the values to unary and take the sum.

```
_{100}

```

Integer divide the sum by 100 and convert back to decimal.
> 1 votes

# Answer
# 05AB1E, ~~20~~ ~~19~~ 18 bytes

```
D¢<OR;т*777T)Åm+т÷

```

Port of *@JonathanAllan*'s Jelly answer, so make sure to upvote him!!
-2 bytes thanks to *@Grimy*.

Takes the list of icons as first input (being `[1,2,3,4,5]`), and the amount of coins as second input.

Try it online or verify all test cases. (The test suite uses `T‚à+` instead of `TMI+`, which is an equal bytes alternative.)

**Explanation:**

```
D                   # Duplicate the first (implicit) input-list
 ¢                  # Count the amount of occurrences in itself
  <                 # Decrease each count by 1
   O                # Sum these
    R               # Reverse it
     ;              # Halve it
      т*            # Multiply by 100
        777         # Push 777
           T        # Push 10
            )       # Wrap all three values into a list
             Åm     # Get the median of these three values
               +    # Add the second (implicit) input to it
                т÷  # And integer-divide it by 100
                    # (after which the result is output implicitly)

```
> 1 votes

# Answer
# Scala, 88 bytes

```
(c,v)=>(Seq(777,300,200,100,0,10)((v.groupBy(x=>x).map(_._2.size+1).product-5)/2)+c)/100

```

Try it online!
> 1 votes

# Answer
# PowerShell, ~~114~~ 107 bytes

-7 bytes thanks to mazzy

```
param($n,$l)((((0,.1,1)[+($x=($l|group|% c*t|sort))[2]],2,3)[$x[1]-1],7.77)[$x[0]-eq4]+".$n")-replace'\..*'

```

Try it online!

A big ol' PowerShell-flavored ternary operation built upon grouping and sorting the counts of the input list. The sort is needed because we leverage the fact that the grouped list gets shorter the more repeats there are. In fact, here's all the possible values:

```
(1,1,1,1)
(1,1,2)
(2,2)
(1,3)
(4)

```

Truncating to an int is still expensive.

Unrolled:

```
param($n,$l)
$x=$l|group|% c*t|sort
(((                      #Start building a list...
   (0,.1,1)[+$x[2]],     #where spot 0 holds dummy data or handles no match and 1 pair
    2,3)[$x[1]-1],       #Overwrite the dummy data with 2-pair or 3-o-k
   7.77)[$x[0]-eq4]      #OR ignore all that and use spot 1 because it's a 4-o-k
   +".$n"                #Use that value and add CoinCnt via int-to-string-to-decimal
)-replace'\..*'          #Snip off the decimal part

```
> 1 votes

# Answer
# Charcoal, 30 bytes

```
≔⊘ΣＥη№ηιηＩ⌊⁺∕θ¹⁰⁰∨⁻η∕²∨›⁸η⁹∕¹χ

```

Try it online! Link is to verbose version of code. Takes input as the number of coins and an array of any Python comparable values as icons. Explanation:

```
≔⊘ΣＥη№ηιη

```

Shamelessly steal @GammaFunction's trick of computing half the sum of counts.

```
⁻η∕²∨›⁸η⁹

```

Subtract `2` from the sum, thus resulting in the values `0, 1, 2, 3` appropriately, but for 4-of-a-kind, divide the `2` by `9` first, resulting in `7.777...`.

```
∨...∕¹χ

```

But if the result is 0, then there were no matches, so replace it with `0.1` instead. (Using a literal doesn't help me here because I would need a separator.)

```
Ｉ⌊⁺∕θ¹⁰⁰...

```

Divide the initial coins by 100 and add on the winnings, then floor the result and cast to string for implicit output.
> 1 votes

# Answer
# R, ~~102~~, ~~91~~, 81 bytes

```
f=function(b,v,s=table(v))(477*any(s>3)+b+10*all(s<2))%/%100+sum(s==2)+3*any(s>2)

```

Managed to drop 11 bytes (and fix a bug) thanks to @Giuseppe. Managed a further 10 inspired by by @Giuseppe's /10 idea.

Ungolfed

```
f=function(b,v){
  s = table(v)          #included in fn inputs
  a = b+10*all(s<2)     #covers all different case
  a = a+477*any(s>3)    #Covers 4 of a kind
  d = sum(s==2)+3*any(s>2) #covers 1 and 2 pair, 3 of a kind.
  a%/%100+d         #sum appropriate values
}

```

Try it online!
> 1 votes

# Answer
# Wolfram Language (Mathematica), 54 bytes

```
⌊{,.1,1,2,3,,,7.77}[[Total[Counts@#2^2]/2]]+.01#⌋&

```

Try it online!
> 1 votes

# Answer
# Pyth, 32 bytes

```
AQ-@[+K2/G90J/sm/HdH2+9>G22)/J3K

```

Try it online!

Inspired by GammaFunction's solution. Takes input as `[coins, [icons]]`.

```
AQ                               # Q is the input. Set G := Q[0], H := Q[1]
    [                      )     # Construct a list from the following entries:
     +K2/G90                     # [0] (K:=2) + G/90 (/ is integer division)
            J                    # [1] J:=
              s                  #        reduce on + (
               m   H             #          map entries of H as d on (
                /Hd              #            number of occurences of d in H ) )
             /      2            #                                               / 2
                     +9>G22      # [2] 9 + (G > 22)
   @                        /J3  # Take element at position J/3
  -                            K # Subtract K (=2)

```
> 1 votes

# Answer
# PowerShell, 94 bytes

```
param($n,$l)$r=@{2=100;3=300;4=777}[($l|group|% c*t)]|?{$_;$n+=$_}
+(($n+10*!$r)-replace'..$')

```

Try it online!

Unrolled:

```
param($nowCoins,$values)
$groupCounts=$values|group|% count
$rewardedCoins=@{2=100;3=300;4=777}[$groupCounts]|?{
    $_                          # output matched only
    $nowCoins+=$_               # and accumulate
}
$nowCoins+=10*!$rewardedCoins   # add 10 coins if no rewarded conis
+($nowCoins-replace'..$')       # truncate last two digits

```
> 1 votes

# Answer
# 8051 Assembly (compiles to 158 bytes)

This is a VEEEEEEEEEERRY naive approch, this is yet untested and ungolfed but im pretty confident that works. Things to consider are:

1) the 8051 is an accumulator machine ie. it needs mov instructions that other architectures may not need at all.

2) the 8051 is an 8bit machine therefor there has to be done some trickery for the numbers \>255 which makes for more code and is therefor a disadvantage of the platform over the others.

```
CSEG AT 0000H

coinStackOnes equ 0xf3
coinStackTens equ 0xf4
coinStackHundreds equ 0xf5 ; leave one byte as guard so that if that gets corrupted it doesnt really matter

values1 equ 0xf7
values2 equ 0xf8
values3 equ 0xf9
values4 equ 0xfa

numOfFlowers equ 0xfb
numOfLeaf equ 0xfc
numOfBell equ 0xfd
numOfCherry equ 0xfe
numOfBoomerang equ 0xff

flower equ 1
leaf equ 2
bell equ 3
cherry equ 4
boomerang equ 5

numOfHeartsReceived equ 0xf1

mov r1, #4
mov r0, numOfFlowers
clearNumOfRegs: mov @r0, #0d
        inc r0
        djnz r1, clearNumOfRegs
;if you reach this all numOfXXXX registers are zeroed

mov r0, #values1
mov r1, #flower

mov a, #6 ; innercounter
mov b, #5 ; outercounter
checkfornextpossibleitem:   mov r2, a; backup countervar
                mov a, @r0 ; store given value in a
                xrl a, @r1 ; xor a with item
                jnz nextItem ; if value!=item -> nextitem
                mov a, #numOfFlowers ;if you end up here a=0 (ie value == item) --> generate addr for numOfReg <-- load a with addr for numOfFlowers
                add a, r1 ; since items are only numbers you can add the item to get the addr for numOfReg a=addr(numOfReg)
                xch a, r1 ; change the item with the addr as r1 is indirect register
                inc @r1 ; increment numOfRegister
                xch a, r1; r1 = item
                ;next item
                nextItem:   inc r1 ; increment item
                        mov a, r2 ; restore counter
                        dec a; decrement counter
                        cjne a, #0, checkfornextpossibleitem
                        ;if you reach this you have successfully tested one value against all items and therefor the next value must be tested
                        mov a, #6; reset the innercounter
                        dec b; decrement the outercounter
                        inc r0; increment the register that points to the value-under-test
                        xch a,b; cjne works with a but not with b therefor exchange them
                        cjne a, #0, here ; do the comparison; if you dont jump here you have tested all values
                        jmp howManyPairsDoIHave; if you didnt jump above you have the now the number of flowers and so on
                        here:   xch a,b ; and change back
                            jmp checkfornextpossibleitem ; check the next value
howManyPairsDoIHave:    mov r0,#0; store numOfPairsHere initialize with zeros
            mov r1, numOfFlowers;
            mov b, #6; use as counter to know when you went through all numOfRegisters
analyseNumOfRegister:   mov a, @r1 ; load the numOfregister for some math
            xrl a, #2; a will contain zero if numOfXXX = 2
            jnz numOfXXXWasNot2; if you do not jump here you have 2 XXX therefor
            inc r0; increment the number of pairs
            jmp nextNumOfRegister; continiue with the next one
            numOfXXXWasNot2:    mov a, @r1; restore the number of XXX and try the next magic value
                        xrl a, #3; will contain zero if you have a three of a kind
                        jnz no3XXX; if you dont jump here however you have a three of a kind
                        jz add300Coins
                        no3XXX:     mov a, @r1; restore number of XXX
                                xrl a, #4; a will contain zero if 4 of a kind
                                jnz nextNumOfRegister; if you numOfXXX!=4 you can only continiue trying to find something in the next numof register
                                jz add777Coins; if you didnt jump above how ever you will have to add the 777 coins as you detected a 4 of a kind
nextNumOfRegister:  inc r0; move pointer to the next numofregister
            djnz b, analyseNumOfRegister; if you havent already analysed all numofregisters then continue
            ; if you have however you end up here so you will have to take a look at the numOfPairs
            cjne r0, #1, tryIf2Pairs; test if you have 1 pair if not try if you have 2
            jmp add100Coins; if you have 1 pair however add the 100 coins
            tryIf2Pairs:    cjne r0, #2, youMustHave0Pairs; test if you have 2 pairs if not you can be sure to have 0 of them
                    jmp add200Coins; if you have 2 pairs however add them
youMustHave0Pairs:  ; add 10 coins
            inc coinStackTens
            mov a, coinStackTens
            cjne a, #10d, howManyHearts ; if your tens digit isnt outta range continue with the calculation of the number of hearts
            inc coinStackHundreds; if it is outta range do correct that
            mov coinStackTens, #0
            jmp howManyHearts;
add100Coins:    inc coinStackHundreds; here the digit can not possibly have an invalid value...
        jmp howManyHearts
add200Coins:    mov a, coinStackHundreds
        add a, #2
        mov coinStackHundreds, a
        jmp howManyHearts ; also here no invalid values possible
add300Coins:    mov a, coinStackHundreds
        add a, #3
        mov coinStackHundreds, a
        jmp howManyHearts ; same again
add777Coins:    mov r0, #coinStackOnes
        mov r2, #3
add7:       mov a, r0
        mov r1, a
        mov a, @r0
        add a, #7
        mov b, a; b contains the possibly invalid version of the ones digit
        da a; if you have an invalid value its lower nibble gets corrected this way
        anl a, 0x0f; and the higher one gets corrected this way
        xch a,b; a and b must be swapped in order to make subb work ie b contains now the corrected value and a has the maybe faulty value
        subb a,b; returns zero if all the corrections had no effect therefor the next digit can be increased by 7
        jz nextDigit
        inc r1
        inc @r1
        nextDigit:  inc r0
                djnz r2, add7;

howManyHearts:  mov numOfHeartsReceived, coinStackHundreds
loop_forever:   sjmp loop_forever
        END

```
> 0 votes

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