WeixiangYan/CodeTransOcean huggingface dataset:
Task: Sorting algorithms_Bogosort



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

namespace RosettaCode.BogoSort
{
    public static class BogoSorter
    {
        public static void Sort<T>(List<T> list) where T:IComparable
        {
            while (!list.isSorted())
            {
                list.Shuffle();
            }
        }

        private static bool isSorted<T>(this IList<T> list) where T:IComparable
        {
            if(list.Count<=1)
                return true;
            for (int i = 1 ; i < list.Count; i++)
                if(list[i].CompareTo(list[i-1])<0) return false;
            return true;
        }

        private static void Shuffle<T>(this IList<T> list)
        {
            Random rand = new Random();
            for (int i = 0; i < list.Count; i++)
            {
                int swapIndex = rand.Next(list.Count);
                T temp = list[swapIndex];
                list[swapIndex] = list[i];
                list[i] = temp;
            }
        }
    }

    class TestProgram
    {
        static void Main()
        {
            List<int> testList = new List<int> { 3, 4, 1, 8, 7, 4, -2 };
            BogoSorter.Sort(testList);
            foreach (int i in testList) Console.Write(i + " ");
        }

    }
}


Go: package main

import (
    "fmt"
    "math/rand"
    "sort"
    "time"
)

func main() {
    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
    rand.Seed(time.Now().UnixNano())
    fmt.Println("unsorted:", list)
    temp := make([]int, len(list))
    copy(temp, list)
    for !sort.IntsAreSorted(temp) {
        for i, v := range rand.Perm(len(list)) {
            temp[i] = list[v]
        }
    }
    fmt.Println("sorted!  ", temp)
}
Task: Euler method



C#: using System;

namespace prog
{
	class MainClass
	{
		const float T0 = 100f;
		const float TR = 20f;
		const float k = 0.07f;
		readonly static float[] delta_t = {2.0f,5.0f,10.0f};
		const int n = 100;
		
		public delegate float func(float t);
		static float NewtonCooling(float t)
		{
			return -k * (t-TR);			
		}
		
		public static void Main (string[] args)
		{
			func f = new func(NewtonCooling); 
			for(int i=0; i<delta_t.Length; i++)
			{
				Console.WriteLine("delta_t = " + delta_t[i]);
				Euler(f,T0,n,delta_t[i]);
			}
		}
				
		public static void Euler(func f, float y, int n, float h)
		{
			for(float x=0; x<=n; x+=h)
			{
				Console.WriteLine("\t" + x + "\t" + y);
				y += h * f(y);	
			}
		}
	}
}


Go: package main

import (
    "fmt"
    "math"
)


type fdy func(float64, float64) float64




func eulerStep(f fdy, x, y, h float64) float64 {
    return y + h*f(x, y)
}






func newCoolingRate(k float64) func(float64) float64 {
    return func(deltaTemp float64) float64 {
        return -k * deltaTemp
    }
}



func newTempFunc(k, ambientTemp, initialTemp float64) func(float64) float64 {
    return func(time float64) float64 {
        return ambientTemp + (initialTemp-ambientTemp)*math.Exp(-k*time)
    }
}






func newCoolingRateDy(k, ambientTemp float64) fdy {
    crf := newCoolingRate(k)
    
    
    
    return func(_, objectTemp float64) float64 {
        return crf(objectTemp - ambientTemp)
    }
}

func main() {
    k := .07
    tempRoom := 20.
    tempObject := 100.
    fcr := newCoolingRateDy(k, tempRoom)
    analytic := newTempFunc(k, tempRoom, tempObject)
    for _, deltaTime := range []float64{2, 5, 10} {
        fmt.Printf("Step size = %.1f\n", deltaTime)
        fmt.Println(" Time Euler's Analytic")
        temp := tempObject
        for time := 0.; time <= 100; time += deltaTime {
            fmt.Printf("%5.1f %7.3f %7.3f\n", time, temp, analytic(time))
            temp = eulerStep(fcr, time, temp, deltaTime)
        }
        fmt.Println()
    }
}
Task: Sequence of non-squares



C#: using System;
using System.Diagnostics;

namespace sons
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i < 23; i++)            
                Console.WriteLine(nonsqr(i));            

            for (int i = 1; i < 1000000; i++)
            {
                double j = Math.Sqrt(nonsqr(i));
                Debug.Assert(j != Math.Floor(j),"Square");
            }            
        }

        static int nonsqr(int i)
        {
            return (int)(i + Math.Floor(0.5 + Math.Sqrt(i)));
        }
    }
}


Go: package main

import (
    "fmt"
    "math"
)

func remarkable(n int) int {
    return n + int(.5+math.Sqrt(float64(n)))
}

func main() {
    
    fmt.Println("  n  r(n)")
    fmt.Println("---  ---")
    for n := 1; n <= 22; n++ {
        fmt.Printf("%3d  %3d\n", n, remarkable(n))
    }

    
    const limit = 1e6
    fmt.Println("\nChecking for squares for n <", limit)
    next := 2
    nextSq := 4
    for n := 1; n < limit; n++ {
        r := remarkable(n)
        switch {
        case r == nextSq:
            panic(n)
        case r > nextSq:
            fmt.Println(nextSq, "didn't occur")
            next++
            nextSq = next * next
        }
    }
    fmt.Println("No squares occur for n <", limit)
}
Task: Substring



C#: using System;
namespace SubString
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "0123456789";
            const int n = 3;
            const int m = 2;
            const char c = '3';
            const string z = "345";

            
            Console.WriteLine(s.Substring(n, m));
            
            Console.WriteLine(s.Substring(n, s.Length - n));
            
            Console.WriteLine(s.Substring(0, s.Length - 1));
            
            Console.WriteLine(s.Substring(s.IndexOf(c), m));
            
            Console.WriteLine(s.Substring(s.IndexOf(z), m));
        }
    }
}


Go: package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "ABCDEFGH"
    n, m := 2, 3
    
    fmt.Println("Index: ", "01234567")
    fmt.Println("String:", s)
    
    fmt.Printf("Start %d, length %d:    %s\n", n, m, s[n : n+m])
    
    fmt.Printf("Start %d, to end:      %s\n", n, s[n:])
    
    fmt.Printf("All but last:         %s\n", s[:len(s)-1])
    
    dx := strings.IndexByte(s, 'D')
    fmt.Printf("Start 'D', length %d:  %s\n", m, s[dx : dx+m])
    
    sx := strings.Index(s, "DE")
    fmt.Printf(`Start "DE", length %d: %s`+"\n", m, s[sx : sx+m])
}
Task: JortSort



C#: using System;

class Program
{
  public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>
  {
    
    T[] originalArray = (T[]) array.Clone();
    Array.Sort(array);

    
    for (var i = 0; i < originalArray.Length; i++)
    {
      if (!Equals(originalArray[i], array[i]))
      {
        return false;
      }
    }

    return true;
  }
}


Go: package main

import (
  "log"
  "sort"
)

func main() {
  log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) 
  log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))       
  log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))    
  log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))       
}

func jortSort(a []int) bool {
  c := make([]int, len(a))
  copy(c, a)
  sort.Ints(a)
  for k, v := range c {
    if v == a[k] {
      continue
    } else {
      return false
    }
  }
  return true
}
Task: Leap year



C#: using System;

class Program
{
    static void Main()
    {
        foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })
        {
            Console.WriteLine("{0} is {1}a leap year.",
                              year,
                              DateTime.IsLeapYear(year) ? string.Empty : "not ");
        }
    }
}


Go: func isLeap(year int) bool {
    return year%400 == 0 || year%4 == 0 && year%100 != 0
}
Task: Sort numbers lexicographically



C#: using static System.Console;
using static System.Linq.Enumerable;

public class Program
{
    public static void Main() {
        foreach (int n in new [] { 0, 5, 13, 21, -22 }) WriteLine($"{n}: {string.Join(", ", LexOrder(n))}");
    }

    public static IEnumerable<int> LexOrder(int n) => (n < 1 ? Range(n, 2 - n) : Range(1, n)).OrderBy(i => i.ToString());
}


Go: package main

import (
    "fmt"
    "sort"
    "strconv"
)

func lexOrder(n int) []int {
    first, last, k := 1, n, n
    if n < 1 {
        first, last, k = n, 1, 2-n
    }
    strs := make([]string, k)
    for i := first; i <= last; i++ {
        strs[i-first] = strconv.Itoa(i)
    }
    sort.Strings(strs)
    ints := make([]int, k)
    for i := 0; i < k; i++ {
        ints[i], _ = strconv.Atoi(strs[i])
    }
    return ints
}

func main() {
    fmt.Println("In lexicographical order:\n")
    for _, n := range []int{0, 5, 13, 21, -22} {
        fmt.Printf("%3d: %v\n", n, lexOrder(n))
    }
}
Task: Compare length of two strings



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

namespace example
{
    class Program
    {
        static void Main(string[] args)
        {
            var strings = new string[] { "abcd", "123456789", "abcdef", "1234567" };
            compareAndReportStringsLength(strings);
        }

        private static void compareAndReportStringsLength(string[] strings)
        {
            if (strings.Length > 0)
            {
                char Q = '"';
                string hasLength = " has length ";
                string predicateMax = " and is the longest string";
                string predicateMin = " and is the shortest string";
                string predicateAve = " and is neither the longest nor the shortest string";
                string predicate;

                (int, int)[] li = new (int, int)[strings.Length];
                for (int i = 0; i < strings.Length; i++)
                    li[i] = (strings[i].Length, i);
                Array.Sort(li, ((int, int) a, (int, int) b) => b.Item1 - a.Item1);
                int maxLength = li[0].Item1;
                int minLength = li[strings.Length - 1].Item1;

                for (int i = 0; i < strings.Length; i++)
                {
                    int length = li[i].Item1;
                    string str = strings[li[i].Item2];
                    if (length == maxLength)
                        predicate = predicateMax;
                    else if (length == minLength)
                        predicate = predicateMin;
                    else
                        predicate = predicateAve;
                    Console.WriteLine(Q + str + Q + hasLength + length + predicate);
                }
            }
        }

    }
}


Go: package main

import (
	"fmt"
	"os"
	"sort"
)

func main() {
	
	if len(os.Args) == 1 {
		compareStrings("abcd", "123456789", "abcdef", "1234567")
	} else {
		
		strings := os.Args[1:]
		compareStrings(strings...)
	}
}


func compareStrings(strings ...string) {
	
	
	sort.SliceStable(strings, func(i, j int) bool {
		return len(strings[i]) > len(strings[j])
	})

	for _, s := range strings {
		fmt.Printf("%d: %s\n", len(s), s)
	}
}
Task: Letter frequency



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

class Program
{
    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)
    {
        var dictionary = new SortedDictionary<TItem, int>();
        foreach (var item in items)
        {
            if (dictionary.ContainsKey(item))
            {
                dictionary[item]++;
            }
            else
            {
                dictionary[item] = 1;
            }
        }
        return dictionary;
    }

    static void Main(string[] arguments)
    {
        var file = arguments.FirstOrDefault();
        if (File.Exists(file))
        {
            var text = File.ReadAllText(file);
            foreach (var entry in GetFrequencies(text))
            {
                Console.WriteLine("{0}: {1}", entry.Key, entry.Value);
            }
        }
    }
}


Go: package main

import (
    "fmt"
    "io/ioutil"
    "sort"
    "unicode"
)

const file = "unixdict.txt"

func main() {
    bs, err := ioutil.ReadFile(file)
    if err != nil {
        fmt.Println(err)
        return
    }
    m := make(map[rune]int)
    for _, r := range string(bs) {
        m[r]++
    }
    
    lfs := make(lfList, 0, len(m))
    for l, f := range m {
        lfs = append(lfs, &letterFreq{l, f})
    }
    sort.Sort(lfs)
    fmt.Println("file:", file)
    fmt.Println("letter  frequency")
    for _, lf := range lfs {
        if unicode.IsGraphic(lf.rune) {
            fmt.Printf("   %c    %7d\n", lf.rune, lf.freq)
        } else {
            fmt.Printf("%U  %7d\n", lf.rune, lf.freq)
        }
    }
}

type letterFreq struct {
    rune
    freq int
}
type lfList []*letterFreq

func (lfs lfList) Len() int { return len(lfs) }
func (lfs lfList) Less(i, j int) bool {
    switch fd := lfs[i].freq - lfs[j].freq; {
    case fd < 0:
        return false
    case fd > 0:
        return true
    }
    return lfs[i].rune < lfs[j].rune
}
func (lfs lfList) Swap(i, j int) {
    lfs[i], lfs[j] = lfs[j], lfs[i]
}
Task: Increment a numerical string



C#: string s = "12345";
s = (int.Parse(s) + 1).ToString();






using System.Numerics;
string bis = "123456789012345678999999999";
bis = (BigInteger.Parse(bis) + 1).ToString();




Go: package main
import "fmt"
import "strconv"
func main() {
  i, _ := strconv.Atoi("1234")
  fmt.Println(strconv.Itoa(i + 1))
}
Task: Strip a set of characters from a string



C#: using System;

public static string RemoveCharactersFromString(string testString, string removeChars)
{
    char[] charAry = removeChars.ToCharArray();
    string returnString = testString;
    foreach (char c in charAry)
    {
        while (returnString.IndexOf(c) > -1)
        {
            returnString = returnString.Remove(returnString.IndexOf(c), 1);
        }
    }
    return returnString;
}


Go: package main

import (
    "fmt"
    "strings"
)

func stripchars(str, chr string) string {
    return strings.Map(func(r rune) rune {
        if strings.IndexRune(chr, r) < 0 {
            return r
        }
        return -1
    }, str)
}

func main() {
    fmt.Println(stripchars("She was a soul stripper. She took my heart!",
        "aei"))
}
Task: Averages_Arithmetic mean



C#: using System;
using System.Linq;

class Program
{
    static void Main()
    {
        Console.WriteLine(new[] { 1, 2, 3 }.Average());
    }
}


Go: package main

import (
    "fmt"
    "math"
)

func mean(v []float64) (m float64, ok bool) {
    if len(v) == 0 {
        return
    }
    
    
    var parts []float64
    for _, x := range v {
        var i int
        for _, p := range parts {
            sum := p + x
            var err float64
            switch ax, ap := math.Abs(x), math.Abs(p); {
            case ax < ap:
                err = x - (sum - p)
            case ap < ax:
                err = p - (sum - x)
            }
            if err != 0 {
                parts[i] = err
                i++
            }
            x = sum
        }
        parts = append(parts[:i], x)
    }
    var sum float64
    for _, x := range parts {
        sum += x
    }
    return sum / float64(len(v)), true
}

func main() {
    for _, v := range [][]float64{
        []float64{},                         
        []float64{math.Inf(1), math.Inf(1)}, 

        
        
        []float64{math.Inf(1), math.Inf(-1)},

        []float64{3, 1, 4, 1, 5, 9},

        
        []float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},

        []float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},
        []float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},
    } {
        fmt.Println("Vector:", v)
        if m, ok := mean(v); ok {
            fmt.Printf("Mean of %d numbers is %g\n\n", len(v), m)
        } else {
            fmt.Println("Mean undefined\n")
        }
    }
}
Task: Entropy



C#: using System;
using System.Collections.Generic;
namespace Entropy
{
	class Program
	{
		public static double logtwo(double num)
		{
			return Math.Log(num)/Math.Log(2);
		}
		public static void Main(string[] args)
		{
		label1:
			string input = Console.ReadLine();
			double infoC=0;
			Dictionary<char,double> table = new Dictionary<char, double>();

			
			foreach (char c in input)
			{
				if (table.ContainsKey(c))
					table[c]++;
				    else
				    	table.Add(c,1);
	
			}
			double freq;
			foreach (KeyValuePair<char,double> letter in table)
			{
				freq=letter.Value/input.Length;
				infoC+=freq*logtwo(freq);
			}
			infoC*=-1;
			Console.WriteLine("The Entropy of {0} is {1}",input,infoC);
			goto label1;
		
		}
	}
}


Go: package main

import (
    "fmt"
    "math"
    "strings"
)

func main(){
    fmt.Println(H("1223334444"))
}


func H(data string) (entropy float64) {
    if data == "" {
        return 0
    }
    for i := 0; i < 256; i++ {
        px := float64(strings.Count(data, string(byte(i)))) / float64(len(data))
        if px > 0 {
	    entropy += -px * math.Log2(px)
	}
    }
    return entropy
}
Task: Tokenize a string with escaping



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

public class TokenizeAStringWithEscaping
{
    public static void Main() {
        string testcase = "one^|uno||three^^^^|four^^^|^cuatro|";
        foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {
            Console.WriteLine(": " + token); 
        }
    }
}

public static class Extensions
{
    public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {
        if (input == null) yield break;
        var buffer = new StringBuilder();
        bool escaping = false;
        foreach (char c in input) {
            if (escaping) {
                buffer.Append(c);
                escaping = false;
            } else if (c == escape) {
                escaping = true;
            } else if (c == separator) {
                yield return buffer.Flush();
            } else {
                buffer.Append(c);
            }
        }
        if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();
    }
    
    public static string Flush(this StringBuilder stringBuilder) {
        string result = stringBuilder.ToString();
        stringBuilder.Clear();
        return result;
    }
}


Go: package main

import (
	"errors"
	"fmt"
)

func TokenizeString(s string, sep, escape rune) (tokens []string, err error) {
	var runes []rune
	inEscape := false
	for _, r := range s {
		switch {
		case inEscape:
			inEscape = false
			fallthrough
		default:
			runes = append(runes, r)
		case r == escape:
			inEscape = true
		case r == sep:
			tokens = append(tokens, string(runes))
			runes = runes[:0]
		}
	}
	tokens = append(tokens, string(runes))
	if inEscape {
		err = errors.New("invalid terminal escape")
	}
	return tokens, err
}

func main() {
	const sample = "one^|uno||three^^^^|four^^^|^cuatro|"
	const separator = '|'
	const escape = '^'

	fmt.Printf("Input:   %q\n", sample)
	tokens, err := TokenizeString(sample, separator, escape)
	if err != nil {
		fmt.Println("error:", err)
	} else {
		fmt.Printf("Tokens: %q\n", tokens)
	}
}
Task: Hello world_Text



C#: Using System;
namespace HelloWorld {
  class Program
  {
    static void Main()
    {
      Console.Writeln("Hello World!");
    }
  }
}


Go: package main

import "fmt"

func main() { fmt.Println("Hello world!") }
Task: Forward difference



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

class Program
{
    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)
    {
        switch (order)
        {
            case 0u:
                return sequence;
            case 1u:
                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);
            default:
                return ForwardDifference(ForwardDifference(sequence), order - 1u);
        }
    }

    static void Main()
    {
        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };
        do
        {
            Console.WriteLine(string.Join(", ", sequence));
        } while ((sequence = ForwardDifference(sequence)).Any());
    }
}


Go: package main

import "fmt"

func main() {
    a := []int{90, 47, 58, 29, 22, 32, 55, 5, 55, 73}
    fmt.Println(a)
    fmt.Println(fd(a, 9))
}

func fd(a []int, ord int) []int {
    for i := 0; i < ord; i++ {
        for j := 0; j < len(a)-i-1; j++ {
            a[j] = a[j+1] - a[j]
        }
    }
    return a[:len(a)-ord]
}
Task: Primality by trial division



C#: static bool isPrime(int n)
        {
            if (n <= 1) return false;
            for (int i = 2; i * i <= n; i++)            
                if (n % i == 0) return false;            
            return true;
        }


Go: func IsPrime(n int) bool {
	if n < 0 { n = -n }
	switch {
        case n == 2:
		return true
	case n < 2 || n % 2 == 0:
		return false
	
	default:
		for i = 3; i*i <= n; i += 2 {
			if n % i == 0 { return false }
		}
	}
	return true
}
Task: Evaluate binomial coefficients



C#: using System;

namespace BinomialCoefficients
{
    class Program
    {
        static void Main(string[] args)
        {
            ulong n = 1000000, k = 3;
            ulong result = biCoefficient(n, k);
            Console.WriteLine("The Binomial Coefficient of {0}, and {1}, is equal to: {2}", n, k, result);
            Console.ReadLine();
        }

        static int fact(int n)
        {
            if (n == 0) return 1;
            else return n * fact(n - 1);
        }

        static ulong biCoefficient(ulong n, ulong k)
        {
            if (k > n - k)
            {
                k = n - k;
            }

            ulong c = 1;
            for (uint i = 0; i < k; i++)
            {
                c = c * (n - i);
                c = c / (i + 1);
            }
            return c;
        }
    }
}


Go: package main
import "fmt"
import "math/big"

func main() {
  fmt.Println(new(big.Int).Binomial(5, 3))
  fmt.Println(new(big.Int).Binomial(60, 30))
}
Task: Collections



C#: 
int[] intArray = new int[5] { 1, 2, 3, 4, 5 };

int[] intArray = new int[]{ 1, 2, 3, 4, 5 };

int[] intArray = { 1, 2, 3, 4, 5 };


string[] stringArr = new string[5];
stringArr[0] = "string";


Go: package main

import "fmt"

func main() {
    var a []interface{}
    a = append(a, 3)
    a = append(a, "apples", "oranges")
    fmt.Println(a)
}
Task: Singly-linked list_Traversal



C#: var current = [head of list to traverse]
while(current != null)
{
    

    current = current.Next;
}


Go: start := &Ele{"tacos", nil}
end := start.Append("burritos")
end = end.Append("fajitas")
end = end.Append("enchilatas")
for iter := start; iter != nil; iter = iter.Next {
    fmt.Println(iter)
}
Task: Bitmap_Write a PPM file



C#: using System;
using System.IO;
class PPMWriter
{
    public static void WriteBitmapToPPM(string file, Bitmap bitmap)
        {
            
            var writer = new StreamWriter(file);
            writer.WriteLine("P6");
            writer.WriteLine($"{bitmap.Width}  {bitmap.Height}");
            writer.WriteLine("255");
            writer.Close();
            
            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));
            for (int x = 0; x < bitmap.Height; x++)
                for (int y = 0; y < bitmap.Width; y++)
                {
                    Color color = bitmap.GetPixel(y, x);
                    writerB.Write(color.R);
                    writerB.Write(color.G);
                    writerB.Write(color.B);
                }
            writerB.Close();
        }
}


Go: package raster

import (
    "fmt"
    "io"
    "os"
)


func (b *Bitmap) WritePpmTo(w io.Writer) (err error) {
    
    if _, err = fmt.Fprintln(w, "P6"); err != nil {
        return
    }

    
    for _, c := range b.Comments {
        if _, err = fmt.Fprintln(w, c); err != nil {
            return
        }
    }

    
    _, err = fmt.Fprintf(w, "%d %d\n255\n", b.cols, b.rows)
    if err != nil {
        return
    }

    
    b3 := make([]byte, 3*len(b.px))
    n1 := 0
    for _, px := range b.px {
        b3[n1] = px.R
        b3[n1+1] = px.G
        b3[n1+2] = px.B
        n1 += 3
    }
    if _, err = w.Write(b3); err != nil {
        return
    }
    return
}


func (b *Bitmap) WritePpmFile(fn string) (err error) {
    var f *os.File
    if f, err = os.Create(fn); err != nil {
        return
    }
    if err = b.WritePpmTo(f); err != nil {
        return
    }
    return f.Close()
}