WeixiangYan/CodeTransOcean huggingface dataset:
Task: Largest proper divisor of n


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

int largest_proper_divisor(int n) {
    assert(n > 0);
    if ((n & 1) == 0)
        return n >> 1;
    for (int p = 3; p * p <= n; p += 2) {
        if (n % p == 0)
            return n / p;
    }
    return 1;
}

int main() {
    for (int n = 1; n < 101; ++n) {
        std::cout << std::setw(2) << largest_proper_divisor(n)
            << (n % 10 == 0 ? '\n' : ' ');
    }
}



Go: package main

import "fmt"

func largestProperDivisor(n int) int {
    for i := 2; i*i <= n; i++ {
        if n%i == 0 {
            return n / i
        }
    }
    return 1
}

func main() {
    fmt.Println("The largest proper divisors for numbers in the interval [1, 100] are:")
    fmt.Print(" 1  ")
    for n := 2; n <= 100; n++ {
        if n%2 == 0 {
            fmt.Printf("%2d  ", n/2)
        } else {
            fmt.Printf("%2d  ", largestProperDivisor(n))
        }
        if n%10 == 0 {
            fmt.Println()
        }
    }
}
Task: Move-to-front algorithm


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

using namespace std;

class MTF
{
public:
    string encode( string str )
    {
	fillSymbolTable();
	vector<int> output;
	for( string::iterator it = str.begin(); it != str.end(); it++ )
	{
	    for( int i = 0; i < 26; i++ )
	    {
		if( *it == symbolTable[i] )
		{
		    output.push_back( i );
		    moveToFront( i );
		    break;
		}
	    }
	}
	string r;
	for( vector<int>::iterator it = output.begin(); it != output.end(); it++ )
	{
	    ostringstream ss;
	    ss << *it;
	    r += ss.str() + " ";
	}
	return r;
    }

    string decode( string str )
    {
	fillSymbolTable();
	istringstream iss( str ); vector<int> output;
	copy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );
	string r;
	for( vector<int>::iterator it = output.begin(); it != output.end(); it++ )
	{
	    r.append( 1, symbolTable[*it] );
	    moveToFront( *it );
	}
	return r;
    }

private:
    void moveToFront( int i )
    {
	char t = symbolTable[i];
	for( int z = i - 1; z >= 0; z-- )
	    symbolTable[z + 1] = symbolTable[z];

        symbolTable[0] = t;
    }

    void fillSymbolTable()
    {
        for( int x = 0; x < 26; x++ )
	    symbolTable[x] = x + 'a';
    }

    char symbolTable[26];
};

int main()
{
    MTF mtf;
    string a, str[] = { "broood", "bananaaa", "hiphophiphop" };
    for( int x = 0; x < 3; x++ )
    {
        a = str[x];
        cout << a << " -> encoded = ";
        a = mtf.encode( a );
        cout << a << "; decoded = " << mtf.decode( a ) << endl;
    }
    return 0;
}



Go: package main

import (
	"bytes"
	"fmt"
)

type symbolTable string

func (symbols symbolTable) encode(s string) []byte {
	seq := make([]byte, len(s))
	pad := []byte(symbols)
	for i, c := range []byte(s) {
		x := bytes.IndexByte(pad, c)
		seq[i] = byte(x)
		copy(pad[1:], pad[:x])
		pad[0] = c
	}
	return seq
}

func (symbols symbolTable) decode(seq []byte) string {
	chars := make([]byte, len(seq))
	pad := []byte(symbols)
	for i, x := range seq {
		c := pad[x]
		chars[i] = c
		copy(pad[1:], pad[:x])
		pad[0] = c
	}
	return string(chars)
}

func main() {
	m := symbolTable("abcdefghijklmnopqrstuvwxyz")
	for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} {
		enc := m.encode(s)
		dec := m.decode(enc)
		fmt.Println(s, enc, dec)
		if dec != s {
			panic("Whoops!")
		}
	}
}
Task: Sum of first n cubes


C++: #include <array>
#include <cstdio>
#include <numeric>

void PrintContainer(const auto& vec)
{
    int count = 0;
    for(auto value : vec)
    {
        printf("%7d%c", value, ++count % 10 == 0 ? '\n' : ' ');
    }
}

int main()
{
    
    auto cube = [](auto x){return x * x * x;};

    
    std::array<int, 50> a;
    std::iota(a.begin(), a.end(), 0);

    
    
    
    std::transform_inclusive_scan(a.begin(), a.end(), a.begin(), std::plus{}, cube);
    PrintContainer(a);    
}



Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    fmt.Println("Cumulative sums of the first 50 cubes:")
    sum := 0
    for n := 0; n < 50; n++ {
        sum += n * n * n
        fmt.Printf("%9s ", rcu.Commatize(sum))
        if n%10 == 9 {
            fmt.Println()
        }
    }
    fmt.Println()
Task: Execute a system command


C++: system("pause");



Go: package main

import (
    "log"
    "os"
    "os/exec"
)

func main() {
    cmd := exec.Command("ls", "-l")
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    if err := cmd.Run(); err != nil {
        log.Fatal(err)
    }
}
Task: Longest increasing subsequence


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

template <typename T>
struct Node {
    T value;
    Node* prev_node;
};

template <typename Container>
Container lis(const Container& values) {
    using E = typename Container::value_type;
    using NodePtr = Node<E>*;
    using ConstNodePtr = const NodePtr;

    std::vector<NodePtr> pileTops;
    std::vector<Node<E>> nodes(values.size());

    
    auto cur_node = std::begin(nodes);
    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)
    {
        auto node = &*cur_node;
        node->value = *cur_value;

        
        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,
            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });

        if (lb != pileTops.begin())
            node->prev_node = *std::prev(lb);

        if (lb == pileTops.end())
            pileTops.push_back(node);
        else
            *lb = node;
    }

    
    
    Container result(pileTops.size());
    auto r = std::rbegin(result);

    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)
        *r = node->value;

    return result;
}

template <typename Container>
void show_lis(const Container& values)
{
    auto&& result = lis(values);
    for (auto& r : result) {
        std::cout << r << ' ';
    }
    std::cout << std::endl;
}

int main() 
{
    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });
    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });
}



Go: package main

import (
  "fmt"
  "sort"
)

type Node struct {
    val int
    back *Node
}

func lis (n []int) (result []int) {
  var pileTops []*Node
  
  for _, x := range n {
    j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })
    node := &Node{ x, nil }
    if j != 0 { node.back = pileTops[j-1] }
    if j != len(pileTops) {
      pileTops[j] = node
    } else {
      pileTops = append(pileTops, node)
    }
  }

  if len(pileTops) == 0 { return []int{} }
  for node := pileTops[len(pileTops)-1]; node != nil; node = node.back {
    result = append(result, node.val)
  }
  
  for i := 0; i < len(result)/2; i++ {
    result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i]
  }
  return
}

func main() {
    for _, d := range [][]int{{3, 2, 6, 4, 5, 1},
            {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}} {
        fmt.Printf("an L.I.S. of %v is %v\n", d, lis(d))
    }
}
Task: Superpermutation minimisation


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

constexpr int MAX = 12;

static std::vector<char> sp;
static std::array<int, MAX> count;
static int pos = 0;

int factSum(int n) {
    int s = 0;
    int x = 0;
    int f = 1;
    while (x < n) {
        f *= ++x;
        s += f;
    }
    return s;
}

bool r(int n) {
    if (n == 0) {
        return false;
    }
    char c = sp[pos - n];
    if (--count[n] == 0) {
        count[n] = n;
        if (!r(n - 1)) {
            return false;
        }
    }
    sp[pos++] = c;
    return true;
}

void superPerm(int n) {
    pos = n;
    int len = factSum(n);
    if (len > 0) {
        sp.resize(len);
    }
    for (size_t i = 0; i <= n; i++) {
        count[i] = i;
    }
    for (size_t i = 1; i <= n; i++) {
        sp[i - 1] = '0' + i;
    }
    while (r(n)) {}
}

int main() {
    for (size_t n = 0; n < MAX; n++) {
        superPerm(n);
        std::cout << "superPerm(" << n << ") len = " << sp.size() << '\n';
    }

    return 0;
}



Go: package main

import "fmt"

const max = 12

var (
    super []byte
    pos   int
    cnt   [max]int
)


func factSum(n int) int {
    s := 0
    for x, f := 0, 1; x < n; {
        x++
        f *= x
        s += f
    }
    return s
}

func r(n int) bool {
    if n == 0 {
        return false
    }
    c := super[pos-n]
    cnt[n]--
    if cnt[n] == 0 {
        cnt[n] = n
        if !r(n - 1) {
            return false
        }
    }
    super[pos] = c
    pos++
    return true
}

func superperm(n int) {
    pos = n
    le := factSum(n)
    super = make([]byte, le)
    for i := 0; i <= n; i++ {
        cnt[i] = i
    }
    for i := 1; i <= n; i++ {
        super[i-1] = byte(i) + '0'
    }

    for r(n) {
    }
}

func main() {
    for n := 0; n < max; n++ {
        fmt.Printf("superperm(%2d) ", n)
        superperm(n)
        fmt.Printf("len = %d\n", len(super))
    }
}
Task: GUI component interaction


C++: #ifndef INTERACTION_H
#define INTERACTION_H
#include <QWidget>

class QPushButton ;
class QLineEdit ;
class QVBoxLayout ;
class MyWidget : public QWidget {
   Q_OBJECT 

public :
   MyWidget( QWidget *parent = 0 ) ;
private :
   QLineEdit *entryField ;
   QPushButton *increaseButton ;
   QPushButton *randomButton ;
   QVBoxLayout *myLayout ;
private slots :
   void doIncrement( ) ;
   void findRandomNumber( ) ;
} ;
#endif



Go: package main

import (
    "github.com/gotk3/gotk3/gtk"
    "log"
    "math/rand"
    "strconv"
    "time"
)

func validateInput(window *gtk.Window, str string) (int64, bool) {
    i, err := strconv.ParseInt(str, 10, 64)
    if err != nil {
        dialog := gtk.MessageDialogNew(
            window,
            gtk.DIALOG_MODAL,
            gtk.MESSAGE_ERROR,
            gtk.BUTTONS_OK,
            "Invalid value",
        )
        dialog.Run()
        dialog.Destroy()
        return 0, false
    }
    return i, true
}

func check(err error, msg string) {
    if err != nil {
        log.Fatal(msg, err)
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    gtk.Init(nil)

    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
    check(err, "Unable to create window:")
    window.SetTitle("Rosetta Code")
    window.SetPosition(gtk.WIN_POS_CENTER)
    window.Connect("destroy", func() {
        gtk.MainQuit()
    })

    box, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
    check(err, "Unable to create box:")
    box.SetBorderWidth(1)

    label, err := gtk.LabelNew("Value:")
    check(err, "Unable to create label:")

    entry, err := gtk.EntryNew()
    check(err, "Unable to create entry:")
    entry.SetText("0") 
    entry.Connect("activate", func() {
        
        str, _ := entry.GetText()
        validateInput(window, str)
    })

    
    ib, err := gtk.ButtonNewWithLabel("Increment")
    check(err, "Unable to create increment button:")
    ib.Connect("clicked", func() {
        
        str, _ := entry.GetText()
        if i, ok := validateInput(window, str); ok {
            entry.SetText(strconv.FormatInt(i+1, 10))
        }
    })

    
    rb, err := gtk.ButtonNewWithLabel("Random")
    check(err, "Unable to create random button:")
    rb.Connect("clicked", func() {
        dialog := gtk.MessageDialogNew(
            window,
            gtk.DIALOG_MODAL,
            gtk.MESSAGE_QUESTION,
            gtk.BUTTONS_YES_NO,
            "Set random value",
        )
        answer := dialog.Run()
        dialog.Destroy()
        if answer == gtk.RESPONSE_YES {
            entry.SetText(strconv.Itoa(rand.Intn(10000)))
        }
    })

    box.PackStart(label, false, false, 2)
    box.PackStart(entry, false, false, 2)
    box.PackStart(ib, false, false, 2)
    box.PackStart(rb, false, false, 2)
    window.Add(box)

    window.ShowAll()
    gtk.Main()
}
Task: One of n lines in a file


C++: #include <random>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;

mt19937 engine; 

unsigned int one_of_n(unsigned int n) {
	unsigned int choice;
	for(unsigned int i = 0; i < n; ++i) {
		uniform_int_distribution<unsigned int> distribution(0, i);
		if(!distribution(engine))
			choice = i;
	}
	return choice;
}

int main() {
	engine = mt19937(random_device()()); 
	unsigned int results[10] = {0};
	for(unsigned int i = 0; i < 1000000; ++i)
		results[one_of_n(10)]++;
	ostream_iterator<unsigned int> out_it(cout, " ");
	copy(results, results+10, out_it);
	cout << '\n';
}



Go: package main

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







func choseLineRandomly(r io.Reader) (s string, ln int, err error) {
    br := bufio.NewReader(r)
    s, err = br.ReadString('\n')
    if err != nil {
        return
    }
    ln = 1
    lnLast := 1.
    var sLast string
    for {
        
        
        sLast, err = br.ReadString('\n')
        if err == io.EOF {
            return s, ln, nil 
        }
        if err != nil {
            break
        }
        lnLast++
        if rand.Float64() < 1/lnLast {
            s = sLast
            ln = int(lnLast)
        }
    }
    return 
}





func oneOfN(n int, file io.Reader) int {
    _, ln, err := choseLineRandomly(file)
    if err != nil {
        panic(err)
    }
    return ln
}


type simReader int

func (r *simReader) Read(b []byte) (int, error) {
    if *r <= 0 {
        return 0, io.EOF
    }
    b[0] = '\n'
    *r--
    return 1, nil
}

func main() {
    
    
    n := 10
    freq := make([]int, n)
    rand.Seed(time.Now().UnixNano())
    for times := 0; times < 1e6; times++ {
        sr := simReader(n)
        freq[oneOfN(n, &sr)-1]++
    }

    
    fmt.Println(freq)
}
Task: Summarize and say sequence


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

std::map<char, int> _map;
std::vector<std::string> _result;
size_t longest = 0;

void make_sequence( std::string n ) {
    _map.clear();
    for( std::string::iterator i = n.begin(); i != n.end(); i++ )
        _map.insert( std::make_pair( *i, _map[*i]++ ) );

    std::string z;
    for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) {
        char c = ( *i ).second + 48;
        z.append( 1, c );
        z.append( 1, i->first );
    }

    if( longest <= z.length() ) {
        longest = z.length();
        if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) {
            _result.push_back( z );
            make_sequence( z );
        }
    }
}
int main( int argc, char* argv[] ) {
    std::vector<std::string> tests;
    tests.push_back( "9900" ); tests.push_back( "9090" ); tests.push_back( "9009" );
    for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) {
        make_sequence( *i );
        std::cout  << "[" << *i << "] Iterations: " << _result.size() + 1 << "\n";
        for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) {
            std::cout << *j << "\n";
        }
        std::cout << "\n\n";
    }
    return 0;
}



Go: package main

import (
    "fmt"
    "strconv"
)

func main() {
    var maxLen int
    var seqMaxLen [][]string
    for n := 1; n < 1e6; n++ {
        switch s := seq(n); {
        case len(s) == maxLen:
            seqMaxLen = append(seqMaxLen, s)
        case len(s) > maxLen:
            maxLen = len(s)
            seqMaxLen = [][]string{s}
        }
    }
    fmt.Println("Max sequence length:", maxLen)
    fmt.Println("Sequences:", len(seqMaxLen))
    for _, seq := range seqMaxLen {
        fmt.Println("Sequence:")
        for _, t := range seq {
            fmt.Println(t)
        }
    }
}

func seq(n int) []string {
    s := strconv.Itoa(n)
    ss := []string{s}

    for {
        dSeq := sortD(s)
        d := dSeq[0]
        nd := 1
        s = ""
        for i := 1; ; i++ {
            if i == len(dSeq) {
                s = fmt.Sprintf("%s%d%c", s, nd, d)
                break
            }
            if dSeq[i] == d {
                nd++
            } else {
                s = fmt.Sprintf("%s%d%c", s, nd, d)
                d = dSeq[i]
                nd = 1
            }
        }
        for _, s0 := range ss {
            if s == s0 {
                return ss
            }
        }
        ss = append(ss, s)
    }
    panic("unreachable")
}

func sortD(s string) []rune {
    r := make([]rune, len(s))
    for i, d := range s {
        j := 0
        for ; j < i; j++ {
            if d > r[j] {
                copy(r[j+1:], r[j:i])
                break
            }
        }
        r[j] = d
    }
    return r
}
Task: Self-describing numbers


C++: #include <iostream>
 

typedef unsigned long long bigint;
 

using namespace std;
 

class sdn
{
public:
    bool check( bigint n )
    {
	int cc = digitsCount( n );
	return compare( n, cc );
    }
 
    void displayAll( bigint s )
    {
	for( bigint y = 1; y < s; y++ )
	    if( check( y ) )
		cout << y << " is a Self-Describing Number." << endl;
    }
 
private:
    bool compare( bigint n, int cc )
    {
	bigint a;
	while( cc )
	{
	    cc--; a = n % 10;
	    if( dig[cc] != a ) return false;
	    n -= a; n /= 10;
	}
	return true;
    }
 
    int digitsCount( bigint n )
    {
	int cc = 0; bigint a;
	memset( dig, 0, sizeof( dig ) );
	while( n )
	{
	    a = n % 10; dig[a]++;
	    cc++ ; n -= a; n /= 10;
	}
	return cc;
    }
 
    int dig[10];
};

int main( int argc, char* argv[] )
{
    sdn s;
    s. displayAll( 1000000000000 );
    cout << endl << endl; system( "pause" );
 
    bigint n;
    while( true )
    {
	system( "cls" );
	cout << "Enter a positive whole number ( 0 to QUIT ): "; cin >> n;
	if( !n ) return 0;
	if( s.check( n ) ) cout << n << " is";
	else cout << n << " is NOT";
	cout << " a Self-Describing Number!" << endl << endl;
	system( "pause" );
    }
 
    return 0;
}



Go: package main

import (
    "fmt"
    "strconv"
    "strings"
)


func sdn(n int64) bool {
    if n >= 1e10 {
        return false
    }
    s := strconv.FormatInt(n, 10)
    for d, p := range s {
        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {
            return false
        }
    }
    return true
}


func main() {
    for n := int64(0); n < 1e10; n++ {
        if sdn(n) {
            fmt.Println(n)
        }
    }
}
Task: Numeric separator syntax


C++: 

#include <iostream>
using namespace std;

int main()
{
    long long int a = 30'00'000;

    std::cout <<"And with the ' in C++ 14 : "<< a << endl;

    return 0;
}



Go: package main

import "fmt"

func main() {
    integers := []int{1_2_3, 0b1_0_1_0_1, 0xa_bc_d, 0o4_37, 0_43_7, 0x_beef}
    for _, integer := range integers {
        fmt.Printf("%d  ", integer)
    }
    floats := []float64{1_2_3_4.2_5, 6.0_22e4, 0x_1.5p-2}
    for _, float := range floats {
        fmt.Printf("%g  ", float)
    }
    fmt.Println()
    
    
}
Task: Repeat


C++: template <typename Function>
void repeat(Function f, unsigned int n) {
 for(unsigned int i=n; 0<i; i--)
  f();
}



Go: package main

import "fmt"

func repeat(n int, f func()) {
  for i := 0; i < n; i++ {
    f()
  }
}

func fn() {
  fmt.Println("Example")
}

func main() {
  repeat(4, fn)
}
Task: Modular inverse


C++: #include <iostream>
 
int mul_inv(int a, int b)
{
	int b0 = b, t, q;
	int x0 = 0, x1 = 1;
	if (b == 1) return 1;
	while (a > 1) {
		q = a / b;
		t = b, b = a % b, a = t;
		t = x0, x0 = x1 - q * x0, x1 = t;
	}
	if (x1 < 0) x1 += b0;
	return x1;
}
 
int main(void) {
	std::cout << mul_inv(42, 2017) << std::endl;
	return 0;
}



Go: package main

import (
	"fmt"
	"math/big"
)

func main() {
	a := big.NewInt(42)
	m := big.NewInt(2017)
	k := new(big.Int).ModInverse(a, m)
	fmt.Println(k)
}
Task: Sunflower fractal


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

bool sunflower(const char* filename) {
    std::ofstream out(filename);
    if (!out)
        return false;

    constexpr int size = 600;
    constexpr int seeds = 5 * size;
    constexpr double pi = 3.14159265359;
    constexpr double phi = 1.61803398875;
    
    out << "<svg xmlns='http:
    out << "' height='" << size << "' style='stroke:gold'>\n";
    out << "<rect width='100%' height='100%' fill='black'/>\n";
    out << std::setprecision(2) << std::fixed;
    for (int i = 1; i <= seeds; ++i) {
        double r = 2 * std::pow(i, phi)/seeds;
        double theta = 2 * pi * phi * i;
        double x = r * std::sin(theta) + size/2;
        double y = r * std::cos(theta) + size/2;
        double radius = std::sqrt(i)/13;
        out << "<circle cx='" << x << "' cy='" << y << "' r='" << radius << "'/>\n";
    }
    out << "</svg>\n";
    return true;
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        std::cerr << "usage: " << argv[0] << " filename\n";
        return EXIT_FAILURE;
    }
    if (!sunflower(argv[1])) {
        std::cerr << "image generation failed\n";
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}



Go: package main

import (
    "github.com/fogleman/gg"
    "math"
)

func main() {
    dc := gg.NewContext(400, 400)
    dc.SetRGB(1, 1, 1)
    dc.Clear()
    dc.SetRGB(0, 0, 1)
    c := (math.Sqrt(5) + 1) / 2
    numberOfSeeds := 3000
    for i := 0; i <= numberOfSeeds; i++ {
        fi := float64(i)
        fn := float64(numberOfSeeds)
        r := math.Pow(fi, c) / fn
        angle := 2 * math.Pi * c * fi
        x := r*math.Sin(angle) + 200
        y := r*math.Cos(angle) + 200
        fi /= fn / 5
        dc.DrawCircle(x, y, fi)
    }
    dc.SetLineWidth(1)
    dc.Stroke()
    dc.SavePNG("sunflower_fractal.png")
}
Task: Permutations by swapping


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

using namespace std;

vector<int> UpTo(int n, int offset = 0)
{
	vector<int> retval(n);
	for (int ii = 0; ii < n; ++ii)
		retval[ii] = ii + offset;
	return retval;
}

struct JohnsonTrotterState_
{
	vector<int> values_;
	vector<int> positions_;	
	vector<bool> directions_;
	int sign_;

	JohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {}

	int LargestMobile() const	
	{
		for (int r = values_.size(); r > 0; --r)
		{
			const int loc = positions_[r] + (directions_[r] ? 1 : -1);
			if (loc >= 0 && loc < values_.size() && values_[loc] < r)
				return r;
		}
		return 0;
	}

	bool IsComplete() const { return LargestMobile() == 0; }

	void operator++()	
	{
		const int r = LargestMobile();
		const int rLoc = positions_[r];
		const int lLoc = rLoc + (directions_[r] ? 1 : -1);
		const int l = values_[lLoc];
		
		swap(values_[lLoc], values_[rLoc]);
		swap(positions_[l], positions_[r]);
		sign_ = -sign_;
		
		for (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd)
			*pd = !*pd;
	}
};

int main(void)
{
	JohnsonTrotterState_ state(4);
	do
	{
		for (auto v : state.values_)
			cout << v << " ";
		cout << "\n";
		++state;
	} while (!state.IsComplete());
}



Go: package permute




func Iter(p []int) func() int {
    f := pf(len(p))
    return func() int {
        return f(p)
    }
}



func pf(n int) func([]int) int {
    sign := 1
    switch n {
    case 0, 1:
        return func([]int) (s int) {
            s = sign
            sign = 0
            return
        }
    default:
        p0 := pf(n - 1)
        i := n
        var d int
        return func(p []int) int {
            switch {
            case sign == 0:
            case i == n:
                i--
                sign = p0(p[:i])
                d = -1
            case i == 0:
                i++
                sign *= p0(p[1:])
                d = 1
                if sign == 0 {
                    p[0], p[1] = p[1], p[0]
                }
            default:
                p[i], p[i-1] = p[i-1], p[i]
                sign = -sign
                i += d
            }
            return sign
        }
    }
}