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.4

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

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

  output
end

def fixed_points(left, right)
  left.zip(right).count { |pair| pair[0] == pair[1] }
end

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

  while shift < chars.length
    candidate = rotate_left(chars, shift)
    candidate_fixed_points = fixed_points(word.chars, 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.