/now
projects
ramblings
smol projects

is positive dominant

13.11.2023 1 min read

An array is positive dominant if it contains strictly more unique positive values than unique negative values. Write a function that returns true if an array is positive dominant.

The main thing here is that we need unique values.

(0 counts as neither negative nor positive)

In Crystal, we have the very aptly named uniq:

def is_positive_dominant(arr : Array(Int32)) : Bool
  num_pos = arr.uniq.count { |i| i > 0 }
  num_neg = arr.uniq.count { |i| i < 0 }
  return num_pos > num_neg
end

Nim has deduplicate:

func isPositiveDominant(s: seq[int]): bool =
    let numPos = s.deduplicate.filterIt(it > 0).len 
    let numNeg = s.deduplicate.filterIt(it < 0).len
    return numPos > numNeg

Raku has unique:

sub is-positive-dominant(@a) {
   @a.unique.grep({$_ > 0}).elems > @a.unique.grep({$_ < 0}).elems;
}

We can use Set in Javascript:

function isPositiveDominant(arr: number[]): boolean {
  const s = new Set(arr);
  const numPos = [...s].filter((i) => i > 0).length;
  const numNeg = [...s].filter((i) => i < 0).length;
  return numPos > numNeg;
}

All in all, rather sameish solutions.

Built with Astro and Tailwind 🚀