Search code examples
scalastringbuilder

stringbuilder Scala drop duplicate chars


  class Buffer(s: String) {

  import scala.collection.mutable.StringBuilder
  import scala.io.StdIn

  private var buffer: StringBuilder = new StringBuilder(s)
  private var cursor: Int = 0  // cursor is in between characters
  private var marker: Int = 0  // marker is in between characters
  private var paste: String = ""
  private def end: Int = buffer.length              // the end of the line
  private def lwr: Int = Math.min(marker, cursor)
  private def upr: Int = Math.max(marker, cursor)

  /*
   * Accessor methods to return aspects of the state
   */
  def getCursor: Int = cursor
  def getMarker: Int = marker
  def getString: String = buffer.toString
  def getPaste: String = paste


          /**
       * Delete Duplicate characters.  Within the defined region, for each character,
       * if it occurs once then keep it, but if it occurs multiple times then keep
       * only the first occurrence.  The characters to the left and right of the
       * defined region remain unchanged, but within the defined region the duplicates
       * are removed. This operation does not affect the paste buffer. The cursor is
       * placed finally at the lower end of the defined region and the marker is placed
       * finally at the upper end of the (probably reduced) defined region. For example:
       * 
       *     m i s s i s s i p p i       marker =  1       
       *      ^                 ^        cursor = 10
       *
       * Then perform  sc('a', 'X')
       * 
       *     m i s p i      marker = 1       
       *      ^     ^       cursor = 4
       */
      def dd() 
      {
        var droppedchars: Int = 0;
         for (x <- lwr until upr)
         {
           var c = buffer.charAt(x)
           for (i <- lwr until upr)
           {
             if (buffer.charAt(i) == c)
             {
               buffer.deleteCharAt(i)
               droppedchars += 1

             }
           }
           marker = lwr
           cursor = upr - droppedchars


         }
      }

Need some help with this one too, doesn't appear to work function needs to drop any duplicate chars it finds, move the marker back to the start of the new defined region and the cursor to the end of the new defined region, not asking for somebody to write this for me just guide me in the right direction


Solution

  • Why not just:

    scala> "mississippi".distinct
    res22: String = misp