Note that there are some explanatory texts on larger screens.

plurals
  1. POGeneralising a "next permutation" function
    primarykey
    data
    text
    <p>Below is an implementation of a function that returns the lexographically next permutation. This is useful in one of the Euler problems. </p> <p>It's written to work on Strings (which I needed for that). However, it should work on any indexed sequence of comparable values. I've tried generalising it by changing the two occurrences of String to IndexedSeq[Char], but this gets an error:</p> <pre><code>euler-lib.scala:26: error: type mismatch; found : IndexedSeq[Char] required: String ((n.slice(pivot+1, successor):+ n(pivot)) + n.drop(successor+1)).reverse ^ </code></pre> <p>Why has the type inferencer inferred String there? I don't seem to have done any operation that requires a String?</p> <p>And can I make it more general still by having IndexedSeq["something-comparable"]? I've not been able to make this work.</p> <pre><code> // return the lexographically next permutation to the one passed as a parameter // pseudo-code from an article on StackOverflow def nextPermutation(n:String):String = { // 1. scan the array from right-to-left //1.1. if the current element is less than its right-hand neighbor, // call the current element the pivot, // and stop scanning // (We scan left-to-right and return the last such). val pivot = n.zip(n.tail).lastIndexWhere{ case (first, second) =&gt; first &lt; second } //1.2. if the left end is reached without finding a pivot, // reverse the array and return // (the permutation was the lexicographically last, so its time to start over) if (pivot &lt; 0) return n.reverse //2. scan the array from right-to-left again, // to find the rightmost element larger than the pivot // (call that one the successor) val successor = n.lastIndexWhere{_ &gt; n(pivot)} //3. swap the pivot and the successor, and //4. reverse the portion of the array to the right of where the pivot was found return (n.take(pivot) :+ n(successor)) + ((n.slice(pivot+1, successor):+ n(pivot)) + n.drop(successor+1)).reverse } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload