WeixiangYan/CodeTransOcean huggingface dataset:
Task: Substitution cipher





Java: public class SubstitutionCipher {

    final static String key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N"
            + "[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ";

    static String text = "Here we have to do is there will be a input/source "
            + "file in which we are going to Encrypt the file by replacing every "
            + "upper/lower case alphabets of the source file with another "
            + "predetermined upper/lower case alphabets or symbols and save "
            + "it into another output/encrypted file and then again convert "
            + "that output/encrypted file into original/decrypted file. This "
            + "type of Encryption/Decryption scheme is often called a "
            + "Substitution Cipher.";

    public static void main(String[] args) {
        String enc = encode(text);
        System.out.println("Encoded: " + enc);
        System.out.println("\nDecoded: " + decode(enc));
    }

    static String encode(String s) {
        StringBuilder sb = new StringBuilder(s.length());

        for (char c : s.toCharArray())
            sb.append(key.charAt((int) c - 32));

        return sb.toString();
    }

    static String decode(String s) {
        StringBuilder sb = new StringBuilder(s.length());

        for (char c : s.toCharArray())
            sb.append((char) (key.indexOf((int) c) + 32));

        return sb.toString();
    }
}




VB: option explicit
const maxk=94
dim key(94) 

a="I
" Please accept this time-limited open invite to RC

sub gen     
  dim i,m,t
  for i=0 to ubound(key)
    key(i)=i+32
  next
  for i=0 to ubound(key)-1
    if key(i)=i+32 then
      m=i+int(rnd*(maxk-i)) 
     if key(m)=m+32 then 
       t=key(m):key(m)=key(i):key(i)=t
     end if
   end if
  next
end sub

function viewkey
dim i,b
b=""
for i=1 to ubound(key)
   b=b&chr(key(i))
next
viewkey=b
end function 

function iif(a,b,c) if a then iif=b else iif =c end if: end function

function docode(a)
  dim b,i,ch,n
  n=maxk+32
  b=""
  for i=1 to len(a)
   ch=asc(mid(a,i,1))
   
   b=b&chr(key(iif (ch>n or ch<32,0,ch-32)))
  next
  docode=b
end function  

randomize timer
dim a,b,c
gen
wscript.echo "Key:   " & viewkey & vbcrlf
wscript.echo "Original: " & a & Vbcrlf
b=docode(a)
wscript.echo "Encoded: "&  b & Vbcrlf
c=docode(b)
wscript.echo "Decoded: " & c & Vbcrlf
wscript.quit(0)
Task: Substitution cipher

C: #include<stdlib.h>
#include<stdio.h>
#include<wchar.h>

#define ENCRYPT 0
#define DECRYPT 1
#define ALPHA 33
#define OMEGA 126

int wideStrLen(wchar_t* str){
	int i = 0;
	while(str[i++]!=00);
	
	return i;
}

void processFile(char* fileName,char plainKey, char cipherKey,int flag){
	
	FILE* inpFile = fopen(fileName,"r");
	FILE* outFile;
	
	int i,len, diff = (flag==ENCRYPT)?(int)cipherKey - (int)plainKey:(int)plainKey - (int)cipherKey;
	wchar_t str[1000], *outStr;
	char* outFileName = (char*)malloc((strlen(fileName)+5)*sizeof(char));

	sprintf(outFileName,"%s_%s",fileName,(flag==ENCRYPT)?"ENC":"DEC");
	
	outFile = fopen(outFileName,"w");
	
	while(fgetws(str,1000,inpFile)!=NULL){
		len = wideStrLen(str);
		
		outStr = (wchar_t*)malloc((len + 1)*sizeof(wchar_t));
		
		for(i=0;i<len;i++){
			if((int)str[i]>=ALPHA && (int)str[i]<=OMEGA && flag == ENCRYPT)
				outStr[i] = (wchar_t)((int)str[i]+diff);
			 else if((int)str[i]-diff>=ALPHA && (int)str[i]-diff<=OMEGA && flag == DECRYPT)
				outStr[i] = (wchar_t)((int)str[i]-diff);
			else
				outStr[i] = str[i];
		}
		outStr[i]=str[i];
		
		fputws(outStr,outFile);
		
		free(outStr);
	}
	
	fclose(inpFile);
	fclose(outFile);
}

int main(int argC,char* argV[]){
	if(argC!=5)
		printf("Usage : %s <file name, plain key, cipher key, action (E)ncrypt or (D)ecrypt>",argV[0]);
	else{
		processFile(argV[1],argV[2][0],argV[3][0],(argV[4][0]=='E'||argV[4][0]=='e')?ENCRYPT:DECRYPT);
		
		printf("File %s_%s has been written to the same location as input file.",argV[1],(argV[4][0]=='E'||argV[4][0]=='e')?"ENC":"DEC");
	}
	
	return 0;
}






PHP: <?php

$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$key      = 'cPYJpjsBlaOEwRbVZIhQnHDWxMXiCtUToLkFrzdAGymKvgNufeSq';

file_put_contents('output.txt', strtr(file_get_contents('input.txt'), $alphabet, $key));

$source  = file_get_contents('input.txt');
$encoded = file_get_contents('output.txt');
$decoded = strtr($encoded, $key, $alphabet);

echo
    '== SOURCE ==', PHP_EOL,
    $source, PHP_EOL, PHP_EOL,
    '== ENCODED ==', PHP_EOL,
    $encoded, PHP_EOL, PHP_EOL,
    '== DECODED ==', PHP_EOL,
    $decoded, PHP_EOL, PHP_EOL;
Task: Substitution cipher


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

class cipher {
public:
    bool work( std::string e, std::string f, std::string k ) {
        if( e.length() < 1 ) return false;
        fileBuffer = readFile( f );
        if( "" == fileBuffer ) return false;
        keyBuffer = readFile( k );
        if( "" == keyBuffer ) return false;

        outName = f;
        outName.insert( outName.find_first_of( "." ), "_out" );

        switch( e[0] ) {
            case 'e': return encode();
            case 'd': return decode();
        }
        return false;
    }
private:
    bool encode() {
        size_t idx, len = keyBuffer.length() >> 1;
        for( std::string::iterator i = fileBuffer.begin(); i != fileBuffer.end(); i++ ) {
            idx = keyBuffer.find_first_of( *i );
            if( idx < len ) outBuffer.append( 1, keyBuffer.at( idx + len ) );
            else outBuffer.append( 1, *i );
        }
        return saveOutput();
    }
    bool decode() {
        size_t idx, l = keyBuffer.length(), len = l >> 1;
        for( std::string::iterator i = fileBuffer.begin(); i != fileBuffer.end(); i++ ) {
            idx = keyBuffer.find_last_of( *i );
            if( idx >= len && idx < l ) outBuffer.append( 1, keyBuffer.at( idx - len ) );
            else outBuffer.append( 1, *i );
        }
        return saveOutput();
    }
    bool saveOutput() {
        std::ofstream o( outName.c_str() );
        o.write( outBuffer.c_str(), outBuffer.size() );
        o.close();
        return true;
    }
    std::string readFile( std::string fl ) {
        std::string buffer = "";
        std::ifstream f( fl.c_str(), std::ios_base::in );
        if( f.good() ) {
            buffer = std::string( ( std::istreambuf_iterator<char>( f ) ), std::istreambuf_iterator<char>() );
            f.close();
        }
        return buffer;
    }
    std::string fileBuffer, keyBuffer, outBuffer, outName;
};

int main( int argc, char* argv[] ) {
    if( argc < 4 ) {
        std::cout << "<d or e>\tDecrypt or Encrypt\n<filename>\tInput file, the output file will have"
        "'_out' added to it.\n<key>\t\tfile with the key to encode/decode\n\n";
    } else {
        cipher c;
        if( c.work( argv[1], argv[2], argv[3] ) ) std::cout << "\nFile successfully saved!\n\n";
        else std::cout << "Something went wrong!\n\n";
    }
    return 0;
}





PHP: <?php

$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$key      = 'cPYJpjsBlaOEwRbVZIhQnHDWxMXiCtUToLkFrzdAGymKvgNufeSq';

file_put_contents('output.txt', strtr(file_get_contents('input.txt'), $alphabet, $key));

$source  = file_get_contents('input.txt');
$encoded = file_get_contents('output.txt');
$decoded = strtr($encoded, $key, $alphabet);

echo
    '== SOURCE ==', PHP_EOL,
    $source, PHP_EOL, PHP_EOL,
    '== ENCODED ==', PHP_EOL,
    $encoded, PHP_EOL, PHP_EOL,
    '== DECODED ==', PHP_EOL,
    $decoded, PHP_EOL, PHP_EOL;
Task: Substitution cipher




Go: package main

import (    
    "fmt"
    "strings"
)

var key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ"

func encode(s string) string {
    bs := []byte(s)
    for i := 0; i < len(bs); i++ {
        bs[i] = key[int(bs[i]) - 32]
    }
    return string(bs)
}

func decode(s string) string {
    bs := []byte(s)
    for i := 0; i < len(bs); i++ {
        bs[i] = byte(strings.IndexByte(key, bs[i]) + 32)
    }
    return string(bs)
}

func main() {
    s := "The quick brown fox jumps over the lazy dog, who barks VERY loudly!"
    enc := encode(s)
    fmt.Println("Encoded: ", enc)
    fmt.Println("Decoded: ", decode(enc))
}



PHP: <?php

$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$key      = 'cPYJpjsBlaOEwRbVZIhQnHDWxMXiCtUToLkFrzdAGymKvgNufeSq';

file_put_contents('output.txt', strtr(file_get_contents('input.txt'), $alphabet, $key));

$source  = file_get_contents('input.txt');
$encoded = file_get_contents('output.txt');
$decoded = strtr($encoded, $key, $alphabet);

echo
    '== SOURCE ==', PHP_EOL,
    $source, PHP_EOL, PHP_EOL,
    '== ENCODED ==', PHP_EOL,
    $encoded, PHP_EOL, PHP_EOL,
    '== DECODED ==', PHP_EOL,
    $decoded, PHP_EOL, PHP_EOL;
Task: Substitution cipher





Java: public class SubstitutionCipher {

    final static String key = "]kYV}(!7P$n5_0i R:?jOWtF/=-pe'AD&@r6%ZXs\"v*N"
            + "[#wSl9zq2^+g;LoB`aGh{3.HIu4fbK)mU8|dMET><,Qc\\C1yxJ";

    static String text = "Here we have to do is there will be a input/source "
            + "file in which we are going to Encrypt the file by replacing every "
            + "upper/lower case alphabets of the source file with another "
            + "predetermined upper/lower case alphabets or symbols and save "
            + "it into another output/encrypted file and then again convert "
            + "that output/encrypted file into original/decrypted file. This "
            + "type of Encryption/Decryption scheme is often called a "
            + "Substitution Cipher.";

    public static void main(String[] args) {
        String enc = encode(text);
        System.out.println("Encoded: " + enc);
        System.out.println("\nDecoded: " + decode(enc));
    }

    static String encode(String s) {
        StringBuilder sb = new StringBuilder(s.length());

        for (char c : s.toCharArray())
            sb.append(key.charAt((int) c - 32));

        return sb.toString();
    }

    static String decode(String s) {
        StringBuilder sb = new StringBuilder(s.length());

        for (char c : s.toCharArray())
            sb.append((char) (key.indexOf((int) c) + 32));

        return sb.toString();
    }
}


PHP: <?php

$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$key      = 'cPYJpjsBlaOEwRbVZIhQnHDWxMXiCtUToLkFrzdAGymKvgNufeSq';

file_put_contents('output.txt', strtr(file_get_contents('input.txt'), $alphabet, $key));

$source  = file_get_contents('input.txt');
$encoded = file_get_contents('output.txt');
$decoded = strtr($encoded, $key, $alphabet);

echo
    '== SOURCE ==', PHP_EOL,
    $source, PHP_EOL, PHP_EOL,
    '== ENCODED ==', PHP_EOL,
    $encoded, PHP_EOL, PHP_EOL,
    '== DECODED ==', PHP_EOL,
    $decoded, PHP_EOL, PHP_EOL;
Task: Substitution cipher






PHP: <?php

$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$key      = 'cPYJpjsBlaOEwRbVZIhQnHDWxMXiCtUToLkFrzdAGymKvgNufeSq';

file_put_contents('output.txt', strtr(file_get_contents('input.txt'), $alphabet, $key));

$source  = file_get_contents('input.txt');
$encoded = file_get_contents('output.txt');
$decoded = strtr($encoded, $key, $alphabet);

echo
    '== SOURCE ==', PHP_EOL,
    $source, PHP_EOL, PHP_EOL,
    '== ENCODED ==', PHP_EOL,
    $encoded, PHP_EOL, PHP_EOL,
    '== DECODED ==', PHP_EOL,
    $decoded, PHP_EOL, PHP_EOL;


Python: from string import printable
import random

EXAMPLE_KEY = ''.join(sorted(printable, key=lambda _:random.random()))

def encode(plaintext, key):
    return ''.join(key[printable.index(char)] for char in plaintext)

def decode(plaintext, key):
    return ''.join(printable[key.index(char)] for char in plaintext)

original = "A simple example."
encoded = encode(original, EXAMPLE_KEY)
decoded = decode(encoded, EXAMPLE_KEY)
print(.format(
    original, EXAMPLE_KEY, encoded, decoded))
Task: Substitution cipher






PHP: <?php

$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$key      = 'cPYJpjsBlaOEwRbVZIhQnHDWxMXiCtUToLkFrzdAGymKvgNufeSq';

file_put_contents('output.txt', strtr(file_get_contents('input.txt'), $alphabet, $key));

$source  = file_get_contents('input.txt');
$encoded = file_get_contents('output.txt');
$decoded = strtr($encoded, $key, $alphabet);

echo
    '== SOURCE ==', PHP_EOL,
    $source, PHP_EOL, PHP_EOL,
    '== ENCODED ==', PHP_EOL,
    $encoded, PHP_EOL, PHP_EOL,
    '== DECODED ==', PHP_EOL,
    $decoded, PHP_EOL, PHP_EOL;



VB: option explicit
const maxk=94
dim key(94) 

a="I
" Please accept this time-limited open invite to RC

sub gen     
  dim i,m,t
  for i=0 to ubound(key)
    key(i)=i+32
  next
  for i=0 to ubound(key)-1
    if key(i)=i+32 then
      m=i+int(rnd*(maxk-i)) 
     if key(m)=m+32 then 
       t=key(m):key(m)=key(i):key(i)=t
     end if
   end if
  next
end sub

function viewkey
dim i,b
b=""
for i=1 to ubound(key)
   b=b&chr(key(i))
next
viewkey=b
end function 

function iif(a,b,c) if a then iif=b else iif =c end if: end function

function docode(a)
  dim b,i,ch,n
  n=maxk+32
  b=""
  for i=1 to len(a)
   ch=asc(mid(a,i,1))
   
   b=b&chr(key(iif (ch>n or ch<32,0,ch-32)))
  next
  docode=b
end function  

randomize timer
dim a,b,c
gen
wscript.echo "Key:   " & viewkey & vbcrlf
wscript.echo "Original: " & a & Vbcrlf
b=docode(a)
wscript.echo "Encoded: "&  b & Vbcrlf
c=docode(b)
wscript.echo "Decoded: " & c & Vbcrlf
wscript.quit(0)
Task: Next highest int from digits

C: #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

void swap(char* str, int i, int j) {
    char c = str[i];
    str[i] = str[j];
    str[j] = c;
}

void reverse(char* str, int i, int j) {
    for (; i < j; ++i, --j)
        swap(str, i, j);
}

bool next_permutation(char* str) {
    int len = strlen(str);
    if (len < 2)
        return false;
    for (int i = len - 1; i > 0; ) {
        int j = i, k;
        if (str[--i] < str[j]) {
            k = len;
            while (str[i] >= str[--k]) {}
            swap(str, i, k);
            reverse(str, j, len - 1);
            return true;
        }
    }
    return false;
}

uint32_t next_highest_int(uint32_t n) {
    char str[16];
    snprintf(str, sizeof(str), "%u", n);
    if (!next_permutation(str))
        return 0;
    return strtoul(str, 0, 10);
}

int main() {
    uint32_t numbers[] = {0, 9, 12, 21, 12453, 738440, 45072010, 95322020};
    const int count = sizeof(numbers)/sizeof(int);
    for (int i = 0; i < count; ++i)
        printf("%d -> %d\n", numbers[i], next_highest_int(numbers[i]));
    
    const char big[] = "9589776899767587796600";
    char next[sizeof(big)];
    memcpy(next, big, sizeof(big));
    next_permutation(next);
    printf("%s -> %s\n", big, next);
    return 0;
}


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

#include <gmpxx.h>

using integer = mpz_class;

std::string to_string(const integer& n) {
    std::ostringstream out;
    out << n;
    return out.str();
}

integer next_highest(const integer& n) {
    std::string str(to_string(n));
    if (!std::next_permutation(str.begin(), str.end()))
        return 0;
    return integer(str);
}

int main() {
    for (integer n : {0, 9, 12, 21, 12453, 738440, 45072010, 95322020})
        std::cout << n << " -> " << next_highest(n) << '\n';
    integer big("9589776899767587796600");
    std::cout << big << " -> " << next_highest(big) << '\n';
    return 0;
}
Task: Next highest int from digits

C: #include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

void swap(char* str, int i, int j) {
    char c = str[i];
    str[i] = str[j];
    str[j] = c;
}

void reverse(char* str, int i, int j) {
    for (; i < j; ++i, --j)
        swap(str, i, j);
}

bool next_permutation(char* str) {
    int len = strlen(str);
    if (len < 2)
        return false;
    for (int i = len - 1; i > 0; ) {
        int j = i, k;
        if (str[--i] < str[j]) {
            k = len;
            while (str[i] >= str[--k]) {}
            swap(str, i, k);
            reverse(str, j, len - 1);
            return true;
        }
    }
    return false;
}

uint32_t next_highest_int(uint32_t n) {
    char str[16];
    snprintf(str, sizeof(str), "%u", n);
    if (!next_permutation(str))
        return 0;
    return strtoul(str, 0, 10);
}

int main() {
    uint32_t numbers[] = {0, 9, 12, 21, 12453, 738440, 45072010, 95322020};
    const int count = sizeof(numbers)/sizeof(int);
    for (int i = 0; i < count; ++i)
        printf("%d -> %d\n", numbers[i], next_highest_int(numbers[i]));
    
    const char big[] = "9589776899767587796600";
    char next[sizeof(big)];
    memcpy(next, big, sizeof(big));
    next_permutation(next);
    printf("%s -> %s\n", big, next);
    return 0;
}







Python: def closest_more_than(n, lst):
    "(index of) closest int from lst, to n that is also > n"
    large = max(lst) + 1
    return lst.index(min(lst, key=lambda x: (large if x <= n else x)))

def nexthigh(n):
    "Return nxt highest number from n's digits using scan & re-order"
    assert n == int(abs(n)), "n >= 0"
    this = list(int(digit) for digit in str(int(n)))[::-1]
    mx = this[0]
    for i, digit in enumerate(this[1:], 1):
        if digit < mx:
            mx_index = closest_more_than(digit, this[:i + 1])
            this[mx_index], this[i] = this[i], this[mx_index]
            this[:i] = sorted(this[:i], reverse=True)
            return int(''.join(str(d) for d in this[::-1]))
        elif digit > mx:
            mx, mx_index = digit, i
    return 0


if __name__ == '__main__':
    for x in [0, 9, 12, 21, 12453, 738440, 45072010, 95322020,
              9589776899767587796600]:
        print(f"{x:>12_d} -> {nexthigh(x):>12_d}")
Task: Next highest int from digits


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

#include <gmpxx.h>

using integer = mpz_class;

std::string to_string(const integer& n) {
    std::ostringstream out;
    out << n;
    return out.str();
}

integer next_highest(const integer& n) {
    std::string str(to_string(n));
    if (!std::next_permutation(str.begin(), str.end()))
        return 0;
    return integer(str);
}

int main() {
    for (integer n : {0, 9, 12, 21, 12453, 738440, 45072010, 95322020})
        std::cout << n << " -> " << next_highest(n) << '\n';
    integer big("9589776899767587796600");
    std::cout << big << " -> " << next_highest(big) << '\n';
    return 0;
}






Python: def closest_more_than(n, lst):
    "(index of) closest int from lst, to n that is also > n"
    large = max(lst) + 1
    return lst.index(min(lst, key=lambda x: (large if x <= n else x)))

def nexthigh(n):
    "Return nxt highest number from n's digits using scan & re-order"
    assert n == int(abs(n)), "n >= 0"
    this = list(int(digit) for digit in str(int(n)))[::-1]
    mx = this[0]
    for i, digit in enumerate(this[1:], 1):
        if digit < mx:
            mx_index = closest_more_than(digit, this[:i + 1])
            this[mx_index], this[i] = this[i], this[mx_index]
            this[:i] = sorted(this[:i], reverse=True)
            return int(''.join(str(d) for d in this[::-1]))
        elif digit > mx:
            mx, mx_index = digit, i
    return 0


if __name__ == '__main__':
    for x in [0, 9, 12, 21, 12453, 738440, 45072010, 95322020,
              9589776899767587796600]:
        print(f"{x:>12_d} -> {nexthigh(x):>12_d}")
Task: Happy numbers

C: #include <stdio.h>

#define CACHE 256
enum { h_unknown = 0, h_yes, h_no };
unsigned char buf[CACHE] = {0, h_yes, 0};

int happy(int n)
{
	int sum = 0, x, nn;
	if (n < CACHE) {
		if (buf[n]) return 2 - buf[n];
		buf[n] = h_no;
	}

	for (nn = n; nn; nn /= 10) x = nn % 10, sum += x * x;

	x = happy(sum);
	if (n < CACHE) buf[n] = 2 - x;
	return x;
}

int main()
{
	int i, cnt = 8;
	for (i = 1; cnt || !printf("\n"); i++)
		if (happy(i)) --cnt, printf("%d ", i);

	printf("The %dth happy number: ", cnt = 1000000);
	for (i = 1; cnt; i++)
		if (happy(i)) --cnt || printf("%d\n", i);

	return 0;
}


C++: #include <map>
#include <set>

bool happy(int number) {
  static std::map<int, bool> cache;

  std::set<int> cycle;
  while (number != 1 && !cycle.count(number)) {
    if (cache.count(number)) {
      number = cache[number] ? 1 : 0;
      break;
    }
    cycle.insert(number);
    int newnumber = 0;
    while (number > 0) {
      int digit = number % 10;
      newnumber += digit * digit;
      number /= 10;
    }
    number = newnumber;
  }
  bool happiness = number == 1;
  for (std::set<int>::const_iterator it = cycle.begin();
       it != cycle.end(); it++)
    cache[*it] = happiness;
  return happiness;
}

#include <iostream>

int main() {
  for (int i = 1; i < 50; i++)
    if (happy(i))
      std::cout << i << std::endl;
  return 0;
}
Task: Happy numbers

C: #include <stdio.h>

#define CACHE 256
enum { h_unknown = 0, h_yes, h_no };
unsigned char buf[CACHE] = {0, h_yes, 0};

int happy(int n)
{
	int sum = 0, x, nn;
	if (n < CACHE) {
		if (buf[n]) return 2 - buf[n];
		buf[n] = h_no;
	}

	for (nn = n; nn; nn /= 10) x = nn % 10, sum += x * x;

	x = happy(sum);
	if (n < CACHE) buf[n] = 2 - x;
	return x;
}

int main()
{
	int i, cnt = 8;
	for (i = 1; cnt || !printf("\n"); i++)
		if (happy(i)) --cnt, printf("%d ", i);

	printf("The %dth happy number: ", cnt = 1000000);
	for (i = 1; cnt; i++)
		if (happy(i)) --cnt || printf("%d\n", i);

	return 0;
}




Go: package main

import "fmt"

func happy(n int) bool {
	m := make(map[int]bool)
	for n > 1 {
		m[n] = true
		var x int
		for x, n = n, 0; x > 0; x /= 10 {
			d := x % 10
			n += d * d
		}
		if m[n] {
			return false
		}
	}
	return true
}

func main() {
	for found, n := 0, 1; found < 8; n++ {
		if happy(n) {
			fmt.Print(n, " ")
			found++
		}
	}
	fmt.Println()
}
Task: Happy numbers

C: #include <stdio.h>

#define CACHE 256
enum { h_unknown = 0, h_yes, h_no };
unsigned char buf[CACHE] = {0, h_yes, 0};

int happy(int n)
{
	int sum = 0, x, nn;
	if (n < CACHE) {
		if (buf[n]) return 2 - buf[n];
		buf[n] = h_no;
	}

	for (nn = n; nn; nn /= 10) x = nn % 10, sum += x * x;

	x = happy(sum);
	if (n < CACHE) buf[n] = 2 - x;
	return x;
}

int main()
{
	int i, cnt = 8;
	for (i = 1; cnt || !printf("\n"); i++)
		if (happy(i)) --cnt, printf("%d ", i);

	printf("The %dth happy number: ", cnt = 1000000);
	for (i = 1; cnt; i++)
		if (happy(i)) --cnt || printf("%d\n", i);

	return 0;
}








VB: Option Explicit

Sub Test_Happy()
Dim i&, Cpt&

    For i = 1 To 100
        If Is_Happy_Number(i) Then
            Debug.Print "Is Happy : " & i
            Cpt = Cpt + 1
            If Cpt = 8 Then Exit For
        End If
    Next
End Sub

Public Function Is_Happy_Number(ByVal N As Long) As Boolean
Dim i&, Number$, Cpt&
    Is_Happy_Number = False 
    Do
        Cpt = Cpt + 1       
        Number = CStr(N)    
        N = 0
        For i = 1 To Len(Number)
            N = N + CInt(Mid(Number, i, 1)) ^ 2
        Next i
        
        If Cpt = 50 Then Exit Function
    Loop Until N = 1
    Is_Happy_Number = True
End Function
Task: Happy numbers


C++: #include <map>
#include <set>

bool happy(int number) {
  static std::map<int, bool> cache;

  std::set<int> cycle;
  while (number != 1 && !cycle.count(number)) {
    if (cache.count(number)) {
      number = cache[number] ? 1 : 0;
      break;
    }
    cycle.insert(number);
    int newnumber = 0;
    while (number > 0) {
      int digit = number % 10;
      newnumber += digit * digit;
      number /= 10;
    }
    number = newnumber;
  }
  bool happiness = number == 1;
  for (std::set<int>::const_iterator it = cycle.begin();
       it != cycle.end(); it++)
    cache[*it] = happiness;
  return happiness;
}

#include <iostream>

int main() {
  for (int i = 1; i < 50; i++)
    if (happy(i))
      std::cout << i << std::endl;
  return 0;
}



Go: package main

import "fmt"

func happy(n int) bool {
	m := make(map[int]bool)
	for n > 1 {
		m[n] = true
		var x int
		for x, n = n, 0; x > 0; x /= 10 {
			d := x % 10
			n += d * d
		}
		if m[n] {
			return false
		}
	}
	return true
}

func main() {
	for found, n := 0, 1; found < 8; n++ {
		if happy(n) {
			fmt.Print(n, " ")
			found++
		}
	}
	fmt.Println()
}