Rosetta Code

Best shuffle

Produce a low-fixed-point shuffle by rotating the sorted characters of a word.

Medium View source
Source rosettacode/popular/best_shuffle.vibe
# title: Best shuffle
# source: https://rosettacode.org/wiki/Best_shuffle
# category: Rosetta Code
# difficulty: Medium
# summary: Produce a low-fixed-point shuffle by rotating the sorted characters of a word.
# tags: popular, strings, permutations, heuristics
# vibe: 0.2

def rotate_left(values, amount)
  output = []
  index = 0

  while index < values.length
    output = output.push(values[(index + amount) % values.length])
    index = index + 1
  end

  output
end

def fixed_points(left, right)
  count = 0
  index = 0

  while index < left.length
    if left[index] == right[index]
      count = count + 1
    end
    index = index + 1
  end

  count
end

def best_shuffle(word)
  chars = word.split("").sort
  best = chars
  best_fixed_points = fixed_points(word.split(""), chars)
  shift = 1

  while shift < chars.length
    candidate = rotate_left(chars, shift)
    candidate_fixed_points = fixed_points(word.split(""), candidate)
    if candidate_fixed_points < best_fixed_points
      best = candidate
      best_fixed_points = candidate_fixed_points
    end
    shift = shift + 1
  end

  {
    original: word,
    shuffled: best.join(""),
    fixed_points: best_fixed_points
  }
end

def run
  [
    best_shuffle("abracadabra"),
    best_shuffle("seesaw"),
    best_shuffle("vibescript")
  ]
end
Output
Press run to execute run from this example.
rosetta-code popular strings permutations heuristics browser-runner