WeixiangYan/CodeTransOcean huggingface dataset:
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);
    }

}
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.
>>>
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
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))
}
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;
            }
        }
    }
}








Fortran:       CHARACTER*12345 TEXT
       ...
      DO I = 0,120
        WRITE (6,*) TEXT(I*80 + 1:(I + 1)*80)
      END DO
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";
}









Fortran:       CHARACTER*12345 TEXT
       ...
      DO I = 0,120
        WRITE (6,*) TEXT(I*80 + 1:(I + 1)*80)
      END DO
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))
}







Fortran:       CHARACTER*12345 TEXT
       ...
      DO I = 0,120
        WRITE (6,*) TEXT(I*80 + 1:(I + 1)*80)
      END DO
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);
    }

}






Fortran:       CHARACTER*12345 TEXT
       ...
      DO I = 0,120
        WRITE (6,*) TEXT(I*80 + 1:(I + 1)*80)
      END DO
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.
>>>




Fortran:       CHARACTER*12345 TEXT
       ...
      DO I = 0,120
        WRITE (6,*) TEXT(I*80 + 1:(I + 1)*80)
      END DO
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



Fortran:       CHARACTER*12345 TEXT
       ...
      DO I = 0,120
        WRITE (6,*) TEXT(I*80 + 1:(I + 1)*80)
      END DO
Task: Word wrap






PHP: <?php

$text = <<<ENDTXT
If there's anything you need
All you have to do is say
You know you satisfy everything in me
We shouldn't waste a single day

So don't stop me falling
It's destiny calling
A power I just can't deny
It's never changing
Can't you hear me, I'm saying
I want you for the rest of my life

Together forever and never to part
Together forever we two
And don't you know
I would move heaven and earth
To be together forever with you
ENDTXT;

$text = str_replace( PHP_EOL,  " " , $text );

echo wordwrap( $text, 20 ), PHP_EOL, PHP_EOL;

echo wordwrap( $text, 40 ), PHP_EOL, PHP_EOL;

echo wordwrap( $text, 80 ), PHP_EOL, PHP_EOL;





Fortran:       CHARACTER*12345 TEXT
       ...
      DO I = 0,120
        WRITE (6,*) TEXT(I*80 + 1:(I + 1)*80)
      END DO
Task: Word wrap






PHP: <?php

$text = <<<ENDTXT
If there's anything you need
All you have to do is say
You know you satisfy everything in me
We shouldn't waste a single day

So don't stop me falling
It's destiny calling
A power I just can't deny
It's never changing
Can't you hear me, I'm saying
I want you for the rest of my life

Together forever and never to part
Together forever we two
And don't you know
I would move heaven and earth
To be together forever with you
ENDTXT;

$text = str_replace( PHP_EOL,  " " , $text );

echo wordwrap( $text, 20 ), PHP_EOL, PHP_EOL;

echo wordwrap( $text, 40 ), PHP_EOL, PHP_EOL;

echo wordwrap( $text, 80 ), PHP_EOL, PHP_EOL;
Task: Word wrap






PHP: <?php

$text = <<<ENDTXT
If there's anything you need
All you have to do is say
You know you satisfy everything in me
We shouldn't waste a single day

So don't stop me falling
It's destiny calling
A power I just can't deny
It's never changing
Can't you hear me, I'm saying
I want you for the rest of my life

Together forever and never to part
Together forever we two
And don't you know
I would move heaven and earth
To be together forever with you
ENDTXT;

$text = str_replace( PHP_EOL,  " " , $text );

echo wordwrap( $text, 20 ), PHP_EOL, PHP_EOL;

echo wordwrap( $text, 40 ), PHP_EOL, PHP_EOL;

echo wordwrap( $text, 80 ), PHP_EOL, PHP_EOL;






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: Harshad or Niven series



C#: using System;
using System.Collections.Generic;

namespace Harshad
{
    class Program
    {
        public static bool IsHarshad(int n)
        {
            char[] inputChars = n.ToString().ToCharArray();
            IList<byte> digits = new List<byte>();

            foreach (char digit in inputChars)
            {
                digits.Add((byte)Char.GetNumericValue(digit));
            }

            if (n < 1)
            {
                return false;
            }

            int sum = 0;

            foreach (byte digit in digits)
            {
                sum += digit;
            }

            return n % sum == 0;
        }

        static void Main(string[] args)
        {
            int i = 1;
            int count = 0;

            while (true)
            {
                if (IsHarshad(i))
                {
                    count++;

                    if (count <= 20)
                    {
                        Console.Write(string.Format("{0} ", i));
                    }
                    else if (i > 1000)
                    {
                        Console.Write(string.Format("{0} ", i));
                        break;
                    }
                }

                i++;
            }

            Console.ReadKey();
        }
    }
}









Ada: with Ada.Text_IO;

procedure Harshad is
   
   function Next(N: in out Positive) return Positive is
      
      function Sum_Of_Digits(N: Natural) return Natural is
	 ( if N = 0 then 0 else ((N mod 10) + Sum_Of_Digits(N / 10)) );
	 
   begin
      while not (N mod Sum_Of_Digits(N) = 0) loop
	 N := N + 1;
      end loop;
      return N;
   end Next;
   
   Current: Positive := 1;
   
begin
   for I in 1 .. 20 loop
      Ada.Text_IO.Put(Integer'Image(Next(Current)));
      Current := Current + 1;
   end loop;
   Current := 1000 + 1; 
   Ada.Text_IO.Put_Line(" ..." & Integer'Image(Next(Current)));
end Harshad;
Task: Harshad or Niven series

C: #include <stdio.h>

static int digsum(int n)
{
    int sum = 0;
    do { sum += n % 10; } while (n /= 10);
    return sum;
}

int main(void)
{
    int n, done, found;

    for (n = 1, done = found = 0; !done; ++n) {
        if (n % digsum(n) == 0) {
            if (found++ < 20) printf("%d ", n);
            if (n > 1000) done = printf("\n%d\n", n);
        }
    }

    return 0;
}











Ada: with Ada.Text_IO;

procedure Harshad is
   
   function Next(N: in out Positive) return Positive is
      
      function Sum_Of_Digits(N: Natural) return Natural is
	 ( if N = 0 then 0 else ((N mod 10) + Sum_Of_Digits(N / 10)) );
	 
   begin
      while not (N mod Sum_Of_Digits(N) = 0) loop
	 N := N + 1;
      end loop;
      return N;
   end Next;
   
   Current: Positive := 1;
   
begin
   for I in 1 .. 20 loop
      Ada.Text_IO.Put(Integer'Image(Next(Current)));
      Current := Current + 1;
   end loop;
   Current := 1000 + 1; 
   Ada.Text_IO.Put_Line(" ..." & Integer'Image(Next(Current)));
end Harshad;
Task: Harshad or Niven series


C++: #include <vector>
#include <iostream>

int sumDigits ( int number ) {
   int sum = 0 ;
   while ( number != 0 ) {
      sum += number % 10 ;
      number /= 10 ;
   }
   return sum ;
}

bool isHarshad ( int number ) {
   return number % ( sumDigits ( number ) ) == 0 ;
}

int main( ) {
   std::vector<int> harshads ;
   int i = 0 ;
   while ( harshads.size( ) != 20 ) {
      i++ ;
      if ( isHarshad ( i ) ) 
	 harshads.push_back( i ) ;
   }
   std::cout << "The first 20 Harshad numbers:\n" ;
   for ( int number : harshads )
      std::cout << number << " " ;
   std::cout << std::endl ;
   int start = 1001 ;
   while ( ! ( isHarshad ( start ) ) ) 
      start++ ;
   std::cout << "The smallest Harshad number greater than 1000 : " << start << '\n' ;
   return 0 ;
}










Ada: with Ada.Text_IO;

procedure Harshad is
   
   function Next(N: in out Positive) return Positive is
      
      function Sum_Of_Digits(N: Natural) return Natural is
	 ( if N = 0 then 0 else ((N mod 10) + Sum_Of_Digits(N / 10)) );
	 
   begin
      while not (N mod Sum_Of_Digits(N) = 0) loop
	 N := N + 1;
      end loop;
      return N;
   end Next;
   
   Current: Positive := 1;
   
begin
   for I in 1 .. 20 loop
      Ada.Text_IO.Put(Integer'Image(Next(Current)));
      Current := Current + 1;
   end loop;
   Current := 1000 + 1; 
   Ada.Text_IO.Put_Line(" ..." & Integer'Image(Next(Current)));
end Harshad;