WeixiangYan/CodeTransOcean huggingface dataset:
Task: Range extraction


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

template<typename InIter>
 void extract_ranges(InIter begin, InIter end, std::ostream& os)
{
  if (begin == end)
    return;

  int current = *begin++;
  os << current;
  int count = 1;

  while (begin != end)
  {
    int next = *begin++;
    if (next == current+1)
      ++count;
    else
    {
      if (count > 2)
        os << '-';
      else
        os << ',';
      if (count > 1)
        os << current << ',';
      os << next;
      count = 1;
    }
    current = next;
  }

  if (count > 1)
    os << (count > 2? '-' : ',') << current;
}

template<typename T, std::size_t n>
 T* end(T (&array)[n])
{
  return array+n;
}

int main()
{
  int data[] = { 0,  1,  2,  4,  6,  7,  8, 11, 12, 14,
                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
                 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
                 37, 38, 39 };

  extract_ranges(data, end(data), std::cout);
  std::cout << std::endl;
}






Python: def range_extract(lst):
    'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'
    lenlst = len(lst)
    i = 0
    while i< lenlst:
        low = lst[i]
        while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1
        hi = lst[i]
        if   hi - low >= 2:
            yield (low, hi)
        elif hi - low == 1:
            yield (low,)
            yield (hi,)
        else:
            yield (low,)
        i += 1

def printr(ranges):
    print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)
                     for r in ranges ) )

if __name__ == '__main__':
    for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,
                 8, 9, 10, 11, 14, 15, 17, 18, 19, 20],
                [0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22,
                 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39]]:
        
        printr(range_extract(lst))
Task: Maximum triangle path sum


C++: 
#include <iostream>

int main( int argc, char* argv[] )
{
    int triangle[] = 
    {
	55,
	94, 48,
	95, 30, 96,
	77, 71, 26, 67,
	97, 13, 76, 38, 45,
	7, 36, 79, 16, 37, 68,
	48, 7, 9, 18, 70, 26, 6,
	18, 72, 79, 46, 59, 79, 29, 90,
	20, 76, 87, 11, 32, 7, 7, 49, 18,
	27, 83, 58, 35, 71, 11, 25, 57, 29, 85,
	14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,
	2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,
	92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,
	56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,
	44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,
	85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,
	6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,
	27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93
    };

    const int size = sizeof( triangle ) / sizeof( int );
    const int tn = static_cast<int>(sqrt(2.0 * size));
    assert(tn * (tn + 1) == 2 * size);    

    
    for (int n = tn - 1; n > 0; --n)   
        for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) 
            triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]);

    std::cout << "Maximum total: " << triangle[0] << "\n\n";
}






Python: fun maxpathsum(t): 
    let a = val t
    for i in a.length-1..-1..1, c in linearindices a[r]:
        a[r, c] += max(a[r+1, c], a[r=1, c+1])
    return a[1, 1]

let test = [
    [55],
    [94, 48],
    [95, 30, 96],
    [77, 71, 26, 67],
    [97, 13, 76, 38, 45],
    [07, 36, 79, 16, 37, 68],
    [48, 07, 09, 18, 70, 26, 06],
    [18, 72, 79, 46, 59, 79, 29, 90],
    [20, 76, 87, 11, 32, 07, 07, 49, 18],
    [27, 83, 58, 35, 71, 11, 25, 57, 29, 85],
    [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55],
    [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23],
    [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42],
    [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72],
    [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36],
    [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52],
    [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15],
    [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]
]

@print maxpathsum test
Task: Variable declaration reset


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

int main()
{
  constexpr std::array s {1,2,2,3,4,4,5};

  if(!s.empty())
  {
    int previousValue = s[0];

    for(size_t i = 1; i < s.size(); ++i)
    {
      
      const int currentValue = s[i];

      if(i > 0 && previousValue == currentValue)
      {
        std::cout << i << "\n";
      }

      previousValue = currentValue;
    }
  }
}






Python: s = [1, 2, 2, 3, 4, 4, 5]
 
for i in range(len(s)):
    curr = s[i]
    if i > 0 and curr == prev:
        print(i)
    prev = curr
Task: Numbers with equal rises and falls


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

bool equal_rises_and_falls(int n) {
    int total = 0;
    for (int previous_digit = -1; n > 0; n /= 10) {
        int digit = n % 10;
        if (previous_digit > digit)
            ++total;
        else if (previous_digit >= 0 && previous_digit < digit)
            --total;
        previous_digit = digit;
    }
    return total == 0;
}

int main() {
    const int limit1 = 200;
    const int limit2 = 10000000;
    int n = 0;
    std::cout << "The first " << limit1 << " numbers in the sequence are:\n";
    for (int count = 0; count < limit2; ) {
        if (equal_rises_and_falls(++n)) {
            ++count;
            if (count <= limit1)
                std::cout << std::setw(3) << n << (count % 20 == 0 ? '\n' : ' ');
        }
    }
    std::cout << "\nThe " << limit2 << "th number in the sequence is " << n << ".\n";
}






Python: import itertools

def riseEqFall(num):
    
    height = 0
    d1 = num % 10
    num //= 10
    while num:
        d2 = num % 10
        height += (d1<d2) - (d1>d2)
        d1 = d2
        num //= 10
    return height == 0
    
def sequence(start, fn):
    
    num=start-1
    while True:
        num += 1
        while not fn(num): num += 1
        yield num

a296712 = sequence(1, riseEqFall)


print("The first 200 numbers are:")
print(*itertools.islice(a296712, 200))


print("The 10,000,000th number is:")
print(*itertools.islice(a296712, 10000000-200-1, 10000000-200))
Task: Koch curve


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

constexpr double sqrt3_2 = 0.86602540378444; 

struct point {
    double x;
    double y;
};

std::vector<point> koch_next(const std::vector<point>& points) {
    size_t size = points.size();
    std::vector<point> output(4*(size - 1) + 1);
    double x0, y0, x1, y1;
    size_t j = 0;
    for (size_t i = 0; i + 1 < size; ++i) {
        x0 = points[i].x;
        y0 = points[i].y;
        x1 = points[i + 1].x;
        y1 = points[i + 1].y;
        double dy = y1 - y0;
        double dx = x1 - x0;
        output[j++] = {x0, y0};
        output[j++] = {x0 + dx/3, y0 + dy/3};
        output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};
        output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};
    }
    output[j] = {x1, y1};
    return output;
}

std::vector<point> koch_points(int size, int iterations) {
    double length = size * sqrt3_2 * 0.95;
    double x = (size - length)/2;
    double y = size/2 - length * sqrt3_2/3;
    std::vector<point> points{
        {x, y},
        {x + length/2, y + length * sqrt3_2},
        {x + length, y},
        {x, y}
    };
    for (int i = 0; i < iterations; ++i)
        points = koch_next(points);
    return points;
}

void koch_curve_svg(std::ostream& out, int size, int iterations) {
    out << "<svg xmlns='http:
        << size << "' height='" << size << "'>\n";
    out << "<rect width='100%' height='100%' fill='black'/>\n";
    out << "<path stroke-width='1' stroke='white' fill='none' d='";
    auto points(koch_points(size, iterations));
    for (size_t i = 0, n = points.size(); i < n; ++i)
        out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n';
    out << "z'/>\n</svg>\n";
}

int main() {
    std::ofstream out("koch_curve.svg");
    if (!out) {
        std::cerr << "Cannot open output file\n";
        return EXIT_FAILURE;
    }
    koch_curve_svg(out, 600, 5);
    return EXIT_SUCCESS;
}






Python: l = 300

def setup():
    size(400, 400)
    background(0, 0, 255)
    stroke(255)
    
    translate(width / 2.0, height / 2.0)
    
    translate(-l / 2.0, l * sqrt(3) / 6.0)
    for i in range(4):
        kcurve(0, l)
        rotate(radians(120))
        translate(-l, 0)


def kcurve(x1, x2):
    s = (x2 - x1) / 3.0
    if s < 5:
        pushMatrix()
        translate(x1, 0)
        line(0, 0, s, 0)
        line(2 * s, 0, 3 * s, 0)
        translate(s, 0)
        rotate(radians(60))
        line(0, 0, s, 0)
        translate(s, 0)
        rotate(radians(-120))
        line(0, 0, s, 0)
        popMatrix()
        return

    pushMatrix()
    translate(x1, 0)
    kcurve(0, s)
    kcurve(2 * s, 3 * s)
    translate(s, 0)
    rotate(radians(60))
    kcurve(0, s)
    translate(s, 0)
    rotate(radians(-120))
    kcurve(0, s)
    popMatrix()
Task: Words from neighbour ones


C++: #include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

int main(int argc, char** argv) {
    const int min_length = 9;
    const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
    std::ifstream in(filename);
    if (!in) {
        std::cerr << "Cannot open file '" << filename << "'.\n";
        return EXIT_FAILURE;
    }
    std::string line;
    std::vector<std::string> words;
    while (getline(in, line)) {
        if (line.size() >= min_length)
            words.push_back(line);
    }
    std::sort(words.begin(), words.end());
    std::string previous_word;
    int count = 0;
    for (size_t i = 0, n = words.size(); i + min_length <= n; ++i) {
        std::string word;
        word.reserve(min_length);
        for (size_t j = 0; j < min_length; ++j)
            word += words[i + j][j];
        if (previous_word == word)
            continue;
        auto w = std::lower_bound(words.begin(), words.end(), word);
        if (w != words.end() && *w == word)
            std::cout << std::setw(2) << ++count << ". " << word << '\n';
        previous_word = word;
    }
    return EXIT_SUCCESS;
}






Python: 

import urllib.request
from collections import Counter
 
urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt")
 
dictionary = open("unixdict.txt","r")
 
wordList = dictionary.read().split('\n')
 
dictionary.close()
 
filteredWords = [chosenWord for chosenWord in wordList if len(chosenWord)>=9]

for word in filteredWords[:-9]:
  position = filteredWords.index(word)
  newWord = "".join([filteredWords[position+i][i] for i in range(0,9)])
  if newWord in filteredWords:
   print(newWord)
Task: Generate Chess960 starting position


C++: #include <iostream>
#include <string>
#include <time.h>
using namespace std;

namespace
{
    void placeRandomly(char* p, char c)
    {
	int loc = rand() % 8;
	if (!p[loc])
	    p[loc] = c;
	else
	    placeRandomly(p, c);    
    }
    int placeFirst(char* p, char c, int loc = 0)
    {
	while (p[loc]) ++loc;
	p[loc] = c;
        return loc;
    }

    string startPos()
    {
	char p[8]; memset( p, 0, 8 );

	
	p[2 * (rand() % 4)] = 'B';
	p[2 * (rand() % 4) + 1] = 'B';

	
	for (char c : "QNN")
	    placeRandomly(p, c);

	
	placeFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R')));

	return string(p, 8);
    }
}   

namespace chess960
{
    void generate( int c )
    {
	for( int x = 0; x < c; x++ )
	    cout << startPos() << "\n";
    }
}

int main( int argc, char* argv[] )
{
    srand( time( NULL ) );
    chess960::generate( 10 );
    cout << "\n\n";
    return system( "pause" );
}






Python: >>> from itertools import permutations
>>> pieces = 'KQRrBbNN'
>>> starts = {''.join(p).upper() for p in permutations(pieces)
                     if p.index('B') % 2 != p.index('b') % 2 		
                     and ( p.index('r') < p.index('K') < p.index('R')	
                           or p.index('R') < p.index('K') < p.index('r') ) }
>>> len(starts)
960
>>> starts.pop()
'QNBRNKRB'
>>>
Task: Modulinos


C++: int meaning_of_life();






Python: 



def meaning_of_life():
  return 42

if __name__ == "__main__":
  print("Main: The meaning of life is %s" % meaning_of_life())
Task: File size distribution


C++: #include <algorithm>
#include <array>
#include <filesystem>
#include <iomanip>
#include <iostream>

void file_size_distribution(const std::filesystem::path& directory) {
    constexpr size_t n = 9;
    constexpr std::array<std::uintmax_t, n> sizes = { 0, 1000, 10000,
        100000, 1000000, 10000000, 100000000, 1000000000, 10000000000 };
    std::array<size_t, n + 1> count = { 0 };
    size_t files = 0;
    std::uintmax_t total_size = 0;
    std::filesystem::recursive_directory_iterator iter(directory);
    for (const auto& dir_entry : iter) {
        if (dir_entry.is_regular_file() && !dir_entry.is_symlink()) {
            std::uintmax_t file_size = dir_entry.file_size();
            total_size += file_size;
            auto i = std::lower_bound(sizes.begin(), sizes.end(), file_size);
            size_t index = std::distance(sizes.begin(), i);
            ++count[index];
            ++files;
        }
    }
    std::cout << "File size distribution for " << directory << ":\n";
    for (size_t i = 0; i <= n; ++i) {
        if (i == n)
            std::cout << "> " << sizes[i - 1];
        else
            std::cout << std::setw(16) << sizes[i];
        std::cout << " bytes: " << count[i] << '\n';
    }
    std::cout << "Number of files: " << files << '\n';
    std::cout << "Total file size: " << total_size << " bytes\n";
}

int main(int argc, char** argv) {
    std::cout.imbue(std::locale(""));
    try {
        const char* directory(argc > 1 ? argv[1] : ".");
        std::filesystem::path path(directory);
        if (!is_directory(path)) {
            std::cerr << directory << " is not a directory.\n";
            return EXIT_FAILURE;
        }
        file_size_distribution(path);
    } catch (const std::exception& ex) {
        std::cerr << ex.what() << '\n';
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}






Python: import sys, os
from collections import Counter

def dodir(path):
    global h

    for name in os.listdir(path):
        p = os.path.join(path, name)

        if os.path.islink(p):
            pass
        elif os.path.isfile(p):
            h[os.stat(p).st_size] += 1
        elif os.path.isdir(p):
            dodir(p)
        else:
            pass

def main(arg):
    global h
    h = Counter()
    for dir in arg:
        dodir(dir)

    s = n = 0
    for k, v in sorted(h.items()):
        print("Size %d -> %d file(s)" % (k, v))
        n += v
        s += k * v
    print("Total %d bytes for %d files" % (s, n))

main(sys.argv[1:])
Task: Unix_ls


C++: #include <iostream>
#include <set>
#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

int main(void)
{
    fs::path p(fs::current_path());
    std::set<std::string> tree;

    for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it)
        tree.insert(it->path().filename().native());

    for (auto entry : tree)
        std::cout << entry << '\n';
}






Python: >>> import os
>>> print('\n'.join(sorted(os.listdir('.'))))
DLLs
Doc
LICENSE.txt
Lib
NEWS.txt
README.txt
Scripts
Tools
include
libs
python.exe
pythonw.exe
tcl
>>>
Task: Magic squares of doubly even order


C++: #include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;

class magicSqr
{
public: 
    magicSqr( int d ) {
        while( d % 4 > 0 ) { d++; }
        sz = d;
        sqr = new int[sz * sz];
        fillSqr();
    }
    ~magicSqr() { delete [] sqr; }

    void display() const {
        cout << "Doubly Even Magic Square: " << sz << " x " << sz << "\n";
        cout << "It's Magic Sum is: " << magicNumber() << "\n\n";
        ostringstream cvr; cvr << sz * sz;
        int l = cvr.str().size();
 
        for( int y = 0; y < sz; y++ ) {
            int yy = y * sz;
            for( int x = 0; x < sz; x++ ) {
                cout << setw( l + 2 ) << sqr[yy + x];
            }
            cout << "\n";
        }
        cout << "\n\n";
    }
private:
    void fillSqr() {
        static const bool tempAll[4][4] = {{ 1, 0, 0, 1 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 }, { 1, 0, 0, 1 } };
        int i = 0;
        for( int curRow = 0; curRow < sz; curRow++ ) {
            for( int curCol = 0; curCol < sz; curCol++ ) {
                sqr[curCol + sz * curRow] = tempAll[curRow % 4][curCol % 4] ? i + 1 : sz * sz - i;
                i++;
            }
        }
    }
    int magicNumber() const { return sz * ( ( sz * sz ) + 1 ) / 2; }
 
    int* sqr;
    int sz;
};
 
int main( int argc, char* argv[] ) {
    magicSqr s( 8 );
    s.display();
    return 0;
}






Python: def MagicSquareDoublyEven(order):
    sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]
    n1 = order/4
    for r in range(n1):
        r1 = sq[r][n1:-n1]
        r2 = sq[order -r - 1][n1:-n1]
        r1.reverse()
        r2.reverse()
        sq[r][n1:-n1] = r2
        sq[order -r - 1][n1:-n1] = r1
    for r in range(n1, order-n1):
        r1 = sq[r][:n1]
        r2 = sq[order -r - 1][order-n1:]
        r1.reverse()
        r2.reverse()
        sq[r][:n1] = r2
        sq[order -r - 1][order-n1:] = r1
    return sq

def printsq(s):
    n = len(s)
    bl = len(str(n**2))+1
    for i in range(n):
        print ''.join( [ ("%"+str(bl)+"s")%(str(x)) for x in s[i]] )
    print "\nMagic constant = %d"%sum(s[0])

printsq(MagicSquareDoublyEven(8))
Task: Pseudo-random numbers_Xorshift star


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

class XorShiftStar {
private:
    const uint64_t MAGIC = 0x2545F4914F6CDD1D;
    uint64_t state;
public:
    void seed(uint64_t num) {
        state = num;
    }

    uint32_t next_int() {
        uint64_t x;
        uint32_t answer;

        x = state;
        x = x ^ (x >> 12);
        x = x ^ (x << 25);
        x = x ^ (x >> 27);
        state = x;
        answer = ((x * MAGIC) >> 32);

        return answer;
    }

    float next_float() {
        return (float)next_int() / (1LL << 32);
    }
};

int main() {
    auto rng = new XorShiftStar();
    rng->seed(1234567);
    std::cout << rng->next_int() << '\n';
    std::cout << rng->next_int() << '\n';
    std::cout << rng->next_int() << '\n';
    std::cout << rng->next_int() << '\n';
    std::cout << rng->next_int() << '\n';
    std::cout << '\n';

    std::array<int, 5> counts = { 0, 0, 0, 0, 0 };
    rng->seed(987654321);
    for (int i = 0; i < 100000; i++) {
        int j = (int)floor(rng->next_float() * 5.0);
        counts[j]++;
    }
    for (size_t i = 0; i < counts.size(); i++) {
        std::cout << i << ": " << counts[i] << '\n';
    }

    return 0;
}






Python: mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
const = 0x2545F4914F6CDD1D



class Xorshift_star():
    
    def __init__(self, seed=0):
        self.state = seed & mask64

    def seed(self, num):
        self.state =  num & mask64
    
    def next_int(self):
        "return random int between 0 and 2**32"
        x = self.state
        x = (x ^ (x >> 12)) & mask64
        x = (x ^ (x << 25)) & mask64
        x = (x ^ (x >> 27)) & mask64
        self.state = x
        answer = (((x * const) & mask64) >> 32) & mask32 
        return answer
    
    def  next_float(self):
        "return random float between 0 and 1"
        return self.next_int() / (1 << 32)
    

if __name__ == '__main__':
    random_gen = Xorshift_star()
    random_gen.seed(1234567)
    for i in range(5):
        print(random_gen.next_int())
        
    random_gen.seed(987654321)
    hist = {i:0 for i in range(5)}
    for i in range(100_000):
        hist[int(random_gen.next_float() *5)] += 1
    print(hist)
Task: Numbers with same digit set in base 10 and base 16


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

const int LIMIT = 100000;

std::bitset<16> digitset(int num, int base) {
    std::bitset<16> set;
    for (; num; num /= base) set.set(num % base);
    return set;
}

int main() {
    int c = 0;
    for (int i=0; i<LIMIT; i++) {
        if (digitset(i,10) == digitset(i,16)) {
            std::cout << std::setw(7) << i;
            if (++c % 10 == 0) std::cout << std::endl;
        }
    }
    std::cout << std::endl;
    return 0;
}






Python: col = 0
for i in range(100000):
    if set(str(i)) == set(hex(i)[2:]):
        col += 1
        print("{:7}".format(i), end='\n'[:col % 10 == 0])
print()
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' : ' ');
    }
}






Python: def lpd(n):
    for i in range(n-1,0,-1):
        if n%i==0: return i
    return 1

for i in range(1,101):
    print("{:3}".format(lpd(i)), end=i%10==0 and '\n' or '')
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;
}






Python: from __future__ import print_function
from string import ascii_lowercase

SYMBOLTABLE = list(ascii_lowercase)

def move2front_encode(strng, symboltable):
    sequence, pad = [], symboltable[::]
    for char in strng:
        indx = pad.index(char)
        sequence.append(indx)
        pad = [pad.pop(indx)] + pad
    return sequence

def move2front_decode(sequence, symboltable):
    chars, pad = [], symboltable[::]
    for indx in sequence:
        char = pad[indx]
        chars.append(char)
        pad = [pad.pop(indx)] + pad
    return ''.join(chars)

if __name__ == '__main__':
    for s in ['broood', 'bananaaa', 'hiphophiphop']:
        encode = move2front_encode(s, SYMBOLTABLE)
        print('%14r encodes to %r' % (s, encode), end=', ')
        decode = move2front_decode(encode, SYMBOLTABLE)
        print('which decodes back to %r' % decode)
        assert s == decode, 'Whoops!'