[R] Sorting based a custom sorting function

Martin Møller Skarbiniks Pedersen tr@xp|@yer @end|ng |rom gm@||@com
Thu Dec 14 12:31:57 CET 2023


> This sounds suspiciously like homework (which is off-topic... see the Posting Guide)

It is not homework.
Currently I am trying to solve this: https://adventofcode.com/2023/day/7

But it is something that has puzzled me for a long time.
In many programming languages, you can give a "less" function to the
sorting function.

The "less" function normally takes two arguments and tells which is
greater. The sorting function then uses that.
Eg. in perl:
@products = sort { $a->{price} <=> $b->{price} || $b->{discount} <=>
$a->{discount} } @products;

>  and you haven't indicated how you plan to encode your poker hands
> If this is not homework, then please show your work so far instead of showing a completely different example.

I believe a MRE is better than a lot of code with many details that
are not related to the precise problem.
See https://stackoverflow.com/help/minimal-reproducible-example

My encoding of poker hands doesn't matter for the general problem of
providing a custom sorting function to any of the many
sorting functions in R.

> Most core features of other languages are possible in R so if you really understand these other techniques and R then you should be able to do this already.

I understand R quite well and implemented my own quicksort but I was
wondering for a better solution.

Here is my current solution.

quicksort <- function(arr, compare_func) {
  if (length(arr) <= 1) {
    return(arr)
  } else {
    pivot <- arr[1]
    less <- arr[-1][compare_func(arr[-1], pivot) <= 0]
    greater <- arr[-1][compare_func(arr[-1], pivot) > 0]
    return(c(quicksort(less, compare_func), pivot, quicksort(greater,
compare_func)))
  }
}

Regards
Martin



Martin



More information about the R-help mailing list