WeixiangYan/CodeTransOcean huggingface dataset:
Task: 100 prisoners





Java: import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    private static boolean playOptimal(int n) {
        List<Integer> secretList = IntStream.range(0, n).boxed().collect(Collectors.toList());
        Collections.shuffle(secretList);

        prisoner:
        for (int i = 0; i < secretList.size(); ++i) {
            int prev = i;
            for (int j = 0; j < secretList.size() / 2; ++j) {
                if (secretList.get(prev) == i) {
                    continue prisoner;
                }
                prev = secretList.get(prev);
            }
            return false;
        }
        return true;
    }

    private static boolean playRandom(int n) {
        List<Integer> secretList = IntStream.range(0, n).boxed().collect(Collectors.toList());
        Collections.shuffle(secretList);

        prisoner:
        for (Integer i : secretList) {
            List<Integer> trialList = IntStream.range(0, n).boxed().collect(Collectors.toList());
            Collections.shuffle(trialList);

            for (int j = 0; j < trialList.size() / 2; ++j) {
                if (Objects.equals(trialList.get(j), i)) {
                    continue prisoner;
                }
            }

            return false;
        }
        return true;
    }

    private static double exec(int n, int p, Function<Integer, Boolean> play) {
        int succ = 0;
        for (int i = 0; i < n; ++i) {
            if (play.apply(p)) {
                succ++;
            }
        }
        return (succ * 100.0) / n;
    }

    public static void main(String[] args) {
        final int n = 100_000;
        final int p = 100;
        System.out.printf("# of executions: %d\n", n);
        System.out.printf("Optimal play success rate: %f%%\n", exec(n, p, Main::playOptimal));
        System.out.printf("Random play success rate: %f%%\n", exec(n, p, Main::playRandom));
    }
}
Task: 100 prisoners







Python: import random

def play_random(n):
    
    pardoned = 0
    in_drawer = list(range(100))
    sampler = list(range(100))
    for _round in range(n):
        random.shuffle(in_drawer)
        found = False
        for prisoner in range(100):
            found = False
            for reveal in random.sample(sampler, 50):
                card = in_drawer[reveal]
                if card == prisoner:
                    found = True
                    break
            if not found:
                break
        if found:
            pardoned += 1
    return pardoned / n * 100   

def play_optimal(n):
    
    pardoned = 0
    in_drawer = list(range(100))
    for _round in range(n):
        random.shuffle(in_drawer)
        for prisoner in range(100):
            reveal = prisoner
            found = False
            for go in range(50):
                card = in_drawer[reveal]
                if card == prisoner:
                    found = True
                    break
                reveal = card
            if not found:
                break
        if found:
            pardoned += 1
    return pardoned / n * 100   

if __name__ == '__main__':
    n = 100_000
    print(" Simulation count:", n)
    print(f" Random play wins: {play_random(n):4.1f}% of simulations")
    print(f"Optimal play wins: {play_optimal(n):4.1f}% of simulations")
Task: 100 prisoners




Go: package main

import (
    "fmt"
    "math/rand"
    "time"
)


func doTrials(trials, np int, strategy string) {
    pardoned := 0
trial:
    for t := 0; t < trials; t++ {
        var drawers [100]int
        for i := 0; i < 100; i++ {
            drawers[i] = i
        }
        rand.Shuffle(100, func(i, j int) {
            drawers[i], drawers[j] = drawers[j], drawers[i]
        })
    prisoner:
        for p := 0; p < np; p++ {
            if strategy == "optimal" {
                prev := p
                for d := 0; d < 50; d++ {
                    this := drawers[prev]
                    if this == p {
                        continue prisoner
                    }
                    prev = this
                }
            } else {
                
                
                var opened [100]bool
                for d := 0; d < 50; d++ {
                    var n int
                    for {
                        n = rand.Intn(100)
                        if !opened[n] {
                            opened[n] = true
                            break
                        }
                    }
                    if drawers[n] == p {
                        continue prisoner
                    }
                }
            }
            continue trial
        }
        pardoned++
    }
    rf := float64(pardoned) / float64(trials) * 100
    fmt.Printf("  strategy = %-7s  pardoned = %-6d relative frequency = %5.2f%%\n\n", strategy, pardoned, rf)
}

func main() {
    rand.Seed(time.Now().UnixNano())
    const trials = 100000
    for _, np := range []int{10, 100} {
        fmt.Printf("Results from %d trials with %d prisoners:\n\n", trials, np)
        for _, strategy := range [2]string{"random", "optimal"} {
            doTrials(trials, np, strategy)
        }
    }
}
Task: Word wrap



C#: namespace RosettaCode.WordWrap
{
    using System;
    using System.Collections.Generic;

    internal static class Program
    {
        private const string LoremIpsum = @"
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien
vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu
pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus
consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt
purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel
felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta
tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est,
condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed
venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu
nibh.";

        private static void Main()
        {
            foreach (var lineWidth in new[] { 72, 80 })
            {
                Console.WriteLine(new string('-', lineWidth));
                Console.WriteLine(Wrap(LoremIpsum, lineWidth));
            }
        }

        private static string Wrap(string text, int lineWidth)
        {
            return string.Join(string.Empty,
                               Wrap(
                                   text.Split(new char[0],
                                              StringSplitOptions
                                                  .RemoveEmptyEntries),
                                   lineWidth));
        }

        private static IEnumerable<string> Wrap(IEnumerable<string> words,
                                                int lineWidth)
        {
            var currentWidth = 0;
            foreach (var word in words)
            {
                if (currentWidth != 0)
                {
                    if (currentWidth + word.Length < lineWidth)
                    {
                        currentWidth++;
                        yield return " ";
                    }
                    else
                    {
                        currentWidth = 0;
                        yield return Environment.NewLine;
                    }
                }
                currentWidth += word.Length;
                yield return word;
            }
        }
    }
}









Ada: generic
   with procedure Put_Line(Line: String);
package Word_Wrap is

   type Basic(Length_Of_Output_Line: Positive) is tagged private;

   procedure Push_Word(State: in out Basic; Word: String);
   procedure New_Paragraph(State: in out Basic);
   procedure Finish(State: in out Basic);

private
   type Basic(Length_Of_Output_Line: Positive) is tagged record
      Line: String(1 .. Length_Of_Output_Line);
      Size: Natural := 0; 
      Top_Of_Paragraph: Boolean := True;
   end record;

end Word_Wrap;
Task: Word wrap


C++: #include <iostream>
#include <sstream>
#include <string>

const char *text =
{
    "In olden times when wishing still helped one, there lived a king "
    "whose daughters were all beautiful, but the youngest was so beautiful "
    "that the sun itself, which has seen so much, was astonished whenever "
    "it shone in her face.  Close by the king's castle lay a great dark "
    "forest, and under an old lime tree in the forest was a well, and when "
    "the day was very warm, the king's child went out into the forest and "
    "sat down by the side of the cool fountain, and when she was bored she "
    "took a golden ball, and threw it up on high and caught it, and this "
    "ball was her favorite plaything."
};

std::string wrap(const char *text, size_t line_length = 72)
{
    std::istringstream words(text);
    std::ostringstream wrapped;
    std::string word;

    if (words >> word) {
        wrapped << word;
        size_t space_left = line_length - word.length();
        while (words >> word) {
            if (space_left < word.length() + 1) {
                wrapped << '\n' << word;
                space_left = line_length - word.length();
            } else {
                wrapped << ' ' << word;
                space_left -= word.length() + 1;
            }
        }
    }
    return wrapped.str();
}

int main()
{
    std::cout << "Wrapped at 72:\n" << wrap(text) << "\n\n";
    std::cout << "Wrapped at 80:\n" << wrap(text, 80) << "\n";
}










Ada: generic
   with procedure Put_Line(Line: String);
package Word_Wrap is

   type Basic(Length_Of_Output_Line: Positive) is tagged private;

   procedure Push_Word(State: in out Basic; Word: String);
   procedure New_Paragraph(State: in out Basic);
   procedure Finish(State: in out Basic);

private
   type Basic(Length_Of_Output_Line: Positive) is tagged record
      Line: String(1 .. Length_Of_Output_Line);
      Size: Natural := 0; 
      Top_Of_Paragraph: Boolean := True;
   end record;

end Word_Wrap;
Task: Word wrap




Go: package main

import (
    "fmt"
    "strings"
)

func wrap(text string, lineWidth int) (wrapped string) {
    words := strings.Fields(text)
    if len(words) == 0 {
        return
    }
    wrapped = words[0]
    spaceLeft := lineWidth - len(wrapped)
    for _, word := range words[1:] {
        if len(word)+1 > spaceLeft {
            wrapped += "\n" + word
            spaceLeft = lineWidth - len(word)
        } else {
            wrapped += " " + word
            spaceLeft -= 1 + len(word)
        }
    }
    return
}

var frog = `
In olden times when wishing still helped one, there lived a king
whose daughters were all beautiful, but the youngest was so beautiful
that the sun itself, which has seen so much, was astonished whenever
it shone in her face.  Close by the king's castle lay a great dark
forest, and under an old lime-tree in the forest was a well, and when
the day was very warm, the king's child went out into the forest and
sat down by the side of the cool fountain, and when she was bored she
took a golden ball, and threw it up on high and caught it, and this
ball was her favorite plaything.`

func main() {
    fmt.Println("wrapped at 80:")
    fmt.Println(wrap(frog, 80))
    fmt.Println("wrapped at 72:")
    fmt.Println(wrap(frog, 72))
}








Ada: generic
   with procedure Put_Line(Line: String);
package Word_Wrap is

   type Basic(Length_Of_Output_Line: Positive) is tagged private;

   procedure Push_Word(State: in out Basic; Word: String);
   procedure New_Paragraph(State: in out Basic);
   procedure Finish(State: in out Basic);

private
   type Basic(Length_Of_Output_Line: Positive) is tagged record
      Line: String(1 .. Length_Of_Output_Line);
      Size: Natural := 0; 
      Top_Of_Paragraph: Boolean := True;
   end record;

end Word_Wrap;
Task: Word wrap





Java: package rosettacode;

import java.util.StringTokenizer;

public class WordWrap 
{
    int defaultLineWidth=80;
    int defaultSpaceWidth=1;
    void minNumLinesWrap(String text)
    {
        minNumLinesWrap(text,defaultLineWidth);
    }
    void minNumLinesWrap(String text,int LineWidth)
    {
        StringTokenizer st=new StringTokenizer(text);
        int SpaceLeft=LineWidth;
        int SpaceWidth=defaultSpaceWidth;
        while(st.hasMoreTokens())
        {
            String word=st.nextToken();
            if((word.length()+SpaceWidth)>SpaceLeft)
            {
                System.out.print("\n"+word+" ");
                SpaceLeft=LineWidth-word.length();
            }
            else
            {
                System.out.print(word+" ");
                SpaceLeft-=(word.length()+SpaceWidth);
            }
        }
    }
    public static void main(String[] args)
    {
        WordWrap now=new WordWrap();
        String wodehouse="Old Mr MacFarland (_said Henry_) started the place fifteen years ago. He was a widower with one son and what you might call half a daughter. That's to say, he had adopted her. Katie was her name, and she was the child of a dead friend of his. The son's name was Andy. A little freckled nipper he was when I first knew him--one of those silent kids that don't say much and have as much obstinacy in them as if they were mules. Many's the time, in them days, I've clumped him on the head and told him to do something; and he didn't run yelling to his pa, same as most kids would have done, but just said nothing and went on not doing whatever it was I had told him to do. That was the sort of disposition Andy had, and it grew on him. Why, when he came back from Oxford College the time the old man sent for him--what I'm going to tell you about soon--he had a jaw on him like the ram of a battleship. Katie was the kid for my money. I liked Katie. We all liked Katie.";
        System.out.println("DEFAULT:");
        now.minNumLinesWrap(wodehouse);
        System.out.println("\n\nLINEWIDTH=120");
        now.minNumLinesWrap(wodehouse,120);
    }

}







Ada: generic
   with procedure Put_Line(Line: String);
package Word_Wrap is

   type Basic(Length_Of_Output_Line: Positive) is tagged private;

   procedure Push_Word(State: in out Basic; Word: String);
   procedure New_Paragraph(State: in out Basic);
   procedure Finish(State: in out Basic);

private
   type Basic(Length_Of_Output_Line: Positive) is tagged record
      Line: String(1 .. Length_Of_Output_Line);
      Size: Natural := 0; 
      Top_Of_Paragraph: Boolean := True;
   end record;

end Word_Wrap;
Task: Word wrap







Python: >>> import textwrap
>>> help(textwrap.fill)
Help on function fill in module textwrap:

fill(text, width=70, **kwargs)
    Fill a single paragraph of text, returning a new string.
    
    Reformat the single paragraph in 'text' to fit in lines of no more
    than 'width' columns, and return a new string containing the entire
    wrapped paragraph.  As with wrap(), tabs are expanded and other
    whitespace characters converted to space.  See TextWrapper class for
    available keyword args to customize wrapping behaviour.

>>> txt = 
>>> print(textwrap.fill(txt, width=75))
Reformat the single paragraph in 'text' to fit in lines of no more than
'width' columns, and return a new string containing the entire wrapped
paragraph.  As with wrap(), tabs are expanded and other whitespace
characters converted to space.  See TextWrapper class for available keyword
args to customize wrapping behaviour.
>>> print(textwrap.fill(txt, width=45))
Reformat the single paragraph in 'text' to
fit in lines of no more than 'width' columns,
and return a new string containing the entire
wrapped paragraph.  As with wrap(), tabs are
expanded and other whitespace characters
converted to space.  See TextWrapper class
for available keyword args to customize
wrapping behaviour.
>>> print(textwrap.fill(txt, width=85))
Reformat the single paragraph in 'text' to fit in lines of no more than 'width'
columns, and return a new string containing the entire wrapped paragraph.  As with
wrap(), tabs are expanded and other whitespace characters converted to space.  See
TextWrapper class for available keyword args to customize wrapping behaviour.
>>>





Ada: generic
   with procedure Put_Line(Line: String);
package Word_Wrap is

   type Basic(Length_Of_Output_Line: Positive) is tagged private;

   procedure Push_Word(State: in out Basic; Word: String);
   procedure New_Paragraph(State: in out Basic);
   procedure Finish(State: in out Basic);

private
   type Basic(Length_Of_Output_Line: Positive) is tagged record
      Line: String(1 .. Length_Of_Output_Line);
      Size: Natural := 0; 
      Top_Of_Paragraph: Boolean := True;
   end record;

end Word_Wrap;
Task: Word wrap








VB: column = 60
text = "In olden times when wishing still helped one, there lived a king " &_
    "whose daughters were all beautiful, but the youngest was so beautiful "&_
    "that the sun itself, which has seen so much, was astonished whenever "&_
    "it shone-in-her-face.  Close-by-the-king
    "forest, and under an old lime-tree in the forest was a well, and when "&_
    "the day was very warm, the king
    "sat down by the side of the cool-fountain, and when she was bored she "&_
    "took a golden ball, and threw it up on high and caught it, and this "&_
    "ball was her favorite plaything."

Call wordwrap(text,column)

Sub wordwrap(s,n)
    word = Split(s," ")
    row = ""
    For i = 0 To UBound(word)
        If Len(row) = 0 Then
            row = row & word(i)
        ElseIf Len(row & " " & word(i)) <= n Then
            row = row & " " & word(i)
        Else
            WScript.StdOut.WriteLine row
            row = word(i)
        End If
    Next
    If Len(row) > 0 Then
        WScript.StdOut.WriteLine row
    End If
End Sub




Ada: generic
   with procedure Put_Line(Line: String);
package Word_Wrap is

   type Basic(Length_Of_Output_Line: Positive) is tagged private;

   procedure Push_Word(State: in out Basic; Word: String);
   procedure New_Paragraph(State: in out Basic);
   procedure Finish(State: in out Basic);

private
   type Basic(Length_Of_Output_Line: Positive) is tagged record
      Line: String(1 .. Length_Of_Output_Line);
      Size: Natural := 0; 
      Top_Of_Paragraph: Boolean := True;
   end record;

end Word_Wrap;
Task: Word wrap



C#: namespace RosettaCode.WordWrap
{
    using System;
    using System.Collections.Generic;

    internal static class Program
    {
        private const string LoremIpsum = @"
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien
vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu
pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus
consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt
purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel
felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta
tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est,
condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed
venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu
nibh.";

        private static void Main()
        {
            foreach (var lineWidth in new[] { 72, 80 })
            {
                Console.WriteLine(new string('-', lineWidth));
                Console.WriteLine(Wrap(LoremIpsum, lineWidth));
            }
        }

        private static string Wrap(string text, int lineWidth)
        {
            return string.Join(string.Empty,
                               Wrap(
                                   text.Split(new char[0],
                                              StringSplitOptions
                                                  .RemoveEmptyEntries),
                                   lineWidth));
        }

        private static IEnumerable<string> Wrap(IEnumerable<string> words,
                                                int lineWidth)
        {
            var currentWidth = 0;
            foreach (var word in words)
            {
                if (currentWidth != 0)
                {
                    if (currentWidth + word.Length < lineWidth)
                    {
                        currentWidth++;
                        yield return " ";
                    }
                    else
                    {
                        currentWidth = 0;
                        yield return Environment.NewLine;
                    }
                }
                currentWidth += word.Length;
                yield return word;
            }
        }
    }
}
Task: Word wrap


C++: #include <iostream>
#include <sstream>
#include <string>

const char *text =
{
    "In olden times when wishing still helped one, there lived a king "
    "whose daughters were all beautiful, but the youngest was so beautiful "
    "that the sun itself, which has seen so much, was astonished whenever "
    "it shone in her face.  Close by the king's castle lay a great dark "
    "forest, and under an old lime tree in the forest was a well, and when "
    "the day was very warm, the king's child went out into the forest and "
    "sat down by the side of the cool fountain, and when she was bored she "
    "took a golden ball, and threw it up on high and caught it, and this "
    "ball was her favorite plaything."
};

std::string wrap(const char *text, size_t line_length = 72)
{
    std::istringstream words(text);
    std::ostringstream wrapped;
    std::string word;

    if (words >> word) {
        wrapped << word;
        size_t space_left = line_length - word.length();
        while (words >> word) {
            if (space_left < word.length() + 1) {
                wrapped << '\n' << word;
                space_left = line_length - word.length();
            } else {
                wrapped << ' ' << word;
                space_left -= word.length() + 1;
            }
        }
    }
    return wrapped.str();
}

int main()
{
    std::cout << "Wrapped at 72:\n" << wrap(text) << "\n\n";
    std::cout << "Wrapped at 80:\n" << wrap(text, 80) << "\n";
}