How to resolve the algorithm Best shuffle step by step in the Seed7 programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Best shuffle step by step in the Seed7 programming language

Table of Contents

Problem Statement

Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative. Display the result as follows: The score gives the number of positions whose character value did not change.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Best shuffle step by step in the Seed7 programming language

Source code in the seed7 programming language

$ include "seed7_05.s7i";

const func string: bestShuffle (in string: stri) is func
  result
    var string: shuffled is "";
  local
    var char: tmp is ' ';
    var integer: i is 0;
    var integer: j is 0;
  begin
    shuffled := stri;
    for key i range shuffled do
      for key j range shuffled do
        if i <> j and stri[i] <> shuffled[j] and stri[j] <> shuffled[i] then
          tmp  := shuffled[i];
          shuffled @:= [i] shuffled[j];
          shuffled @:= [j] tmp;
        end if;
      end for;
    end for;
  end func;

const proc: main is func
  local
    const array string: testData is [] ("abracadabra", "seesaw", "elk", "grrrrrr", "up", "a");
    var string: original is "";
    var string: shuffled is "";
    var integer: j is 0;
    var integer: score is 0;
  begin
    for original range testData do
      shuffled := bestShuffle(original);
      score := 0;
      for key j range shuffled do
        if original[j] = shuffled[j] then
          incr(score);
        end if;
      end for;
      writeln(original <& ", " <& shuffled <& ", (" <& score <& ")");
    end for;
  end func;

  

You may also check:How to resolve the algorithm Averages/Pythagorean means step by step in the Maple programming language
You may also check:How to resolve the algorithm Real constants and functions step by step in the Lua programming language
You may also check:How to resolve the algorithm Regular expressions step by step in the Inform 7 programming language
You may also check:How to resolve the algorithm Determine sentence type step by step in the RPL programming language
You may also check:How to resolve the algorithm Stack traces step by step in the PL/I programming language