WeixiangYan/CodeTransOcean huggingface dataset:
Task: Animate a pendulum


C++: #ifndef __wxPendulumDlg_h__
#define __wxPendulumDlg_h__






#ifdef __BORLANDC__
#pragma hdrstop
#endif

#ifndef WX_PRECOMP
#include <wx/wx.h>
#include <wx/dialog.h>
#else
#include <wx/wxprec.h>
#endif
#include <wx/timer.h>
#include <wx/dcbuffer.h>
#include <cmath>

class wxPendulumDlgApp : public wxApp
{
    public:
        bool OnInit();
        int OnExit();
};

class wxPendulumDlg : public wxDialog
{
    public:

        wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT("wxPendulum"), 
				 const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, 
				 long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);

        virtual ~wxPendulumDlg();
	
		
        void wxPendulumDlgPaint(wxPaintEvent& event);
        void wxPendulumDlgSize(wxSizeEvent& event);
        void OnTimer(wxTimerEvent& event);

    private:

		
        wxTimer *m_timer;

		unsigned int m_uiLength;
		double  	 m_Angle;
		double       m_AngleVelocity;

        enum wxIDs
        {
            ID_WXTIMER1 = 1001,
            ID_DUMMY_VALUE_ 
        };

        void OnClose(wxCloseEvent& event);
        void CreateGUIControls();

        DECLARE_EVENT_TABLE()
};

#endif 




Java: import java.awt.*;
import javax.swing.*;

public class Pendulum extends JPanel implements Runnable {

    private double angle = Math.PI / 2;
    private int length;

    public Pendulum(int length) {
        this.length = length;
        setDoubleBuffered(true);
    }

    @Override
    public void paint(Graphics g) {
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setColor(Color.BLACK);
        int anchorX = getWidth() / 2, anchorY = getHeight() / 4;
        int ballX = anchorX + (int) (Math.sin(angle) * length);
        int ballY = anchorY + (int) (Math.cos(angle) * length);
        g.drawLine(anchorX, anchorY, ballX, ballY);
        g.fillOval(anchorX - 3, anchorY - 4, 7, 7);
        g.fillOval(ballX - 7, ballY - 7, 14, 14);
    }

    public void run() {
        double angleAccel, angleVelocity = 0, dt = 0.1;
        while (true) {
            angleAccel = -9.81 / length * Math.sin(angle);
            angleVelocity += angleAccel * dt;
            angle += angleVelocity * dt;
            repaint();
            try { Thread.sleep(15); } catch (InterruptedException ex) {}
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(2 * length + 50, length / 2 * 3);
    }

    public static void main(String[] args) {
        JFrame f = new JFrame("Pendulum");
        Pendulum p = new Pendulum(200);
        f.add(p);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
        new Thread(p).start();
    }
}
Task: Gray code


C++: #include <bitset>
#include <iostream>
#include <string>
#include <assert.h>

uint32_t gray_encode(uint32_t b)
{
    return b ^ (b >> 1);
}

uint32_t gray_decode(uint32_t g)
{
    for (uint32_t bit = 1U << 31; bit > 1; bit >>= 1)
    {
        if (g & bit) g ^= bit >> 1;
    }
    return g;
}

std::string to_binary(int value) 
{
    const std::bitset<32> bs(value);
    const std::string str(bs.to_string());
    const size_t pos(str.find('1'));
    return pos == std::string::npos ? "0" : str.substr(pos);
}

int main()
{
    std::cout << "Number\tBinary\tGray\tDecoded\n";
    for (uint32_t n = 0; n < 32; ++n)
    {
        uint32_t g = gray_encode(n);
        assert(gray_decode(g) == n);

        std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n";
    }
}




Java: public class Gray {
	public static long grayEncode(long n){
		return n ^ (n >>> 1);
	}
	
	public static long grayDecode(long n) {
		long p = n;
		while ((n >>>= 1) != 0)
			p ^= n;
		return p;
	}
	public static void main(String[] args){
		System.out.println("i\tBinary\tGray\tDecoded");
		for(int i = -1; i < 32;i++){
			System.out.print(i +"\t");
			System.out.print(Integer.toBinaryString(i) + "\t");
			System.out.print(Long.toBinaryString(grayEncode(i))+ "\t");
			System.out.println(grayDecode(grayEncode(i)));
		}
	}
}
Task: Create a file on magnetic tape


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

#if defined(_WIN32) || defined(WIN32)
constexpr auto FILENAME = "tape.file";
#else
constexpr auto FILENAME = "/dev/tape";
#endif

int main() {
    std::filebuf fb;
    fb.open(FILENAME,std::ios::out);
    std::ostream os(&fb);
    os << "Hello World\n";
    fb.close();
    return 0;
}




Java: import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;

public class CreateFile {
    public static void main(String[] args) throws IOException {
        String os = System.getProperty("os.name");
        if (os.contains("Windows")) {
            Path path = Paths.get("tape.file");
            Files.write(path, Collections.singletonList("Hello World!"));
        } else {
            Path path = Paths.get("/dev/tape");
            Files.write(path, Collections.singletonList("Hello World!"));
        }
    }
}
Task: Sorting algorithms_Heapsort


C++: #include <algorithm>
#include <iterator>
#include <iostream>

template<typename RandomAccessIterator>
void heap_sort(RandomAccessIterator begin, RandomAccessIterator end) {
  std::make_heap(begin, end);
  std::sort_heap(begin, end);
}

int main() {
  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
  heap_sort(std::begin(a), std::end(a));
  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
  std::cout << "\n";
}




Java: public static void heapSort(int[] a){
	int count = a.length;

	
	heapify(a, count);

	int end = count - 1;
	while(end > 0){
		
		
		int tmp = a[end];
		a[end] = a[0];
		a[0] = tmp;
		
		siftDown(a, 0, end - 1);
		
		
		end--;
	}
}

public static void heapify(int[] a, int count){
	
	int start = (count - 2) / 2; 

	while(start >= 0){
		
		
		
		siftDown(a, start, count - 1);
		start--;
	}
	
}

public static void siftDown(int[] a, int start, int end){
	
	int root = start;

	while((root * 2 + 1) <= end){      
		int child = root * 2 + 1;           
		
		if(child + 1 <= end && a[child] < a[child + 1])
			child = child + 1;           
		if(a[root] < a[child]){     
			int tmp = a[root];
			a[root] = a[child];
			a[child] = tmp;
			root = child;                
		}else
			return;
	}
}
Task: Playing cards


C++: #include <deque>
#include <algorithm>
#include <ostream>
#include <iterator>

namespace cards
{
class card
{
public:
    enum pip_type { two, three, four, five, six, seven, eight, nine, ten,
                    jack, queen, king, ace, pip_count };
    enum suite_type { hearts, spades, diamonds, clubs, suite_count };
    enum { unique_count = pip_count * suite_count };

    card(suite_type s, pip_type p): value(s + suite_count * p) {}

    explicit card(unsigned char v = 0): value(v) {}

    pip_type pip() { return pip_type(value / suite_count); }

    suite_type suite() { return suite_type(value % suite_count); }

private:
    unsigned char value;
};

const char* const pip_names[] =
    { "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten",
      "jack", "queen", "king", "ace" };

std::ostream& operator<<(std::ostream& os, card::pip_type pip)
{
    return os << pip_names[pip];
}

const char* const suite_names[] =
    { "hearts", "spades", "diamonds", "clubs" };

std::ostream& operator<<(std::ostream& os, card::suite_type suite)
{
    return os << suite_names[suite];
}

std::ostream& operator<<(std::ostream& os, card c)
{
    return os << c.pip() << " of " << c.suite();
}

class deck
{
public:
    deck()
    {
        for (int i = 0; i < card::unique_count; ++i) {
            cards.push_back(card(i));
        }
    }

    void shuffle() { std::random_shuffle(cards.begin(), cards.end()); }

    card deal() { card c = cards.front(); cards.pop_front(); return c; }

    typedef std::deque<card>::const_iterator const_iterator;
    const_iterator begin() const { return cards.cbegin(); }
    const_iterator end() const { return cards.cend(); }
private:
    std::deque<card> cards;
};

inline std::ostream& operator<<(std::ostream& os, const deck& d)
{
    std::copy(d.begin(), d.end(), std::ostream_iterator<card>(os, "\n"));
    return os;
}
}




Java: public enum Pip { Two, Three, Four, Five, Six, Seven, 
    Eight, Nine, Ten, Jack, Queen, King, Ace }
Task: Arrays


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


#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>


template <typename Array>
void demonstrate(Array& array)
{
  
  array[2] = "Three";  
                       
  array.at(1) = "Two"; 
                       
  
  
  std::reverse(begin(array), end(array));
  std::for_each(begin(array), end(array),
    [](typename Array::value_type const& element) 
    {
      std::cout << element << ' ';
    });
  
  std::cout << '\n';
}

int main()
{
  
  auto fixed_size_array = std::array<std::string, 3>{ "One", "Four", "Eight" };
  
  
  
  auto dynamic_array = std::vector<std::string>{ "One", "Four" };
  dynamic_array.push_back("Eight"); 
  
  
  demonstrate(fixed_size_array);
  demonstrate(dynamic_array);
}




Java: Int[] literalArray = [1,2,3];
Int[] fixedLengthArray = new Int[10];
Int[] variableArray = new Int[];

assert literalArray.size == 3; 
Int n = literalArray[2];       
fixedLengthArray[4] = 12345;   

fixedLengthArray += 6789;  
variableArray    += 6789;
Task: Sierpinski carpet


C++: 


#include <cstdint>
#include <cstdlib>
#include <cstdio>

static constexpr int32_t bct_low_bits = 0x55555555;

static int32_t bct_decrement(int32_t v) {
    --v;            
    return v ^ (v & (v>>1) & bct_low_bits);     
}

int main (int argc, char *argv[])
{
    
    const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;
    
    if (n < 0 || 9 < n) {                       
        std::printf("N out of range (use 0..9): %ld\n", long(n));
        return 1;
    }

    const int32_t size_bct = 1<<(n*2);          
    
    int32_t y = size_bct;
    do {                                        
        y = bct_decrement(y);                   
        int32_t x = size_bct;
        do {                                    
            x = bct_decrement(x);               
            
            std::putchar((x & y & bct_low_bits) ? ' ' : '#');
        } while (0 < x);
        std::putchar('\n');
    } while (0 < y);

    return 0;
}




Java: public static boolean inCarpet(long x, long y) {
    while (x!=0 && y!=0) {
        if (x % 3 == 1 && y % 3 == 1)
            return false;
        x /= 3;
        y /= 3;
    }
    return true;
}
 
public static void carpet(final int n) {
    final double power = Math.pow(3,n);
    for(long i = 0; i < power; i++) {
        for(long j = 0; j < power; j++) {
            System.out.print(inCarpet(i, j) ? "*" : " ");
        }
        System.out.println();
    }
}
Task: Sorting algorithms_Bogosort


C++: #include <algorithm>
#include <iostream>
#include <iterator>
#include <random>

template <typename RandomAccessIterator, typename Predicate>
void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,
               Predicate p) {
  std::random_device rd;
  std::mt19937 generator(rd());
  while (!std::is_sorted(begin, end, p)) {
    std::shuffle(begin, end, generator);
  }
}

template <typename RandomAccessIterator>
void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {
  bogo_sort(
      begin, end,
      std::less<
          typename std::iterator_traits<RandomAccessIterator>::value_type>());
}

int main() {
  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
  bogo_sort(std::begin(a), std::end(a));
  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
  std::cout << "\n";
}




Java: public class BogoSort 
{
	public static void main(String[] args)
	{
		
		int[] arr={4,5,6,0,7,8,9,1,2,3};
		
		BogoSort now=new BogoSort();
		System.out.print("Unsorted: ");
		now.display1D(arr);
		
		now.bogo(arr);
		
		System.out.print("Sorted: ");
		now.display1D(arr);
	}
	void bogo(int[] arr)
	{
		
		int shuffle=1;
		for(;!isSorted(arr);shuffle++)
			shuffle(arr);
		
		System.out.println("This took "+shuffle+" shuffles.");
	}
	void shuffle(int[] arr)
	{
		
		int i=arr.length-1;
		while(i>0)
			swap(arr,i--,(int)(Math.random()*i));
	}
	void swap(int[] arr,int i,int j)
	{
		int temp=arr[i];
		arr[i]=arr[j];
		arr[j]=temp;
	}
	boolean isSorted(int[] arr)
	{

		for(int i=1;i<arr.length;i++)
			if(arr[i]<arr[i-1])
				return false;
		return true;
	}
	void display1D(int[] arr)
	{
		for(int i=0;i<arr.length;i++)
			System.out.print(arr[i]+" ");
		System.out.println();
	}

}
Task: Euler method


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

typedef double F(double,double);


void euler(F f, double y0, double a, double b, double h)
{
    double y = y0;
    for (double t = a; t < b; t += h)
    {
        std::cout << std::fixed << std::setprecision(3) << t << " " << y << "\n";
        y += h * f(t, y);
    }
    std::cout << "done\n";
}


double newtonCoolingLaw(double, double t)
{
    return -0.07 * (t - 20);
}

int main()
{
    euler(newtonCoolingLaw, 100, 0, 100,  2);
    euler(newtonCoolingLaw, 100, 0, 100,  5);
    euler(newtonCoolingLaw, 100, 0, 100, 10);
}




Java: public class Euler {
  private static void euler (Callable f, double y0, int a, int b, int h) {
    int t = a;
    double y = y0;
    while (t < b) {
      System.out.println ("" + t + " " + y);
      t += h;
      y += h * f.compute (t, y);
    }
    System.out.println ("DONE");
  }

  public static void main (String[] args) {
    Callable cooling = new Cooling ();
    int[] steps = {2, 5, 10};
    for (int stepSize : steps) {
      System.out.println ("Step size: " + stepSize);
      euler (cooling, 100.0, 0, 100, stepSize);
    }
  }
}


interface Callable {
  public double compute (int time, double t);
}


class Cooling implements Callable {
  public double compute (int time, double t) {
    return -0.07 * (t - 20);
  }
}
Task: Sequence of non-squares


C++: #include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <boost/bind.hpp>
#include <iterator>

double nextNumber( double number ) {
   return number + floor( 0.5 + sqrt( number ) ) ;
}

int main( ) {
   std::vector<double> non_squares ;
   typedef std::vector<double>::iterator SVI ;
   non_squares.reserve( 1000000 ) ;   
   
   for ( double i = 1.0 ; i < 100001.0 ; i += 1 )
      non_squares.push_back( nextNumber( i ) ) ;  
   
   std::copy( non_squares.begin( ) , non_squares.begin( ) + 22 ,
	 std::ostream_iterator<double>(std::cout, " " ) ) ;     
   std::cout << '\n' ;
   
   SVI found = std::find_if ( non_squares.begin( ) , non_squares.end( ) ,
	 boost::bind( &floor, boost::bind( &sqrt, _1 ) ) == boost::bind( &sqrt, _1 ) ) ;
   if ( found != non_squares.end( ) ) {
      std::cout << "Found a square number in the sequence!\n" ;
      std::cout << "It is " << *found << " !\n" ;
   }
   else {
      std::cout << "Up to 1000000, found no square number in the sequence!\n" ;
   }
   return 0 ;
}




Java: public class SeqNonSquares {
    public static int nonsqr(int n) {
        return n + (int)Math.round(Math.sqrt(n));
    }
    
    public static void main(String[] args) {
        
        for (int i = 1; i < 23; i++)
            System.out.print(nonsqr(i) + " ");
        System.out.println();
        
        
        for (int i = 1; i < 1000000; i++) {
            double j = Math.sqrt(nonsqr(i));
            assert j != Math.floor(j);
        }
    }
}
Task: Substring


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

int main()
{
  std::string s = "0123456789";

  int const n = 3;
  int const m = 4;
  char const c = '2';
  std::string const sub = "456";

  std::cout << s.substr(n, m)<< "\n";
  std::cout << s.substr(n) << "\n";
  std::cout << s.substr(0, s.size()-1) << "\n";
  std::cout << s.substr(s.find(c), m) << "\n";
  std::cout << s.substr(s.find(sub), m) << "\n";
}




Java: public static String Substring(String str, int n, int m){
    return str.substring(n, n+m);
}
public static String Substring(String str, int n){
    return str.substring(n);
}
public static String Substring(String str){
    return str.substring(0, str.length()-1);
}
public static String Substring(String str, char c, int m){
    return str.substring(str.indexOf(c), str.indexOf(c)+m+1);
}
public static String Substring(String str, String sub, int m){
    return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);
}
Task: JortSort


C++: #include <algorithm>
#include <string>
#include <iostream>
#include <iterator> 

class jortSort {
public:
    template<class T>
    bool jort_sort( T* o, size_t s ) {
        T* n = copy_array( o, s );
        sort_array( n, s );
        bool r = false;

        if( n ) {
            r = check( o, n, s );
            delete [] n;
        }
        return r;
    }

private:
    template<class T>
    T* copy_array( T* o, size_t s ) {
        T* z = new T[s];
        memcpy( z, o, s * sizeof( T ) );
        
        return z;
    }
    template<class T>
    void sort_array( T* n, size_t s ) {
        std::sort( n, n + s );
    }
    template<class T>
    bool check( T* n, T* o, size_t s ) {
        for( size_t x = 0; x < s; x++ )
            if( n[x] != o[x] ) return false;
        return true;
    }
};

jortSort js;

template<class T>
void displayTest( T* o, size_t s ) {
    std::copy( o, o + s, std::ostream_iterator<T>( std::cout, " " ) );
    std::cout << ": -> The array is " << ( js.jort_sort( o, s ) ? "sorted!" : "not sorted!" ) << "\n\n";
}

int main( int argc, char* argv[] ) {
    const size_t s = 5;
    std::string oStr[] = { "5", "A", "D", "R", "S" };
    displayTest( oStr, s );
    std::swap( oStr[0], oStr[1] );
    displayTest( oStr, s );

    int oInt[] = { 1, 2, 3, 4, 5 };
    displayTest( oInt, s );
    std::swap( oInt[0], oInt[1] );
    displayTest( oInt, s );

    return 0;
}




Java: public class JortSort {
    public static void main(String[] args) {
        System.out.println(jortSort(new int[]{1, 2, 3}));
    }

    static boolean jortSort(int[] arr) {
        return true;
    }
}
Task: Leap year


C++: #include <iostream>

bool is_leap_year(int year) {
  return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}

int main() {
  for (auto year : {1900, 1994, 1996, 1997, 2000}) {
    std::cout << year << (is_leap_year(year) ? " is" : " is not") << " a leap year.\n";
  }
}




Java: import java.util.GregorianCalendar;
import java.text.MessageFormat;

public class Leapyear{
        public static void main(String[] argv){
                int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};
                GregorianCalendar cal = new GregorianCalendar();
                for(int year : yrs){
                        System.err.println(MessageFormat.format("The year {0,number,#} is leaper: {1} / {2}.",
                                                                 year, cal.isLeapYear(year), isLeapYear(year)));
                }

        }
        public static boolean isLeapYear(int year){
                return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);
        }
}
Task: Combinations and permutations


C++: #include <boost/multiprecision/gmp.hpp>
#include <iostream>

using namespace boost::multiprecision;

mpz_int p(uint n, uint p) {
    mpz_int r = 1;
    mpz_int k = n - p;
    while (n > k)
        r *= n--;
    return r;
}

mpz_int c(uint n, uint k) {
    mpz_int r = p(n, k);
    while (k)
        r /= k--;
    return r;
}

int main() {
    for (uint i = 1u; i < 12u; i++)
        std::cout << "P(12," << i << ") = " << p(12u, i) << std::endl;
    for (uint i = 10u; i < 60u; i += 10u)
        std::cout << "C(60," << i << ") = " << c(60u, i) << std::endl;

    return 0;
}




Java: import java.math.BigInteger;

public class CombinationsAndPermutations {

    public static void main(String[] args) {
        System.out.println(Double.MAX_VALUE);
        System.out.println("A sample of permutations from 1 to 12 with exact Integer arithmetic:");
        for ( int n = 1 ; n <= 12 ; n++ ) {
            int k = n / 2;
            System.out.printf("%d P %d = %s%n", n, k, permutation(n, k));
        }

        System.out.println();
        System.out.println("A sample of combinations from 10 to 60 with exact Integer arithmetic:");
        for ( int n = 10 ; n <= 60 ; n += 5 ) {
            int k = n / 2;
            System.out.printf("%d C %d = %s%n", n, k, combination(n, k));
        }
        
        System.out.println();
        System.out.println("A sample of permutations from 5 to 15000 displayed in floating point arithmetic:");
        System.out.printf("%d P %d = %s%n", 5, 2, display(permutation(5, 2), 50));
        for ( int n = 1000 ; n <= 15000 ; n += 1000 ) {
            int k = n / 2;
            System.out.printf("%d P %d = %s%n", n, k, display(permutation(n, k), 50));
        }
        
        System.out.println();
        System.out.println("A sample of combinations from 100 to 1000 displayed in floating point arithmetic:");
        for ( int n = 100 ; n <= 1000 ; n += 100 ) {
            int k = n / 2;
            System.out.printf("%d C %d = %s%n", n, k, display(combination(n, k), 50));
        }

    }
    
    private static String display(BigInteger val, int precision) {
        String s = val.toString();
        precision = Math.min(precision, s.length());
        StringBuilder sb = new StringBuilder();
        sb.append(s.substring(0, 1));
        sb.append(".");
        sb.append(s.substring(1, precision));
        sb.append(" * 10^");
        sb.append(s.length()-1);
        return sb.toString();
    }
    
    public static BigInteger combination(int n, int k) {
        
        
        if ( n-k < k ) {
            k = n-k;
        }
        BigInteger result = permutation(n, k);
        while ( k > 0 ) {
            result = result.divide(BigInteger.valueOf(k));
            k--;
        }
        return result;
    }
    
    public static BigInteger permutation(int n, int k) {
        BigInteger result = BigInteger.ONE;
        for ( int i = n ; i >= n-k+1 ; i-- ) {
            result = result.multiply(BigInteger.valueOf(i));
        }
        return result;
    }
    
}
Task: Sort numbers lexicographically


C++: #include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>

void lexicographical_sort(std::vector<int>& numbers) {
    std::vector<std::string> strings(numbers.size());
    std::transform(numbers.begin(), numbers.end(), strings.begin(),
                   [](int i) { return std::to_string(i); });
    std::sort(strings.begin(), strings.end());
    std::transform(strings.begin(), strings.end(), numbers.begin(),
                   [](const std::string& s) { return std::stoi(s); });
}

std::vector<int> lexicographically_sorted_vector(int n) {
    std::vector<int> numbers(n >= 1 ? n : 2 - n);
    std::iota(numbers.begin(), numbers.end(), std::min(1, n));
    lexicographical_sort(numbers);
    return numbers;
}

template <typename T>
void print_vector(std::ostream& out, const std::vector<T>& v) {
    out << '[';
    if (!v.empty()) {
        auto i = v.begin();
        out << *i++;
        for (; i != v.end(); ++i)
            out << ',' << *i;
    }
    out << "]\n";
}

int main(int argc, char** argv) {
    for (int i : { 0, 5, 13, 21, -22 }) {
        std::cout << i << ": ";
        print_vector(std::cout, lexicographically_sorted_vector(i));
    }
    return 0;
}




Java: import java.util.List;
import java.util.stream.*;

public class LexicographicalNumbers {

    static List<Integer> lexOrder(int n) {
        int first = 1, last = n;
        if (n < 1) {
            first = n;
            last = 1;
        }
        return IntStream.rangeClosed(first, last)
                        .mapToObj(Integer::toString)
                        .sorted()
                        .map(Integer::valueOf)
                        .collect(Collectors.toList());
    }

    public static void main(String[] args) {
        System.out.println("In lexicographical order:\n");
        int[] ints = {0, 5, 13, 21, -22};
        for (int n : ints) {
           System.out.printf("%3d: %s\n", n, lexOrder(n));
        }
    }
}