title: Finding the list permutation with minimum score
body: <p>I need to apply a function to all the permutations of a list and get the one which the result is the lowest.  </p>
  
  <p>Currently I have something like this (it uses <code>library(combinat)</code>):  </p>
  
  <pre><code>scorePermutation &lt;- function(permutation) {
    acc &lt;- 0
    p &lt;- 1
    for (x in permutation) {
      #very simplified version of the orginal for block
      acc &lt;- acc + x/p
      p &lt;- p*1.02^(x/p)
    }
    names(acc) &lt;- paste(permutation, collapse=",")
    return (acc)
  }
  
  minScore &lt;- function(items) {
    scores &lt;- permn(items, scorePermutation)
    return (sort(unlist(scores))[1])
  }
  </code></pre>
  
  <p>I changed the scorePermutation function logic in order to make it simpler for the question, I know the code doesn't make much sense. </p>
  
  <p>I'm trying to improve the performance, particularly I'm trying to do <code>permn(items, scorePermutation)</code> in a vectorized way, but any tip will help.</p>
  
  <p>UPDATE  </p>
  
  <p>Currently the usage is like this: </p>
  
  <pre><code>minScore(c(15,8,42,16,4,23))
  #4,8,15,16,23,42 
  #       62.42506 
  </code></pre>
  
  <p>But I only need the minimum scoring permutation (in the example "4,8,15,16,23,42")</p>
  
  <p>UPDATE 2  </p>
  
  <p>Here is the code with the original logic:  </p>
  
  <pre><code>minScore &lt;- function(items, p) {
    f = function(x) scorePermutation(x, p)
    scores &lt;- permn(items, f)
    return (sort(unlist(scores))[1])
  }
  
  scorePermutation &lt;- function(permutation, startp) {
    acc &lt;- 0
    p &lt;- startp
    for (x in permutation) {
      acc &lt;- acc + x/p
      p &lt;- updateP(x, p) 
    }
    names(acc) &lt;- paste(permutation,collapse=",")
    return (acc)
  }
  
  updateP = function(value, p) {
    wh = ceiling(value/p)/ 60
    cd = wh %/% 24
    rh = wh %% 24
    ldsh = pmin(10, rh)
    lduh = pmax(0, rh-10)
    shf = 1.02^(cd*10+ldsh)
    uhf = 0.9 ^(cd*14+lduh)
    np = p*shf*uhf
    np = pmax(np, 0.25)
    np = pmin(np, 4)  
    return (np)    
  }
  </code></pre>