title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
Word search
C sharp from Java
A word search puzzle typically consists of a grid of letters in which words are hidden. There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards. The words may overlap but are not allowed to zigzag, or wrap around. ;Task Create a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters. The cells not used by the hidden words should contain the message: ''Rosetta Code'', read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message. Pack a minimum of 25 words into the grid. Print the resulting grid and the solutions. ;Example 0 1 2 3 4 5 6 7 8 9 0 n a y r y R e l m f 1 y O r e t s g n a g 2 t n e d i S k y h E 3 n o t n c p c w t T 4 a l s u u n T m a x 5 r o k p a r i s h h 6 a A c f p a e a c C 7 u b u t t t O l u n 8 g y h w a D h p m u 9 m i r p E h o g a n parish (3,5)(8,5) gangster (9,1)(2,1) paucity (4,6)(4,0) guaranty (0,8)(0,1) prim (3,9)(0,9) huckster (2,8)(2,1) plasm (7,8)(7,4) fancy (3,6)(7,2) hogan (5,9)(9,9) nolo (1,2)(1,5) under (3,4)(3,0) chatham (8,6)(8,0) ate (4,8)(6,6) nun (9,7)(9,9) butt (1,7)(4,7) hawk (9,5)(6,2) why (3,8)(1,8) ryan (3,0)(0,0) fay (9,0)(7,2) much (8,8)(8,5) tar (5,7)(5,5) elm (6,0)(8,0) max (7,4)(9,4) pup (5,3)(3,5) mph (8,8)(6,8)
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Wordseach { static class Program { readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}}; class Grid { public char[,] Cells = new char[nRows, nCols]; public List<string> Solutions = new List<string>(); public int NumAttempts; } readonly static int nRows = 10; readonly static int nCols = 10; readonly static int gridSize = nRows * nCols; readonly static int minWords = 25; readonly static Random rand = new Random(); static void Main(string[] args) { PrintResult(CreateWordSearch(ReadWords("unixdict.txt"))); } private static List<string> ReadWords(string filename) { int maxLen = Math.Max(nRows, nCols); return System.IO.File.ReadAllLines(filename) .Select(s => s.Trim().ToLower()) .Where(s => Regex.IsMatch(s, "^[a-z]{3," + maxLen + "}$")) .ToList(); } private static Grid CreateWordSearch(List<string> words) { int numAttempts = 0; while (++numAttempts < 100) { words.Shuffle(); var grid = new Grid(); int messageLen = PlaceMessage(grid, "Rosetta Code"); int target = gridSize - messageLen; int cellsFilled = 0; foreach (var word in words) { cellsFilled += TryPlaceWord(grid, word); if (cellsFilled == target) { if (grid.Solutions.Count >= minWords) { grid.NumAttempts = numAttempts; return grid; } else break; // grid is full but we didn't pack enough words, start over } } } return null; } private static int TryPlaceWord(Grid grid, string word) { int randDir = rand.Next(dirs.GetLength(0)); int randPos = rand.Next(gridSize); for (int dir = 0; dir < dirs.GetLength(0); dir++) { dir = (dir + randDir) % dirs.GetLength(0); for (int pos = 0; pos < gridSize; pos++) { pos = (pos + randPos) % gridSize; int lettersPlaced = TryLocation(grid, word, dir, pos); if (lettersPlaced > 0) return lettersPlaced; } } return 0; } private static int TryLocation(Grid grid, string word, int dir, int pos) { int r = pos / nCols; int c = pos % nCols; int len = word.Length; // check bounds if ((dirs[dir, 0] == 1 && (len + c) > nCols) || (dirs[dir, 0] == -1 && (len - 1) > c) || (dirs[dir, 1] == 1 && (len + r) > nRows) || (dirs[dir, 1] == -1 && (len - 1) > r)) return 0; int rr, cc, i, overlaps = 0; // check cells for (i = 0, rr = r, cc = c; i < len; i++) { if (grid.Cells[rr, cc] != 0 && grid.Cells[rr, cc] != word[i]) { return 0; } cc += dirs[dir, 0]; rr += dirs[dir, 1]; } // place for (i = 0, rr = r, cc = c; i < len; i++) { if (grid.Cells[rr, cc] == word[i]) overlaps++; else grid.Cells[rr, cc] = word[i]; if (i < len - 1) { cc += dirs[dir, 0]; rr += dirs[dir, 1]; } } int lettersPlaced = len - overlaps; if (lettersPlaced > 0) { grid.Solutions.Add($"{word,-10} ({c},{r})({cc},{rr})"); } return lettersPlaced; } private static int PlaceMessage(Grid grid, string msg) { msg = Regex.Replace(msg.ToUpper(), "[^A-Z]", ""); int messageLen = msg.Length; if (messageLen > 0 && messageLen < gridSize) { int gapSize = gridSize / messageLen; for (int i = 0; i < messageLen; i++) { int pos = i * gapSize + rand.Next(gapSize); grid.Cells[pos / nCols, pos % nCols] = msg[i]; } return messageLen; } return 0; } public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = rand.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } private static void PrintResult(Grid grid) { if (grid == null || grid.NumAttempts == 0) { Console.WriteLine("No grid to display"); return; } int size = grid.Solutions.Count; Console.WriteLine("Attempts: " + grid.NumAttempts); Console.WriteLine("Number of words: " + size); Console.WriteLine("\n 0 1 2 3 4 5 6 7 8 9"); for (int r = 0; r < nRows; r++) { Console.Write("\n{0} ", r); for (int c = 0; c < nCols; c++) Console.Write(" {0} ", grid.Cells[r, c]); } Console.WriteLine("\n"); for (int i = 0; i < size - 1; i += 2) { Console.WriteLine("{0} {1}", grid.Solutions[i], grid.Solutions[i + 1]); } if (size % 2 == 1) Console.WriteLine(grid.Solutions[size - 1]); Console.ReadLine(); } } }
Word wrap
C sharp
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. ;Basic task: The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns. ;Extra credit: Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you ''must reference documentation'' indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results.
namespace RosettaCode.WordWrap { using System; using System.Collections.Generic; internal static class Program { private const string LoremIpsum = @" Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est, condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu nibh."; private static void Main() { foreach (var lineWidth in new[] { 72, 80 }) { Console.WriteLine(new string('-', lineWidth)); Console.WriteLine(Wrap(LoremIpsum, lineWidth)); } } private static string Wrap(string text, int lineWidth) { return string.Join(string.Empty, Wrap( text.Split(new char[0], StringSplitOptions .RemoveEmptyEntries), lineWidth)); } private static IEnumerable<string> Wrap(IEnumerable<string> words, int lineWidth) { var currentWidth = 0; foreach (var word in words) { if (currentWidth != 0) { if (currentWidth + word.Length < lineWidth) { currentWidth++; yield return " "; } else { currentWidth = 0; yield return Environment.NewLine; } } currentWidth += word.Length; yield return word; } } } }
World Cup group stage
C sharp
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. Once a team has qualified they are put into a group with 3 other teams. For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once. The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament. The two teams from each group with the most standings points move on to the knockout stage. Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team. :::* A win is worth three points. :::* A draw/tie is worth one point. :::* A loss is worth zero points. ;Task: :* Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them. :* Calculate the standings points for each team with each combination of outcomes. :* Show a histogram (graphical, ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes. Don't worry about tiebreakers as they can get complicated. We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?". ''Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. Oddly enough, there is no way to get 8 points at all.''
using System; using System.Collections.Generic; using System.Linq; using System.Text; using static System.Console; using static System.Linq.Enumerable; namespace WorldCupGroupStage { public static class WorldCupGroupStage { static int[][] _histogram; static WorldCupGroupStage() { int[] scoring = new[] { 0, 1, 3 }; _histogram = Repeat<Func<int[]>>(()=>new int[10], 4).Select(f=>f()).ToArray(); var teamCombos = Range(0, 4).Combinations(2).Select(t2=>t2.ToArray()).ToList(); foreach (var results in Range(0, 3).CartesianProduct(6)) { var points = new int[4]; foreach (var (result, teams) in results.Zip(teamCombos, (r, t) => (r, t))) { points[teams[0]] += scoring[result]; points[teams[1]] += scoring[2 - result]; } foreach(var (p,i) in points.OrderByDescending(a => a).Select((p,i)=>(p,i))) _histogram[i][p]++; } } // https://gist.github.com/martinfreedman/139dd0ec7df4737651482241e48b062f static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> seqs) => seqs.Aggregate(Empty<T>().ToSingleton(), (acc, sq) => acc.SelectMany(a => sq.Select(s => a.Append(s)))); static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<T> seq, int repeat = 1) => Repeat(seq, repeat).CartesianProduct(); static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> seq) => seq.Aggregate(Empty<T>().ToSingleton(), (a, b) => a.Concat(a.Select(x => x.Append(b)))); static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> seq, int numItems) => seq.Combinations().Where(s => s.Count() == numItems); private static IEnumerable<T> ToSingleton<T>(this T item) { yield return item; } static new string ToString() { var sb = new StringBuilder(); var range = String.Concat(Range(0, 10).Select(i => $"{i,-3} ")); sb.AppendLine($"Points : {range}"); var u = String.Concat(Repeat("─", 40+13)); sb.AppendLine($"{u}"); var places = new[] { "First", "Second", "Third", "Fourth" }; foreach (var row in _histogram.Select((r, i) => (r, i))) { sb.Append($"{places[row.i],-6} place: "); foreach (var standing in row.r) sb.Append($"{standing,-3} "); sb.Append("\n"); } return sb.ToString(); } static void Main(string[] args) { Write(ToString()); Read(); } } }
Write float arrays to a text file
C sharp|C#
Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].
using System.IO; class Program { static void Main(string[] args) { var x = new double[] { 1, 2, 3, 1e11 }; var y = new double[] { 1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791 }; int xprecision = 3; int yprecision = 5; string formatString = "{0:G" + xprecision + "}\t{1:G" + yprecision + "}"; using (var outf = new StreamWriter("FloatArrayColumns.txt")) for (int i = 0; i < x.Length; i++) outf.WriteLine(formatString, x[i], y[i]); } }
Write language name in 3D ASCII
C sharp|C#
Write/display a language's name in '''3D''' ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) ;Related tasks: * draw a sphere * draw a cuboid * draw a rotating cube * draw a Deathstar
using System; using System.Text; namespace Language_name_in_3D_ascii { public class F5 { char[] z = { ' ', ' ', '_', '/', }; long[,] f ={ {87381,87381,87381,87381,87381,87381,87381,}, {349525,375733,742837,742837,375733,349525,349525,}, {742741,768853,742837,742837,768853,349525,349525,}, {349525,375733,742741,742741,375733,349525,349525,}, {349621,375733,742837,742837,375733,349525,349525,}, {349525,375637,768949,742741,375733,349525,349525,}, {351157,374101,768949,374101,374101,349525,349525,}, {349525,375733,742837,742837,375733,349621,351157,}, {742741,768853,742837,742837,742837,349525,349525,}, {181,85,181,181,181,85,85,}, {1461,1365,1461,1461,1461,1461,2901,}, {742741,744277,767317,744277,742837,349525,349525,}, {181,181,181,181,181,85,85,}, {1431655765,3149249365L,3042661813L,3042661813L,3042661813L,1431655765,1431655765,}, {349525,768853,742837,742837,742837,349525,349525,}, {349525,375637,742837,742837,375637,349525,349525,}, {349525,768853,742837,742837,768853,742741,742741,}, {349525,375733,742837,742837,375733,349621,349621,}, {349525,744373,767317,742741,742741,349525,349525,}, {349525,375733,767317,351157,768853,349525,349525,}, {374101,768949,374101,374101,351157,349525,349525,}, {349525,742837,742837,742837,375733,349525,349525,}, {5592405,11883957,11883957,5987157,5616981,5592405,5592405,}, {366503875925L,778827027893L,778827027893L,392374737749L,368114513237L,366503875925L,366503875925L,}, {349525,742837,375637,742837,742837,349525,349525,}, {349525,742837,742837,742837,375733,349621,375637,}, {349525,768949,351061,374101,768949,349525,349525,}, {375637,742837,768949,742837,742837,349525,349525,}, {768853,742837,768853,742837,768853,349525,349525,}, {375733,742741,742741,742741,375733,349525,349525,}, {192213,185709,185709,185709,192213,87381,87381,}, {1817525,1791317,1817429,1791317,1817525,1398101,1398101,}, {768949,742741,768853,742741,742741,349525,349525,}, {375733,742741,744373,742837,375733,349525,349525,}, {742837,742837,768949,742837,742837,349525,349525,}, {48053,23381,23381,23381,48053,21845,21845,}, {349621,349621,349621,742837,375637,349525,349525,}, {742837,744277,767317,744277,742837,349525,349525,}, {742741,742741,742741,742741,768949,349525,349525,}, {11883957,12278709,11908533,11883957,11883957,5592405,5592405,}, {11883957,12277173,11908533,11885493,11883957,5592405,5592405,}, {375637,742837,742837,742837,375637,349525,349525,}, {768853,742837,768853,742741,742741,349525,349525,}, {6010197,11885397,11909973,11885397,6010293,5592405,5592405,}, {768853,742837,768853,742837,742837,349525,349525,}, {375733,742741,375637,349621,768853,349525,349525,}, {12303285,5616981,5616981,5616981,5616981,5592405,5592405,}, {742837,742837,742837,742837,375637,349525,349525,}, {11883957,11883957,11883957,5987157,5616981,5592405,5592405,}, {3042268597L,3042268597L,3042661813L,1532713813,1437971797,1431655765,1431655765,}, {11883957,5987157,5616981,5987157,11883957,5592405,5592405,}, {11883957,5987157,5616981,5616981,5616981,5592405,5592405,}, {12303285,5593941,5616981,5985621,12303285,5592405,5592405,} }; private F5(string s) { StringBuilder[] o = new StringBuilder[7]; for (int i = 0; i < 7; i++) o[i] = new StringBuilder(); for (int i = 0, l = s.Length; i < l; i++) { int c = s[i]; if (65 <= c && c <= 90) c -= 39; else if (97 <= c && c <= 122) c -= 97; else c = -1; long[] d = new long[7]; Buffer.BlockCopy(f, (++c * sizeof(long) * 7), d, 0, 7 * sizeof(long)); for (int j = 0; j < 7; j++) { StringBuilder b = new StringBuilder(); long v = d[j]; while (v > 0) { b.Append(z[(int)(v & 3)]); v >>= 2; } char[] charArray = b.ToString().ToCharArray(); Array.Reverse(charArray); o[j].Append(new string(charArray)); } } for (int i = 0; i < 7; i++) { for (int j = 0; j < 7 - i; j++) System.Console.Write(' '); System.Console.WriteLine(o[i]); } } public static void Main(string[] args) { new F5(args.Length > 0 ? args[0] : "C sharp"); } } }
Write to Windows event log
C sharp
Write script status to the Windows Event Log
using System.Diagnostics; namespace RC { internal class Program { public static void Main() { string sSource = "Sample App"; string sLog = "Application"; string sEvent = "Hello from RC!"; if (!EventLog.SourceExists(sSource)) EventLog.CreateEventSource(sSource, sLog); EventLog.WriteEntry(sSource, sEvent); EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Information); } } }
Zeckendorf number representation
C sharp
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. The decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100. 10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution. ;Task: Generate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. The intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. ;Also see: * OEIS A014417 for the the sequence of required results. * Brown's Criterion - Numberphile ;Related task: * [[Fibonacci sequence]]
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Zeckendorf { class Program { private static uint Fibonacci(uint n) { if (n < 2) { return n; } else { return Fibonacci(n - 1) + Fibonacci(n - 2); } } private static string Zeckendorf(uint num) { IList<uint> fibonacciNumbers = new List<uint>(); uint fibPosition = 2; uint currentFibonaciNum = Fibonacci(fibPosition); do { fibonacciNumbers.Add(currentFibonaciNum); currentFibonaciNum = Fibonacci(++fibPosition); } while (currentFibonaciNum <= num); uint temp = num; StringBuilder output = new StringBuilder(); foreach (uint item in fibonacciNumbers.Reverse()) { if (item <= temp) { output.Append("1"); temp -= item; } else { output.Append("0"); } } return output.ToString(); } static void Main(string[] args) { for (uint i = 1; i <= 20; i++) { string zeckendorfRepresentation = Zeckendorf(i); Console.WriteLine(string.Format("{0} : {1}", i, zeckendorfRepresentation)); } Console.ReadKey(); } } }
Zero to the zero power
C sharp|C#
Some computer programming languages are not exactly consistent (with other computer programming languages) when ''raising zero to the zeroth power'': 00 ;Task: Show the results of raising zero to the zeroth power. If your computer language objects to '''0**0''' or '''0^0''' at compile time, you may also try something like: x = 0 y = 0 z = x**y say 'z=' z '''Show the result here.''' And of course use any symbols or notation that is supported in your computer programming language for exponentiation. ;See also: * The Wiki entry: Zero to the power of zero. * The Wiki entry: Zero to the power of zero: History. * The MathWorld(tm) entry: exponent laws. ** Also, in the above MathWorld(tm) entry, see formula ('''9'''): x^0=1. * The OEIS entry: The special case of zero to the zeroth power
using System; namespace ZeroToTheZeroeth { class Program { static void Main(string[] args) { double k = Math.Pow(0, 0); Console.Write("0^0 is {0}", k); } } }
100 doors
Go
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it). The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it. The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door. ;Task: Answer the question: what state are the doors in after the last pass? Which are open, which are closed? '''Alternate:''' As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an optimization that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
package main import "fmt" func main() { doors := [100]bool{} // the 100 passes called for in the task description for pass := 1; pass <= 100; pass++ { for door := pass-1; door < 100; door += pass { doors[door] = !doors[door] } } // one more pass to answer the question for i, v := range doors { if v { fmt.Print("1") } else { fmt.Print("0") } if i%10 == 9 { fmt.Print("\n") } else { fmt.Print(" ") } } }
100 prisoners
Go
The Problem: * 100 prisoners are individually numbered 1 to 100 * A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. * Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. * Prisoners start outside the room :* They can decide some strategy before any enter the room. :* Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer. :* A prisoner can open no more than 50 drawers. :* A prisoner tries to find his own number. :* A prisoner finding his own number is then held apart from the others. * If '''all''' 100 prisoners find their own numbers then they will all be pardoned. If ''any'' don't then ''all'' sentences stand. ;The task: # Simulate several thousand instances of the game where the prisoners randomly open drawers # Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of: :* First opening the drawer whose outside number is his prisoner number. :* If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum). Show and compare the computed probabilities of success for the two strategies, here, on this page. ;References: # The unbelievable solution to the 100 prisoner puzzle standupmaths (Video). # [[wp:100 prisoners problem]] # 100 Prisoners Escape Puzzle DataGenetics. # Random permutation statistics#One hundred prisoners on Wikipedia.
package main import ( "fmt" "math/rand" "time" ) // Uses 0-based numbering rather than 1-based numbering throughout. func doTrials(trials, np int, strategy string) { pardoned := 0 trial: for t := 0; t < trials; t++ { var drawers [100]int for i := 0; i < 100; i++ { drawers[i] = i } rand.Shuffle(100, func(i, j int) { drawers[i], drawers[j] = drawers[j], drawers[i] }) prisoner: for p := 0; p < np; p++ { if strategy == "optimal" { prev := p for d := 0; d < 50; d++ { this := drawers[prev] if this == p { continue prisoner } prev = this } } else { // Assumes a prisoner remembers previous drawers (s)he opened // and chooses at random from the others. var opened [100]bool for d := 0; d < 50; d++ { var n int for { n = rand.Intn(100) if !opened[n] { opened[n] = true break } } if drawers[n] == p { continue prisoner } } } continue trial } pardoned++ } rf := float64(pardoned) / float64(trials) * 100 fmt.Printf(" strategy = %-7s pardoned = %-6d relative frequency = %5.2f%%\n\n", strategy, pardoned, rf) } func main() { rand.Seed(time.Now().UnixNano()) const trials = 100000 for _, np := range []int{10, 100} { fmt.Printf("Results from %d trials with %d prisoners:\n\n", trials, np) for _, strategy := range [2]string{"random", "optimal"} { doTrials(trials, np, strategy) } } }
15 puzzle game
Go
Implement the Fifteen Puzzle Game. The '''15-puzzle''' is also known as: :::* '''Fifteen Puzzle''' :::* '''Gem Puzzle''' :::* '''Boss Puzzle''' :::* '''Game of Fifteen''' :::* '''Mystic Square''' :::* '''14-15 Puzzle''' :::* and some others. ;Related Tasks: :* 15 Puzzle Solver :* [[16 Puzzle Game]]
package main import ( "fmt" "math/rand" "strings" "time" ) func main() { rand.Seed(time.Now().UnixNano()) p := newPuzzle() p.play() } type board [16]cell type cell uint8 type move uint8 const ( up move = iota down right left ) func randMove() move { return move(rand.Intn(4)) } var solvedBoard = board{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0} func (b *board) String() string { var buf strings.Builder for i, c := range b { if c == 0 { buf.WriteString(" .") } else { _, _ = fmt.Fprintf(&buf, "%3d", c) } if i%4 == 3 { buf.WriteString("\n") } } return buf.String() } type puzzle struct { board board empty int // board[empty] == 0 moves int quit bool } func newPuzzle() *puzzle { p := &puzzle{ board: solvedBoard, empty: 15, } // Could make this configurable, 10==easy, 50==normal, 100==hard p.shuffle(50) return p } func (p *puzzle) shuffle(moves int) { // As with other Rosetta solutions, we use some number // of random moves to "shuffle" the board. for i := 0; i < moves || p.board == solvedBoard; { if p.doMove(randMove()) { i++ } } } func (p *puzzle) isValidMove(m move) (newIndex int, ok bool) { switch m { case up: return p.empty - 4, p.empty/4 > 0 case down: return p.empty + 4, p.empty/4 < 3 case right: return p.empty + 1, p.empty%4 < 3 case left: return p.empty - 1, p.empty%4 > 0 default: panic("not reached") } } func (p *puzzle) doMove(m move) bool { i := p.empty j, ok := p.isValidMove(m) if ok { p.board[i], p.board[j] = p.board[j], p.board[i] p.empty = j p.moves++ } return ok } func (p *puzzle) play() { fmt.Printf("Starting board:") for p.board != solvedBoard && !p.quit { fmt.Printf("\n%v\n", &p.board) p.playOneMove() } if p.board == solvedBoard { fmt.Printf("You solved the puzzle in %d moves.\n", p.moves) } } func (p *puzzle) playOneMove() { for { fmt.Printf("Enter move #%d (U, D, L, R, or Q): ", p.moves+1) var s string if n, err := fmt.Scanln(&s); err != nil || n != 1 { continue } s = strings.TrimSpace(s) if s == "" { continue } var m move switch s[0] { case 'U', 'u': m = up case 'D', 'd': m = down case 'L', 'l': m = left case 'R', 'r': m = right case 'Q', 'q': fmt.Printf("Quiting after %d moves.\n", p.moves) p.quit = true return default: fmt.Println(` Please enter "U", "D", "L", or "R" to move the empty cell up, down, left, or right. You can also enter "Q" to quit. Upper or lowercase is accepted and only the first non-blank character is important (i.e. you may enter "up" if you like). `) continue } if !p.doMove(m) { fmt.Println("That is not a valid move at the moment.") continue } return } }
21 game
Go
'''21''' is a two player game, the game is played by choosing a number ('''1''', '''2''', or '''3''') to be added to the ''running total''. The game is won by the player whose chosen number causes the ''running total'' to reach ''exactly'' '''21'''. The ''running total'' starts at zero. One player will be the computer. Players alternate supplying a number to be added to the ''running total''. ;Task: Write a computer program that will: ::* do the prompting (or provide a button menu), ::* check for errors and display appropriate error messages, ::* do the additions (add a chosen number to the ''running total''), ::* display the ''running total'', ::* provide a mechanism for the player to quit/exit/halt/stop/close the program, ::* issue a notification when there is a winner, and ::* determine who goes first (maybe a random or user choice, or can be specified when the game begins).
package main import ( "bufio" "fmt" "log" "math/rand" "os" "strconv" "time" ) var scanner = bufio.NewScanner(os.Stdin) var ( total = 0 quit = false ) func itob(i int) bool { if i == 0 { return false } return true } func getChoice() { for { fmt.Print("Your choice 1 to 3 : ") scanner.Scan() if scerr := scanner.Err(); scerr != nil { log.Fatalln(scerr, "when choosing number") } text := scanner.Text() if text == "q" || text == "Q" { quit = true return } input, err := strconv.Atoi(text) if err != nil { fmt.Println("Invalid number, try again") continue } newTotal := total + input switch { case input < 1 || input > 3: fmt.Println("Out of range, try again") case newTotal > 21: fmt.Println("Too big, try again") default: total = newTotal fmt.Println("Running total is now", total) return } } } func main() { rand.Seed(time.Now().UnixNano()) computer := itob(rand.Intn(2)) fmt.Println("Enter q to quit at any time\n") if computer { fmt.Println("The computer will choose first") } else { fmt.Println("You will choose first") } fmt.Println("\nRunning total is now 0\n") var choice int for round := 1; ; round++ { fmt.Printf("ROUND %d:\n\n", round) for i := 0; i < 2; i++ { if computer { if total < 18 { choice = 1 + rand.Intn(3) } else { choice = 21 - total } total += choice fmt.Println("The computer chooses", choice) fmt.Println("Running total is now", total) if total == 21 { fmt.Println("\nSo, commiserations, the computer has won!") return } } else { getChoice() if quit { fmt.Println("OK, quitting the game") return } if total == 21 { fmt.Println("\nSo, congratulations, you've won!") return } } fmt.Println() computer = !computer } } }
24 game
Go
The 24 Game tests one's mental arithmetic. ;Task Write a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to '''24'''. * Only the following operators/functions are allowed: multiplication, division, addition, subtraction * Division should use floating point or rational arithmetic, etc, to preserve remainders. * Brackets are allowed, if using an infix expression evaluator. * Forming multiple digit numbers from the supplied digits is ''disallowed''. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). * The order of the digits when given does not have to be preserved. ;Notes * The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example. * The task is not for the program to generate the expression, or test whether an expression is even possible. ;Related tasks * [[24 game/Solve]] ;Reference * The 24 Game on h2g2.
package main import ( "fmt" "math" "math/rand" "time" ) func main() { rand.Seed(time.Now().Unix()) n := make([]rune, 4) for i := range n { n[i] = rune(rand.Intn(9) + '1') } fmt.Printf("Your numbers: %c\n", n) fmt.Print("Enter RPN: ") var expr string fmt.Scan(&expr) if len(expr) != 7 { fmt.Println("invalid. expression length must be 7." + " (4 numbers, 3 operators, no spaces)") return } stack := make([]float64, 0, 4) for _, r := range expr { if r >= '0' && r <= '9' { if len(n) == 0 { fmt.Println("too many numbers.") return } i := 0 for n[i] != r { i++ if i == len(n) { fmt.Println("wrong numbers.") return } } n = append(n[:i], n[i+1:]...) stack = append(stack, float64(r-'0')) continue } if len(stack) < 2 { fmt.Println("invalid expression syntax.") return } switch r { case '+': stack[len(stack)-2] += stack[len(stack)-1] case '-': stack[len(stack)-2] -= stack[len(stack)-1] case '*': stack[len(stack)-2] *= stack[len(stack)-1] case '/': stack[len(stack)-2] /= stack[len(stack)-1] default: fmt.Printf("%c invalid.\n", r) return } stack = stack[:len(stack)-1] } if math.Abs(stack[0]-24) > 1e-6 { fmt.Println("incorrect.", stack[0], "!= 24") } else { fmt.Println("correct.") } }
24 game/Solve
Go
Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the [[24 game]]. Show examples of solutions generated by the program. ;Related task: * [[Arithmetic Evaluator]]
package main import ( "fmt" "math/rand" "time" ) const ( op_num = iota op_add op_sub op_mul op_div ) type frac struct { num, denom int } // Expression: can either be a single number, or a result of binary // operation from left and right node type Expr struct { op int left, right *Expr value frac } var n_cards = 4 var goal = 24 var digit_range = 9 func (x *Expr) String() string { if x.op == op_num { return fmt.Sprintf("%d", x.value.num) } var bl1, br1, bl2, br2, opstr string switch { case x.left.op == op_num: case x.left.op >= x.op: case x.left.op == op_add && x.op == op_sub: bl1, br1 = "", "" default: bl1, br1 = "(", ")" } if x.right.op == op_num || x.op < x.right.op { bl2, br2 = "", "" } else { bl2, br2 = "(", ")" } switch { case x.op == op_add: opstr = " + " case x.op == op_sub: opstr = " - " case x.op == op_mul: opstr = " * " case x.op == op_div: opstr = " / " } return bl1 + x.left.String() + br1 + opstr + bl2 + x.right.String() + br2 } func expr_eval(x *Expr) (f frac) { if x.op == op_num { return x.value } l, r := expr_eval(x.left), expr_eval(x.right) switch x.op { case op_add: f.num = l.num*r.denom + l.denom*r.num f.denom = l.denom * r.denom return case op_sub: f.num = l.num*r.denom - l.denom*r.num f.denom = l.denom * r.denom return case op_mul: f.num = l.num * r.num f.denom = l.denom * r.denom return case op_div: f.num = l.num * r.denom f.denom = l.denom * r.num return } return } func solve(ex_in []*Expr) bool { // only one expression left, meaning all numbers are arranged into // a binary tree, so evaluate and see if we get 24 if len(ex_in) == 1 { f := expr_eval(ex_in[0]) if f.denom != 0 && f.num == f.denom*goal { fmt.Println(ex_in[0].String()) return true } return false } var node Expr ex := make([]*Expr, len(ex_in)-1) // try to combine a pair of expressions into one, thus reduce // the list length by 1, and recurse down for i := range ex { copy(ex[i:len(ex)], ex_in[i+1:len(ex_in)]) ex[i] = &node for j := i + 1; j < len(ex_in); j++ { node.left = ex_in[i] node.right = ex_in[j] // try all 4 operators for o := op_add; o <= op_div; o++ { node.op = o if solve(ex) { return true } } // also - and / are not commutative, so swap arguments node.left = ex_in[j] node.right = ex_in[i] node.op = op_sub if solve(ex) { return true } node.op = op_div if solve(ex) { return true } if j < len(ex) { ex[j] = ex_in[j] } } ex[i] = ex_in[i] } return false } func main() { cards := make([]*Expr, n_cards) rand.Seed(time.Now().Unix()) for k := 0; k < 10; k++ { for i := 0; i < n_cards; i++ { cards[i] = &Expr{op_num, nil, nil, frac{rand.Intn(digit_range-1) + 1, 1}} fmt.Printf(" %d", cards[i].value.num) } fmt.Print(": ") if !solve(cards) { fmt.Println("No solution") } } }
4-rings or 4-squares puzzle
Go
Replace '''a, b, c, d, e, f,''' and '''g ''' with the decimal digits LOW ---> HIGH such that the sum of the letters inside of each of the four large squares add up to the same sum. +--------------+ +--------------+ | | | | | a | | e | | | | | | +---+------+---+ +---+---------+ | | | | | | | | | | b | | d | | f | | | | | | | | | | | | | | | | | | +----------+---+ +---+------+---+ | | c | | g | | | | | | | | | +--------------+ +-------------+ Show all output here. :* Show all solutions for each letter being unique with LOW=1 HIGH=7 :* Show all solutions for each letter being unique with LOW=3 HIGH=9 :* Show only the ''number'' of solutions when each letter can be non-unique LOW=0 HIGH=9 ;Related task: * [[Solve the no connection puzzle]]
package main import "fmt" func main(){ n, c := getCombs(1,7,true) fmt.Printf("%d unique solutions in 1 to 7\n",n) fmt.Println(c) n, c = getCombs(3,9,true) fmt.Printf("%d unique solutions in 3 to 9\n",n) fmt.Println(c) n, _ = getCombs(0,9,false) fmt.Printf("%d non-unique solutions in 0 to 9\n",n) } func getCombs(low,high int,unique bool) (num int,validCombs [][]int){ for a := low; a <= high; a++ { for b := low; b <= high; b++ { for c := low; c <= high; c++ { for d := low; d <= high; d++ { for e := low; e <= high; e++ { for f := low; f <= high; f++ { for g := low; g <= high; g++ { if validComb(a,b,c,d,e,f,g) { if !unique || isUnique(a,b,c,d,e,f,g) { num++ validCombs = append(validCombs,[]int{a,b,c,d,e,f,g}) } } } } } } } } } return } func isUnique(a,b,c,d,e,f,g int) (res bool) { data := make(map[int]int) data[a]++ data[b]++ data[c]++ data[d]++ data[e]++ data[f]++ data[g]++ return len(data) == 7 } func validComb(a,b,c,d,e,f,g int) bool{ square1 := a + b square2 := b + c + d square3 := d + e + f square4 := f + g return square1 == square2 && square2 == square3 && square3 == square4 }
99 bottles of beer
Go
Display the complete lyrics for the song: '''99 Bottles of Beer on the Wall'''. ;The beer song: The lyrics follow this form: ::: 99 bottles of beer on the wall ::: 99 bottles of beer ::: Take one down, pass it around ::: 98 bottles of beer on the wall ::: 98 bottles of beer on the wall ::: 98 bottles of beer ::: Take one down, pass it around ::: 97 bottles of beer on the wall ... and so on, until reaching '''0''' (zero). Grammatical support for ''1 bottle of beer'' is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). ;See also: * http://99-bottles-of-beer.net/ * [[:Category:99_Bottles_of_Beer]] * [[:Category:Programming language families]] * Wikipedia 99 bottles of beer
package main import ( "fmt" "math/rand" "strings" "time" ) func main() { rand.Seed(time.Now().UnixNano()) for i := 99; i > 0; i-- { fmt.Printf("%s %s %s\n", slur(numberName(i), i), pluralizeFirst(slur("bottle of", i), i), slur("beer on the wall", i)) fmt.Printf("%s %s %s\n", slur(numberName(i), i), pluralizeFirst(slur("bottle of", i), i), slur("beer", i)) fmt.Printf("%s %s %s\n", slur("take one", i), slur("down", i), slur("pass it around", i)) fmt.Printf("%s %s %s\n", slur(numberName(i-1), i), pluralizeFirst(slur("bottle of", i), i-1), slur("beer on the wall", i)) } } // adapted from Number names task func numberName(n int) string { switch { case n < 0: case n < 20: return small[n] case n < 100: t := tens[n/10] s := n % 10 if s > 0 { t += " " + small[s] } return t } return "" } var small = []string{"no", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"} var tens = []string{"ones", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"} // pluralize first word of s by adding an s, but only if n is not 1. func pluralizeFirst(s string, n int) string { if n == 1 { return s } w := strings.Fields(s) w[0] += "s" return strings.Join(w, " ") } // p is string to slur, d is drunkenness, from 0 to 99 func slur(p string, d int) string { // shuffle only interior letters a := []byte(p[1 : len(p)-1]) // adapted from Knuth shuffle task. // shuffle letters with probability d/100. for i := len(a) - 1; i >= 1; i-- { if rand.Intn(100) >= d { j := rand.Intn(i + 1) a[i], a[j] = a[j], a[i] } } // condense spaces w := strings.Fields(p[:1] + string(a) + p[len(p)-1:]) return strings.Join(w, " ") }
99 bottles of beer
Go!
Display the complete lyrics for the song: '''99 Bottles of Beer on the Wall'''. ;The beer song: The lyrics follow this form: ::: 99 bottles of beer on the wall ::: 99 bottles of beer ::: Take one down, pass it around ::: 98 bottles of beer on the wall ::: 98 bottles of beer on the wall ::: 98 bottles of beer ::: Take one down, pass it around ::: 97 bottles of beer on the wall ... and so on, until reaching '''0''' (zero). Grammatical support for ''1 bottle of beer'' is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). ;See also: * http://99-bottles-of-beer.net/ * [[:Category:99_Bottles_of_Beer]] * [[:Category:Programming language families]] * Wikipedia 99 bottles of beer
-- -- 99 Bottles of Beer in Go! -- John Knottenbelt -- -- Go! is a multi-paradigm programming language that is oriented -- to the needs of programming secure, production quality, agent -- based applications. -- -- http://www.doc.ic.ac.uk/~klc/dalt03.html -- main .. { include "sys:go/io.gof". include "sys:go/stdlib.gof". main() -> drink(99); stdout.outLine("Time to buy some more beer..."). drink(0) -> {}. drink(i) -> stdout.outLine( bottles(i) <> " on the wall,\n" <> bottles(i) <> ".\n" <> "take one down, pass it around,\n" <> bottles(i-1) <> " on the wall.\n"); drink(i-1). bottles(0) => "no bottles of beer". bottles(1) => "1 bottle of beer". bottles(i) => i^0 <> " bottles of beer". }
9 billion names of God the integer
Go
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a "name": :The integer 1 has 1 name "1". :The integer 2 has 2 names "1+1", and "2". :The integer 3 has 3 names "1+1+1", "2+1", and "3". :The integer 4 has 5 names "1+1+1+1", "2+1+1", "2+2", "3+1", "4". :The integer 5 has 7 names "1+1+1+1+1", "2+1+1+1", "2+2+1", "3+1+1", "3+2", "4+1", "5". ;Task Display the first 25 rows of a number triangle which begins: 1 1 1 1 1 1 1 2 1 1 1 2 2 1 1 1 3 3 2 1 1 Where row n corresponds to integer n, and each column C in row m from left to right corresponds to the number of names beginning with C. A function G(n) should return the sum of the n-th row. Demonstrate this function by displaying: G(23), G(123), G(1234), and G(12345). Optionally note that the sum of the n-th row P(n) is the integer partition function. Demonstrate this is equivalent to G(n) by displaying: P(23), P(123), P(1234), and P(12345). ;Extra credit If your environment is able, plot P(n) against n for n=1\ldots 999. ;Related tasks * [[Partition function P]]
package main import ( "fmt" "math/big" ) func main() { intMin := func(a, b int) int { if a < b { return a } else { return b } } var cache = [][]*big.Int{{big.NewInt(1)}} cumu := func(n int) []*big.Int { for y := len(cache); y <= n; y++ { row := []*big.Int{big.NewInt(0)} for x := 1; x <= y; x++ { cacheValue := cache[y-x][intMin(x, y-x)] row = append(row, big.NewInt(0).Add(row[len(row)-1], cacheValue)) } cache = append(cache, row) } return cache[n] } row := func(n int) { e := cumu(n) for i := 0; i < n; i++ { fmt.Printf(" %v ", (big.NewInt(0).Sub(e[i+1], e[i])).Text(10)) } fmt.Println() } fmt.Println("rows:") for x := 1; x < 11; x++ { row(x) } fmt.Println() fmt.Println("sums:") for _, num := range [...]int{23, 123, 1234, 12345} { r := cumu(num) fmt.Printf("%d %v\n", num, r[len(r)-1].Text(10)) } }
A+B
Go
'''A+B''' --- a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used. ;Task: Given two integers, '''A''' and '''B'''. Their sum needs to be calculated. ;Input data: Two integers are written in the input stream, separated by space(s): : (-1000 \le A,B \le +1000) ;Output data: The required output is one integer: the sum of '''A''' and '''B'''. ;Example: ::{|class="standard" ! input ! output |- | 2 2 | 4 |- | 3 2 | 5 |}
package main import "fmt" func main() { var a, b int fmt.Scan(&a, &b) fmt.Println(a + b) }
ABC problem
Go
You are given a collection of ABC blocks (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sides of the blocks. The sample collection of blocks: (B O) (X K) (D Q) (C P) (N A) (G T) (R E) (T G) (Q D) (F S) (J W) (H U) (V I) (A N) (O B) (E R) (F S) (L Y) (P C) (Z M) ;Task: Write a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. The rules are simple: ::# Once a letter on a block is used that block cannot be used again ::# The function should be case-insensitive ::# Show the output on this page for the following 7 words in the following example ;Example: >>> can_make_word("A") True >>> can_make_word("BARK") True >>> can_make_word("BOOK") False >>> can_make_word("TREAT") True >>> can_make_word("COMMON") False >>> can_make_word("SQUAD") True >>> can_make_word("CONFUSE") True
package main import ( "fmt" "strings" ) func newSpeller(blocks string) func(string) bool { bl := strings.Fields(blocks) return func(word string) bool { return r(word, bl) } } func r(word string, bl []string) bool { if word == "" { return true } c := word[0] | 32 for i, b := range bl { if c == b[0]|32 || c == b[1]|32 { bl[i], bl[0] = bl[0], b if r(word[1:], bl[1:]) == true { return true } bl[i], bl[0] = bl[0], bl[i] } } return false } func main() { sp := newSpeller( "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM") for _, word := range []string{ "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"} { fmt.Println(word, sp(word)) } }
ASCII art diagram converter
Go
Given the RFC 1035 message diagram from Section 4.1.1 (Header section format) as a string: http://www.ietf.org/rfc/rfc1035.txt +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ Where (every column of the table is 1 bit): ID is 16 bits QR = Query (0) or Response (1) Opcode = Four bits defining kind of query: 0: a standard query (QUERY) 1: an inverse query (IQUERY) 2: a server status request (STATUS) 3-15: reserved for future use AA = Authoritative Answer bit TC = Truncation bit RD = Recursion Desired bit RA = Recursion Available bit Z = Reserved RCODE = Response code QC = Question Count ANC = Answer Count AUC = Authority Count ADC = Additional Count Write a function, member function, class or template that accepts a similar multi-line string as input to define a data structure or something else able to decode or store a header with that specified bit structure. If your language has macros, introspection, code generation, or powerful enough templates, then accept such string at compile-time to define the header data structure statically. Such "Header" function or template should accept a table with 8, 16, 32 or 64 columns, and any number of rows. For simplicity the only allowed symbols to define the table are + - | (plus, minus, pipe), and whitespace. Lines of the input string composed just of whitespace should be ignored. Leading and trailing whitespace in the input string should be ignored, as well as before and after each table row. The box for each bit of the diagram takes four chars "+--+". The code should perform a little of validation of the input string, but for brevity a full validation is not required. Bonus: perform a thoroughly validation of the input string.
package main import ( "fmt" "log" "math/big" "strings" ) type result struct { name string size int start int end int } func (r result) String() string { return fmt.Sprintf("%-7s %2d %3d %3d", r.name, r.size, r.start, r.end) } func validate(diagram string) []string { var lines []string for _, line := range strings.Split(diagram, "\n") { line = strings.Trim(line, " \t") if line != "" { lines = append(lines, line) } } if len(lines) == 0 { log.Fatal("diagram has no non-empty lines!") } width := len(lines[0]) cols := (width - 1) / 3 if cols != 8 && cols != 16 && cols != 32 && cols != 64 { log.Fatal("number of columns should be 8, 16, 32 or 64") } if len(lines)%2 == 0 { log.Fatal("number of non-empty lines should be odd") } if lines[0] != strings.Repeat("+--", cols)+"+" { log.Fatal("incorrect header line") } for i, line := range lines { if i == 0 { continue } else if i%2 == 0 { if line != lines[0] { log.Fatal("incorrect separator line") } } else if len(line) != width { log.Fatal("inconsistent line widths") } else if line[0] != '|' || line[width-1] != '|' { log.Fatal("non-separator lines must begin and end with '|'") } } return lines } func decode(lines []string) []result { fmt.Println("Name Bits Start End") fmt.Println("======= ==== ===== ===") start := 0 width := len(lines[0]) var results []result for i, line := range lines { if i%2 == 0 { continue } line := line[1 : width-1] for _, name := range strings.Split(line, "|") { size := (len(name) + 1) / 3 name = strings.TrimSpace(name) res := result{name, size, start, start + size - 1} results = append(results, res) fmt.Println(res) start += size } } return results } func unpack(results []result, hex string) { fmt.Println("\nTest string in hex:") fmt.Println(hex) fmt.Println("\nTest string in binary:") bin := hex2bin(hex) fmt.Println(bin) fmt.Println("\nUnpacked:\n") fmt.Println("Name Size Bit pattern") fmt.Println("======= ==== ================") for _, res := range results { fmt.Printf("%-7s %2d %s\n", res.name, res.size, bin[res.start:res.end+1]) } } func hex2bin(hex string) string { z := new(big.Int) z.SetString(hex, 16) return fmt.Sprintf("%0*b", 4*len(hex), z) } func main() { const diagram = ` +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | QDCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ANCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | NSCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ARCOUNT | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ ` lines := validate(diagram) fmt.Println("Diagram after trimming whitespace and removal of blank lines:\n") for _, line := range lines { fmt.Println(line) } fmt.Println("\nDecoded:\n") results := decode(lines) hex := "78477bbf5496e12e1bf169a4" // test string unpack(results, hex) }
AVL tree
Go
{{wikipedia|AVL tree}} In computer science, an '''AVL tree''' is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log ''n'') time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed. AVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log ''n'') time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor m-balanced; that is, sibling nodes can have hugely differing numbers of descendants. ;Task: Implement an AVL tree in the language of choice, and provide at least basic operations. ;Related task [[Red_black_tree_sort]]
package avl // AVL tree adapted from Julienne Walker's presentation at // http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_avl.aspx. // This port uses similar indentifier names. // The Key interface must be supported by data stored in the AVL tree. type Key interface { Less(Key) bool Eq(Key) bool } // Node is a node in an AVL tree. type Node struct { Data Key // anything comparable with Less and Eq. Balance int // balance factor Link [2]*Node // children, indexed by "direction", 0 or 1. } // A little readability function for returning the opposite of a direction, // where a direction is 0 or 1. Go inlines this. // Where JW writes !dir, this code has opp(dir). func opp(dir int) int { return 1 - dir } // single rotation func single(root *Node, dir int) *Node { save := root.Link[opp(dir)] root.Link[opp(dir)] = save.Link[dir] save.Link[dir] = root return save } // double rotation func double(root *Node, dir int) *Node { save := root.Link[opp(dir)].Link[dir] root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)] save.Link[opp(dir)] = root.Link[opp(dir)] root.Link[opp(dir)] = save save = root.Link[opp(dir)] root.Link[opp(dir)] = save.Link[dir] save.Link[dir] = root return save } // adjust valance factors after double rotation func adjustBalance(root *Node, dir, bal int) { n := root.Link[dir] nn := n.Link[opp(dir)] switch nn.Balance { case 0: root.Balance = 0 n.Balance = 0 case bal: root.Balance = -bal n.Balance = 0 default: root.Balance = 0 n.Balance = bal } nn.Balance = 0 } func insertBalance(root *Node, dir int) *Node { n := root.Link[dir] bal := 2*dir - 1 if n.Balance == bal { root.Balance = 0 n.Balance = 0 return single(root, opp(dir)) } adjustBalance(root, dir, bal) return double(root, opp(dir)) } func insertR(root *Node, data Key) (*Node, bool) { if root == nil { return &Node{Data: data}, false } dir := 0 if root.Data.Less(data) { dir = 1 } var done bool root.Link[dir], done = insertR(root.Link[dir], data) if done { return root, true } root.Balance += 2*dir - 1 switch root.Balance { case 0: return root, true case 1, -1: return root, false } return insertBalance(root, dir), true } // Insert a node into the AVL tree. // Data is inserted even if other data with the same key already exists. func Insert(tree **Node, data Key) { *tree, _ = insertR(*tree, data) } func removeBalance(root *Node, dir int) (*Node, bool) { n := root.Link[opp(dir)] bal := 2*dir - 1 switch n.Balance { case -bal: root.Balance = 0 n.Balance = 0 return single(root, dir), false case bal: adjustBalance(root, opp(dir), -bal) return double(root, dir), false } root.Balance = -bal n.Balance = bal return single(root, dir), true } func removeR(root *Node, data Key) (*Node, bool) { if root == nil { return nil, false } if root.Data.Eq(data) { switch { case root.Link[0] == nil: return root.Link[1], false case root.Link[1] == nil: return root.Link[0], false } heir := root.Link[0] for heir.Link[1] != nil { heir = heir.Link[1] } root.Data = heir.Data data = heir.Data } dir := 0 if root.Data.Less(data) { dir = 1 } var done bool root.Link[dir], done = removeR(root.Link[dir], data) if done { return root, true } root.Balance += 1 - 2*dir switch root.Balance { case 1, -1: return root, true case 0: return root, false } return removeBalance(root, dir) } // Remove a single item from an AVL tree. // If key does not exist, function has no effect. func Remove(tree **Node, data Key) { *tree, _ = removeR(*tree, data) }
Abbreviations, automatic
Go from Kotlin
The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an easy way to add flexibility when specifying or using commands, sub-commands, options, etc. It would make a list of words easier to maintain (as words are added, changed, and/or deleted) if the minimum abbreviation length of that list could be automatically (programmatically) determined. For this task, use the list (below) of the days-of-the-week names that are expressed in about a hundred languages (note that there is a blank line in the list). Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag E_djele E_hene E_marte E_merkure E_enjte E_premte E_shtune Ehud Segno Maksegno Erob Hamus Arbe Kedame Al_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit Guiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat domingu llunes martes miercoles xueves vienres sabadu Bazar_gUnU Birinci_gUn Ckinci_gUn UcUncU_gUn DOrdUncU_gUn Bes,inci_gUn Altonco_gUn Igande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat Robi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar Nedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota Disul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn nedelia ponedelnik vtornik sriada chetvartak petak sabota sing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk Diumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte Dzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee dy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn Dimanch Lendi Madi Mekredi Jedi Vandredi Samdi nedjelja ponedjeljak utorak srijeda cxetvrtak petak subota nede^le ponde^li utery str^eda c^tvrtek patek sobota Sondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee s0ndag mandag tirsdag onsdag torsdag fredag l0rdag zondag maandag dinsdag woensdag donderdag vrijdag zaterdag Diman^co Lundo Mardo Merkredo ^Jaudo Vendredo Sabato pUhapaev esmaspaev teisipaev kolmapaev neljapaev reede laupaev Diu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata sunnudagur manadagur tysdaguy mikudagur hosdagur friggjadagur leygardagur Yek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh sunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai dimanche lundi mardi mercredi jeudi vendredi samedi Snein Moandei Tiisdei Woansdei Tonersdei Freed Sneon Domingo Segunda_feira Martes Mercores Joves Venres Sabado k'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag Kiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato ravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar popule po`akahi po`alua po`akolu po`aha po`alima po`aono Yom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat ravivara somavar mangalavar budhavara brahaspativar shukravara shanivar vasarnap hetfo kedd szerda csutortok pentek szombat Sunnudagur Manudagur +ridjudagur Midvikudagar Fimmtudagur FOstudagur Laugardagur sundio lundio mardio merkurdio jovdio venerdio saturdio Minggu Senin Selasa Rabu Kamis Jumat Sabtu Dominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato De_Domhnaigh De_Luain De_Mairt De_Ceadaoin De_ardaoin De_hAoine De_Sathairn domenica lunedi martedi mercoledi giovedi venerdi sabato Nichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi Il-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il Dies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni sve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien Sekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis Wangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi xing-_qi-_ri xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu Jedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam Jabot Manre Juje Wonje Taije Balaire Jarere geminrongo minomishi martes mierkoles misheushi bernashi mishabaro Ahad Isnin Selasa Rabu Khamis Jumaat Sabtu sphndag mandag tirsdag onsdag torsdag fredag lphrdag lo_dimenge lo_diluns lo_dimarc lo_dimercres lo_dijous lo_divendres lo_dissabte djadomingo djaluna djamars djarason djaweps djabierna djasabra Niedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota Domingo segunda-feire terca-feire quarta-feire quinta-feire sexta-feira sabado Domingo Lunes martes Miercoles Jueves Viernes Sabado Duminica Luni Mart'i Miercuri Joi Vineri Sambata voskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota Sunday Di-luain Di-mairt Di-ciadain Di-ardaoin Di-haoine Di-sathurne nedjelja ponedjeljak utorak sreda cxetvrtak petak subota Sontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo Iridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha- nedel^a pondelok utorok streda s^tvrtok piatok sobota Nedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota domingo lunes martes miercoles jueves viernes sabado sonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday Jumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi sondag mandag tisdag onsdag torsdag fredag lordag Linggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado Le-pai-jit Pai-it Pai-ji Pai-san Pai-si Pai-gO. Pai-lak wan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao Tshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso Pazar Pazartesi Sali Car,samba Per,sembe Cuma Cumartesi nedilya ponedilok vivtorok sereda chetver pyatnytsya subota Chu?_Nha.t Thu*_Hai Thu*_Ba Thu*_Tu* Thu*_Na'm Thu*_Sau Thu*_Ba?y dydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn Dibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw iCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo zuntik montik dinstik mitvokh donershtik fraytik shabes iSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo Dies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni Bazar_gUnU Bazar_aertaesi Caers,aenbae_axs,amo Caers,aenbae_gUnU CUmae_axs,amo CUmae_gUnU CUmae_Senbae Sun Moon Mars Mercury Jove Venus Saturn zondag maandag dinsdag woensdag donderdag vrijdag zaterdag KoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend Domingo Luns Terza_feira Corta_feira Xoves Venres Sabado Dies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum xing-_qi-_tian xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu djadomingu djaluna djamars djarason djaweps djabierne djasabra Killachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau ''Caveat: The list (above) most surely contains errors (or, at the least, differences) of what the actual (or true) names for the days-of-the-week.'' To make this Rosetta Code task page as small as possible, if processing the complete list, read the days-of-the-week from a file (that is created from the above list). Notes concerning the above list of words ::* each line has a list of days-of-the-week for a language, separated by at least one blank ::* the words on each line happen to be in order, from Sunday --> Saturday ::* most lines have words in mixed case and some have all manner of accented words and other characters ::* some words were translated to the nearest character that was available to ''code page'' '''437''' ::* the characters in the words are not restricted except that they may not have imbedded blanks ::* for this example, the use of an underscore ('''_''') was used to indicate a blank in a word ;Task: ::* The list of words (days of the week) needn't be verified/validated. ::* Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique. ::* A blank line (or a null line) should return a null string. ::* Process and show the output for at least the first '''five''' lines of the file. ::* Show all output here.
package main import( "bufio" "fmt" "os" "strings" ) func distinctStrings(strs []string) []string { len := len(strs) set := make(map[string]bool, len) distinct := make([]string, 0, len) for _, str := range strs { if !set[str] { distinct = append(distinct, str) set[str] = true } } return distinct } func takeRunes(s string, n int) string { i := 0 for j := range s { if i == n { return s[:j] } i++ } return s } func main() { file, err := os.Open("days_of_week.txt") if err != nil { fmt.Println("Unable to open file.") return } defer file.Close() reader := bufio.NewReader(file) lineCount := 0 for { line, err := reader.ReadString('\n') if err != nil { // end of file reached return } line = strings.TrimSpace(line) lineCount++ if line == "" { fmt.Println() continue } days := strings.Fields(line) daysLen := len(days) if (len(days) != 7) { fmt.Println("There aren't 7 days in line", lineCount) return } if len(distinctStrings(days)) != 7 { // implies some days have the same name fmt.Println(" ∞ ", line) continue } for abbrevLen := 1; ; abbrevLen++ { abbrevs := make([]string, daysLen) for i := 0; i < daysLen; i++ { abbrevs[i] = takeRunes(days[i], abbrevLen) } if len(distinctStrings(abbrevs)) == 7 { fmt.Printf("%2d %s\n", abbrevLen, line) break } } } }
Abbreviations, easy
Go from Kotlin
This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]]. For this task, the following ''command table'' will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up Notes concerning the above ''command table'': ::* it can be thought of as one long literal string (with blanks at end-of-lines) ::* it may have superfluous blanks ::* it may be in any case (lower/upper/mixed) ::* the order of the words in the ''command table'' must be preserved as shown ::* the user input(s) may be in any case (upper/lower/mixed) ::* commands will be restricted to the Latin alphabet (A --> Z, a --> z) ::* A valid abbreviation is a word that has: :::* at least the minimum length of the number of capital letters of the word in the ''command table'' :::* compares equal (regardless of case) to the leading characters of the word in the ''command table'' :::* a length not longer than the word in the ''command table'' ::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer''' ::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer''' ::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters ::::* Any word longer than five characters can't be an abbreviation for '''ALTer''' ::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay''' ::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted ;Task: ::* The command table needn't be verified/validated. ::* Write a function to validate if the user "words" (given as input) are valid (in the ''command table''). ::* If the word is valid, then return the full uppercase version of that "word". ::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters). ::* A blank input (or a null input) should return a null string. ::* Show all output here. ;An example test case to be used for this task: For a user string of: riG rePEAT copies put mo rest types fup. 6 poweRin the computer program should return the string: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
package main import ( "fmt" "strings" ) var table = "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy " + "COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find " + "NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput " + "Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO " + "MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT " + "READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT " + "RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up " func validate(commands, words []string, minLens []int) []string { results := make([]string, 0) if len(words) == 0 { return results } for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func main() { table = strings.TrimSpace(table) commands := strings.Fields(table) clen := len(commands) minLens := make([]int, clen) for i := 0; i < clen; i++ { count := 0 for _, c := range commands[i] { if c >= 'A' && c <= 'Z' { count++ } } minLens[i] = count } sentence := "riG rePEAT copies put mo rest types fup. 6 poweRin" words := strings.Fields(sentence) results := validate(commands, words, minLens) fmt.Print("user words: ") for j := 0; j < len(words); j++ { fmt.Printf("%-*s ", len(results[j]), words[j]) } fmt.Print("\nfull words: ") fmt.Println(strings.Join(results, " ")) }
Abbreviations, simple
Go from Kotlin
The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an easy way to add flexibility when specifying or using commands, sub-commands, options, etc. For this task, the following ''command table'' will be used: add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 Notes concerning the above ''command table'': ::* it can be thought of as one long literal string (with blanks at end-of-lines) ::* it may have superfluous blanks ::* it may be in any case (lower/upper/mixed) ::* the order of the words in the ''command table'' must be preserved as shown ::* the user input(s) may be in any case (upper/lower/mixed) ::* commands will be restricted to the Latin alphabet (A --> Z, a --> z) ::* a command is followed by an optional number, which indicates the minimum abbreviation ::* A valid abbreviation is a word that has: :::* at least the minimum length of the word's minimum number in the ''command table'' :::* compares equal (regardless of case) to the leading characters of the word in the ''command table'' :::* a length not longer than the word in the ''command table'' ::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3''' ::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3''' ::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters ::::* Any word longer than five characters can't be an abbreviation for '''ALTER''' ::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1''' ::* if there isn't a number after the command, then there isn't an abbreviation permitted ;Task: ::* The command table needn't be verified/validated. ::* Write a function to validate if the user "words" (given as input) are valid (in the ''command table''). ::* If the word is valid, then return the full uppercase version of that "word". ::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters). ::* A blank input (or a null input) should return a null string. ::* Show all output here. ;An example test case to be used for this task: For a user string of: riG rePEAT copies put mo rest types fup. 6 poweRin the computer program should return the string: RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT
package main import ( "io" "os" "strconv" "strings" "text/tabwriter" ) func readTable(table string) ([]string, []int) { fields := strings.Fields(table) var commands []string var minLens []int for i, max := 0, len(fields); i < max; { cmd := fields[i] cmdLen := len(cmd) i++ if i < max { num, err := strconv.Atoi(fields[i]) if err == nil && 1 <= num && num < cmdLen { cmdLen = num i++ } } commands = append(commands, cmd) minLens = append(minLens, cmdLen) } return commands, minLens } func validateCommands(commands []string, minLens []int, words []string) []string { var results []string for _, word := range words { matchFound := false wlen := len(word) for i, command := range commands { if minLens[i] == 0 || wlen < minLens[i] || wlen > len(command) { continue } c := strings.ToUpper(command) w := strings.ToUpper(word) if strings.HasPrefix(c, w) { results = append(results, c) matchFound = true break } } if !matchFound { results = append(results, "*error*") } } return results } func printResults(words []string, results []string) { wr := tabwriter.NewWriter(os.Stdout, 0, 1, 1, ' ', 0) io.WriteString(wr, "user words:") for _, word := range words { io.WriteString(wr, "\t"+word) } io.WriteString(wr, "\n") io.WriteString(wr, "full words:\t"+strings.Join(results, "\t")+"\n") wr.Flush() } func main() { const table = "" + "add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 " + "compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate " + "3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 " + "forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load " + "locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 " + "msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 " + "refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left " + "2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 " const sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin" commands, minLens := readTable(table) words := strings.Fields(sentence) results := validateCommands(commands, minLens, words) printResults(words, results) }
Abelian sandpile model
Go from Rust
{{wikipedia|Abelian sandpile model}} Implement the '''Abelian sandpile model''' also known as '''Bak-Tang-Wiesenfeld model'''. Its history, mathematical definition and properties can be found under its wikipedia article. The task requires the creation of a 2D grid of arbitrary size on which "piles of sand" can be placed. Any "pile" that has 4 or more sand particles on it ''collapses'', resulting in '''four particles being subtracted from the pile''' and '''distributed among its neighbors.''' It is recommended to display the output in some kind of image format, as terminal emulators are usually too small to display images larger than a few dozen characters tall. As an example of how to accomplish this, see the Bitmap/Write a PPM file task. Examples up to 2^30, wow! javascript running on web '''Examples:''' 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 4 0 0 -> 0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 6 0 0 -> 0 1 2 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 2 1 2 0 0 0 16 0 0 -> 1 1 0 1 1 0 0 0 0 0 0 2 1 2 0 0 0 0 0 0 0 0 1 0 0
package main import ( "fmt" "log" "os" "strings" ) const dim = 16 // image size func check(err error) { if err != nil { log.Fatal(err) } } // Outputs the result to the terminal using UTF-8 block characters. func drawPile(pile [][]uint) { chars:= []rune(" ░▓█") for _, row := range pile { line := make([]rune, len(row)) for i, elem := range row { if elem > 3 { // only possible when algorithm not yet completed. elem = 3 } line[i] = chars[elem] } fmt.Println(string(line)) } } // Creates a .ppm file in the current directory, which contains // a colored image of the pile. func writePile(pile [][]uint) { file, err := os.Create("output.ppm") check(err) defer file.Close() // Write the signature, image dimensions and maximum color value to the file. fmt.Fprintf(file, "P3\n%d %d\n255\n", dim, dim) bcolors := []string{"125 0 25 ", "125 80 0 ", "186 118 0 ", "224 142 0 "} var line strings.Builder for _, row := range pile { for _, elem := range row { line.WriteString(bcolors[elem]) } file.WriteString(line.String() + "\n") line.Reset() } } // Main part of the algorithm, a simple, recursive implementation of the model. func handlePile(x, y uint, pile [][]uint) { if pile[y][x] >= 4 { pile[y][x] -= 4 // Check each neighbor, whether they have enough "sand" to collapse and if they do, // recursively call handlePile on them. if y > 0 { pile[y-1][x]++ if pile[y-1][x] >= 4 { handlePile(x, y-1, pile) } } if x > 0 { pile[y][x-1]++ if pile[y][x-1] >= 4 { handlePile(x-1, y, pile) } } if y < dim-1 { pile[y+1][x]++ if pile[y+1][x] >= 4 { handlePile(x, y+1, pile) } } if x < dim-1 { pile[y][x+1]++ if pile[y][x+1] >= 4 { handlePile(x+1, y, pile) } } // Uncomment this line to show every iteration of the program. // Not recommended with large input values. // drawPile(pile) // Finally call the function on the current cell again, // in case it had more than 4 particles. handlePile(x, y, pile) } } func main() { // Create 2D grid and set size using the 'dim' constant. pile := make([][]uint, dim) for i := 0; i < dim; i++ { pile[i] = make([]uint, dim) } // Place some sand particles in the center of the grid and start the algorithm. hdim := uint(dim/2 - 1) pile[hdim][hdim] = 16 handlePile(hdim, hdim, pile) drawPile(pile) // Uncomment this to save the final image to a file // after the recursive algorithm has ended. // writePile(pile) }
Abelian sandpile model/Identity
Go from Wren
Our sandpiles are based on a 3 by 3 rectangular grid giving nine areas that contain a number from 0 to 3 inclusive. (The numbers are said to represent grains of sand in each area of the sandpile). E.g. s1 = 1 2 0 2 1 1 0 1 3 and s2 = 2 1 3 1 0 1 0 1 0 Addition on sandpiles is done by adding numbers in corresponding grid areas, so for the above: 1 2 0 2 1 3 3 3 3 s1 + s2 = 2 1 1 + 1 0 1 = 3 1 2 0 1 3 0 1 0 0 2 3 If the addition would result in more than 3 "grains of sand" in any area then those areas cause the whole sandpile to become "unstable" and the sandpile areas are "toppled" in an "avalanche" until the "stable" result is obtained. Any unstable area (with a number >= 4), is "toppled" by loosing one grain of sand to each of its four horizontal or vertical neighbours. Grains are lost at the edge of the grid, but otherwise increase the number in neighbouring cells by one, whilst decreasing the count in the toppled cell by four in each toppling. A toppling may give an adjacent area more than four grains of sand leading to a chain of topplings called an "avalanche". E.g. 4 3 3 0 4 3 1 0 4 1 1 0 2 1 0 3 1 2 ==> 4 1 2 ==> 4 2 2 ==> 4 2 3 ==> 0 3 3 0 2 3 0 2 3 0 2 3 0 2 3 1 2 3 The final result is the stable sandpile on the right. '''Note:''' The order in which cells are toppled does not affect the final result. ;Task: * Create a class or datastructure and functions to represent and operate on sandpiles. * Confirm the result of the avalanche of topplings shown above * Confirm that s1 + s2 == s2 + s1 # Show the stable results * If s3 is the sandpile with number 3 in every grid area, and s3_id is the following sandpile: 2 1 2 1 0 1 2 1 2 * Show that s3 + s3_id == s3 * Show that s3_id + s3_id == s3_id Show confirming output here, with your examples. ;References: * https://www.youtube.com/watch?v=1MtEUErz7Gg * https://en.wikipedia.org/wiki/Abelian_sandpile_model
package main import ( "fmt" "strconv" "strings" ) type sandpile struct{ a [9]int } var neighbors = [][]int{ {1, 3}, {0, 2, 4}, {1, 5}, {0, 4, 6}, {1, 3, 5, 7}, {2, 4, 8}, {3, 7}, {4, 6, 8}, {5, 7}, } // 'a' is in row order func newSandpile(a [9]int) *sandpile { return &sandpile{a} } func (s *sandpile) plus(other *sandpile) *sandpile { b := [9]int{} for i := 0; i < 9; i++ { b[i] = s.a[i] + other.a[i] } return &sandpile{b} } func (s *sandpile) isStable() bool { for _, e := range s.a { if e > 3 { return false } } return true } // just topples once so we can observe intermediate results func (s *sandpile) topple() { for i := 0; i < 9; i++ { if s.a[i] > 3 { s.a[i] -= 4 for _, j := range neighbors[i] { s.a[j]++ } return } } } func (s *sandpile) String() string { var sb strings.Builder for i := 0; i < 3; i++ { for j := 0; j < 3; j++ { sb.WriteString(strconv.Itoa(s.a[3*i+j]) + " ") } sb.WriteString("\n") } return sb.String() } func main() { fmt.Println("Avalanche of topplings:\n") s4 := newSandpile([9]int{4, 3, 3, 3, 1, 2, 0, 2, 3}) fmt.Println(s4) for !s4.isStable() { s4.topple() fmt.Println(s4) } fmt.Println("Commutative additions:\n") s1 := newSandpile([9]int{1, 2, 0, 2, 1, 1, 0, 1, 3}) s2 := newSandpile([9]int{2, 1, 3, 1, 0, 1, 0, 1, 0}) s3_a := s1.plus(s2) for !s3_a.isStable() { s3_a.topple() } s3_b := s2.plus(s1) for !s3_b.isStable() { s3_b.topple() } fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s1, s2, s3_a) fmt.Printf("and\n\n%s\nplus\n\n%s\nalso equals\n\n%s\n", s2, s1, s3_b) fmt.Println("Addition of identity sandpile:\n") s3 := newSandpile([9]int{3, 3, 3, 3, 3, 3, 3, 3, 3}) s3_id := newSandpile([9]int{2, 1, 2, 1, 0, 1, 2, 1, 2}) s4 = s3.plus(s3_id) for !s4.isStable() { s4.topple() } fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s\n", s3, s3_id, s4) fmt.Println("Addition of identities:\n") s5 := s3_id.plus(s3_id) for !s5.isStable() { s5.topple() } fmt.Printf("%s\nplus\n\n%s\nequals\n\n%s", s3_id, s3_id, s5) }
Abundant odd numbers
Go
An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''', or, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''. ;E.G.: '''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n'''); or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n'''). Abundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers. To make things more interesting, this task is specifically about finding ''odd abundant numbers''. ;Task *Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum. *Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum. *Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum. ;References: :* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n) :* American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)
package main import ( "fmt" "strconv" ) func divisors(n int) []int { divs := []int{1} divs2 := []int{} for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs = append(divs, i) if i != j { divs2 = append(divs2, j) } } } for i := len(divs2) - 1; i >= 0; i-- { divs = append(divs, divs2[i]) } return divs } func sum(divs []int) int { tot := 0 for _, div := range divs { tot += div } return tot } func sumStr(divs []int) string { s := "" for _, div := range divs { s += strconv.Itoa(div) + " + " } return s[0 : len(s)-3] } func abundantOdd(searchFrom, countFrom, countTo int, printOne bool) int { count := countFrom n := searchFrom for ; count < countTo; n += 2 { divs := divisors(n) if tot := sum(divs); tot > n { count++ if printOne && count < countTo { continue } s := sumStr(divs) if !printOne { fmt.Printf("%2d. %5d < %s = %d\n", count, n, s, tot) } else { fmt.Printf("%d < %s = %d\n", n, s, tot) } } } return n } func main() { const max = 25 fmt.Println("The first", max, "abundant odd numbers are:") n := abundantOdd(1, 0, 25, false) fmt.Println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) fmt.Println("\nThe first abundant odd number above one billion is:") abundantOdd(1e9+1, 0, 1, true) }
Accumulator factory
Go
{{requires|Mutable State}} A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created). ;Rules: The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text''). :Before you submit an example, make sure the function :# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used :# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)'' :# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)'' :# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)'' :# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)'' : E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'': :: x = foo(1); x(5); foo(3); print x(2.3); : It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)'' ;Task: Create a function that implements the described rules. It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
package main import "fmt" func accumulator(sum interface{}) func(interface{}) interface{} { return func(nv interface{}) interface{} { switch s := sum.(type) { case int: switch n := nv.(type) { case int: sum = s + n case float64: sum = float64(s) + n } case float64: switch n := nv.(type) { case int: sum = s + float64(n) case float64: sum = s + n } default: sum = nv } return sum } } func main() { x := accumulator(1) x(5) accumulator(3) fmt.Println(x(2.3)) }
Achilles numbers
Go from Wren
{{Wikipedia|Achilles number}} An '''Achilles number''' is a number that is powerful but imperfect. ''Named after Achilles, a hero of the Trojan war, who was also powerful but imperfect.'' A positive integer '''n''' is a powerful number if, for every prime factor '''p''' of '''n''', '''p2''' is also a divisor. In other words, every prime factor appears at least squared in the factorization. All '''Achilles numbers''' are powerful. However, not all powerful numbers are '''Achilles numbers''': only those that cannot be represented as '''mk''', where '''m''' and '''k''' are positive integers greater than '''1'''. A '''''strong'' Achilles number''' is an '''Achilles number''' whose '''Euler totient ()''' is also an '''Achilles number'''. ;E.G. '''108''' is a powerful number. Its prime factorization is '''22 x 33''', and thus its prime factors are '''2''' and '''3'''. Both '''22 = 4''' and '''32 = 9''' are divisors of '''108'''. However, '''108''' cannot be represented as '''mk''', where '''m''' and '''k''' are positive integers greater than '''1''', so '''108''' is an '''Achilles number'''. '''360''' is ''not'' an '''Achilles number''' because it is not powerful. One of its prime factors is '''5''' but '''360''' is not divisible by '''52 = 25'''. Finally, '''784''' is ''not'' an '''Achilles number'''. It is a powerful number, because not only are '''2''' and '''7''' its only prime factors, but also '''22 = 4''' and '''72 = 49''' are divisors of it. Nonetheless, it is a perfect power; its square root is an even integer, so it is ''not'' an '''Achilles number'''. '''500 = 22 x 53''' is a '''''strong'' Achilles number''' as its Euler totient, '''(500)''', is '''200 = 23 x 52''' which is ''also'' an '''Achilles number'''. ;Task * Find and show the first 50 '''Achilles numbers'''. * Find and show at least the first 20 '''''strong'' Achilles numbers'''. * For at least 2 through 5, show the count of '''Achilles numbers''' with that many digits. ;See also ;* Wikipedia: Achilles number ;* OEIS:A052486 - Achilles numbers - powerful but imperfect numbers ;* OEIS:A194085 - Strong Achilles numbers: Achilles numbers m such that phi(m) is also an Achilles number ;* Related task: Powerful numbers ;* Related task: Totient function
package main import ( "fmt" "math" "sort" ) func totient(n int) int { tot := n i := 2 for i*i <= n { if n%i == 0 { for n%i == 0 { n /= i } tot -= tot / i } if i == 2 { i = 1 } i += 2 } if n > 1 { tot -= tot / n } return tot } var pps = make(map[int]bool) func getPerfectPowers(maxExp int) { upper := math.Pow(10, float64(maxExp)) for i := 2; i <= int(math.Sqrt(upper)); i++ { fi := float64(i) p := fi for { p *= fi if p >= upper { break } pps[int(p)] = true } } } func getAchilles(minExp, maxExp int) map[int]bool { lower := math.Pow(10, float64(minExp)) upper := math.Pow(10, float64(maxExp)) achilles := make(map[int]bool) for b := 1; b <= int(math.Cbrt(upper)); b++ { b3 := b * b * b for a := 1; a <= int(math.Sqrt(upper)); a++ { p := b3 * a * a if p >= int(upper) { break } if p >= int(lower) { if _, ok := pps[p]; !ok { achilles[p] = true } } } } return achilles } func main() { maxDigits := 15 getPerfectPowers(maxDigits) achillesSet := getAchilles(1, 5) // enough for first 2 parts achilles := make([]int, len(achillesSet)) i := 0 for k := range achillesSet { achilles[i] = k i++ } sort.Ints(achilles) fmt.Println("First 50 Achilles numbers:") for i = 0; i < 50; i++ { fmt.Printf("%4d ", achilles[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println("\nFirst 30 strong Achilles numbers:") var strongAchilles []int count := 0 for n := 0; count < 30; n++ { tot := totient(achilles[n]) if _, ok := achillesSet[tot]; ok { strongAchilles = append(strongAchilles, achilles[n]) count++ } } for i = 0; i < 30; i++ { fmt.Printf("%5d ", strongAchilles[i]) if (i+1)%10 == 0 { fmt.Println() } } fmt.Println("\nNumber of Achilles numbers with:") for d := 2; d <= maxDigits; d++ { ac := len(getAchilles(d-1, d)) fmt.Printf("%2d digits: %d\n", d, ac) } }
Aliquot sequence classifications
Go from Kotlin
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the [[Proper divisors]] of the previous term. :* If the terms eventually reach 0 then the series for K is said to '''terminate'''. :There are several classifications for non termination: :* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''. :* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''. :* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''. :Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions... :* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''. :* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''. :And finally: :* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. ;Task: # Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above. # Use it to display the classification and sequences of the numbers one to ten inclusive. # Use it to show the classification and sequences of the following integers, in order: :: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080. Show all output on this page. ;Related tasks: * [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence). * [[Proper divisors]] * [[Amicable pairs]]
package main import ( "fmt" "math" "strings" ) const threshold = uint64(1) << 47 func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 } func contains(s []uint64, search uint64) bool { return indexOf(s, search) > -1 } func maxOf(i1, i2 int) int { if i1 > i2 { return i1 } return i2 } func sumProperDivisors(n uint64) uint64 { if n < 2 { return 0 } sqrt := uint64(math.Sqrt(float64(n))) sum := uint64(1) for i := uint64(2); i <= sqrt; i++ { if n % i != 0 { continue } sum += i + n / i } if sqrt * sqrt == n { sum -= sqrt } return sum } func classifySequence(k uint64) ([]uint64, string) { if k == 0 { panic("Argument must be positive.") } last := k var seq []uint64 seq = append(seq, k) for { last = sumProperDivisors(last) seq = append(seq, last) n := len(seq) aliquot := "" switch { case last == 0: aliquot = "Terminating" case n == 2 && last == k: aliquot = "Perfect" case n == 3 && last == k: aliquot = "Amicable" case n >= 4 && last == k: aliquot = fmt.Sprintf("Sociable[%d]", n - 1) case last == seq[n - 2]: aliquot = "Aspiring" case contains(seq[1 : maxOf(1, n - 2)], last): aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last)) case n == 16 || last > threshold: aliquot = "Non-Terminating" } if aliquot != "" { return seq, aliquot } } } func joinWithCommas(seq []uint64) string { res := fmt.Sprint(seq) res = strings.Replace(res, " ", ", ", -1) return res } func main() { fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n") for k := uint64(1); k <= 10; k++ { seq, aliquot := classifySequence(k) fmt.Printf("%2d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() s := []uint64{ 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, } for _, k := range s { seq, aliquot := classifySequence(k) fmt.Printf("%7d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) } fmt.Println() k := uint64(15355717786080) seq, aliquot := classifySequence(k) fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) }
Almkvist-Giullera formula for pi
Go from Wren
The Almkvist-Giullera formula for calculating 1/p2 is based on the Calabi-Yau differential equations of order 4 and 5, which were originally used to describe certain manifolds in string theory. The formula is: ::::: 1/p2 = (25/3) 0 ((6n)! / (n!6))(532n2 + 126n + 9) / 10002n+1 This formula can be used to calculate the constant p-2, and thus to calculate p. Note that, because the product of all terms but the power of 1000 can be calculated as an integer, the terms in the series can be separated into a large integer term: ::::: (25) (6n)! (532n2 + 126n + 9) / (3(n!)6) (***) multiplied by a negative integer power of 10: ::::: 10-(6n + 3) ;Task: :* Print the integer portions (the starred formula, which is without the power of 1000 divisor) of the first 10 terms of the series. :* Use the complete formula to calculate and print p to 70 decimal digits of precision. ;Reference: :* Gert Almkvist and Jesus Guillera, Ramanujan-like series for 1/p2 and string theory, Experimental Mathematics, 21 (2012), page 2, formula 1.
package main import ( "fmt" "math/big" "strings" ) func factorial(n int64) *big.Int { var z big.Int return z.MulRange(1, n) } var one = big.NewInt(1) var three = big.NewInt(3) var six = big.NewInt(6) var ten = big.NewInt(10) var seventy = big.NewInt(70) func almkvistGiullera(n int64, print bool) *big.Rat { t1 := big.NewInt(32) t1.Mul(factorial(6*n), t1) t2 := big.NewInt(532*n*n + 126*n + 9) t3 := new(big.Int) t3.Exp(factorial(n), six, nil) t3.Mul(t3, three) ip := new(big.Int) ip.Mul(t1, t2) ip.Quo(ip, t3) pw := 6*n + 3 t1.SetInt64(pw) tm := new(big.Rat).SetFrac(ip, t1.Exp(ten, t1, nil)) if print { fmt.Printf("%d %44d %3d %-35s\n", n, ip, -pw, tm.FloatString(33)) } return tm } func main() { fmt.Println("N Integer Portion Pow Nth Term (33 dp)") fmt.Println(strings.Repeat("-", 89)) for n := int64(0); n < 10; n++ { almkvistGiullera(n, true) } sum := new(big.Rat) prev := new(big.Rat) pow70 := new(big.Int).Exp(ten, seventy, nil) prec := new(big.Rat).SetFrac(one, pow70) n := int64(0) for { term := almkvistGiullera(n, false) sum.Add(sum, term) z := new(big.Rat).Sub(sum, prev) z.Abs(z) if z.Cmp(prec) < 0 { break } prev.Set(sum) n++ } sum.Inv(sum) pi := new(big.Float).SetPrec(256).SetRat(sum) pi.Sqrt(pi) fmt.Println("\nPi to 70 decimal places is:") fmt.Println(pi.Text('f', 70)) }
Amb
Go
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure. Problems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. Essentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other "parallel universes" somehow go away. Amb called with no arguments fails. For simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four. A pseudo-code program which satisfies this constraint might look like: let x = Amb(1, 2, 3) let y = Amb(7, 6, 4, 5) Amb(x * y = 8) print x, y The output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success. Alternatively, failure could be represented using strictly Amb(): unless x * y = 8 do Amb() Or else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints: let x = Ambsel(1, 2, 3) let y = Ambsel(4, 5, 6) Ambassert(x * y = 8) print x, y where Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value. The task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence: #"the" "that" "a" #"frog" "elephant" "thing" #"walked" "treaded" "grows" #"slowly" "quickly" The constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor. The only successful sentence is "that thing grows slowly"; other combinations do not satisfy the constraint and thus fail. The goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.
package main import ( "fmt" "sync" ) func ambStrings(ss []string) chan []string { c := make(chan []string) go func() { for _, s := range ss { c <- []string{s} } close(c) }() return c } func ambChain(ss []string, cIn chan []string) chan []string { cOut := make(chan []string) go func() { var w sync.WaitGroup for chain := range cIn { w.Add(1) go func(chain []string) { for s1 := range ambStrings(ss) { if s1[0][len(s1[0])-1] == chain[0][0] { cOut <- append(s1, chain...) } } w.Done() }(chain) } w.Wait() close(cOut) }() return cOut } func main() { s1 := []string{"the", "that", "a"} s2 := []string{"frog", "elephant", "thing"} s3 := []string{"walked", "treaded", "grows"} s4 := []string{"slowly", "quickly"} c := ambChain(s1, ambChain(s2, ambChain(s3, ambStrings(s4)))) for s := range c { fmt.Println(s) } }
Anagrams/Deranged anagrams
Go
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words. ;Task Use the word list at unixdict to find and display the longest deranged anagram. ;Related * [[Permutations/Derangements]] * Best shuffle {{Related tasks/Word plays}}
package main import ( "fmt" "io/ioutil" "strings" "sort" ) func deranged(a, b string) bool { if len(a) != len(b) { return false } for i := range(a) { if a[i] == b[i] { return false } } return true } func main() { /* read the whole thing in. how big can it be? */ buf, _ := ioutil.ReadFile("unixdict.txt") words := strings.Split(string(buf), "\n") m := make(map[string] []string) best_len, w1, w2 := 0, "", "" for _, w := range(words) { // don't bother: too short to beat current record if len(w) <= best_len { continue } // save strings in map, with sorted string as key letters := strings.Split(w, "") sort.Strings(letters) k := strings.Join(letters, "") if _, ok := m[k]; !ok { m[k] = []string { w } continue } for _, c := range(m[k]) { if deranged(w, c) { best_len, w1, w2 = len(w), c, w break } } m[k] = append(m[k], w) } fmt.Println(w1, w2, ": Length", best_len) }
Angle difference between two bearings
Go
Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings] ;Task: Find the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. Input bearings are expressed in the range '''-180''' to '''+180''' degrees. The result is also expressed in the range '''-180''' to '''+180''' degrees. Compute the angle for the following pairs: * 20 degrees ('''b1''') and 45 degrees ('''b2''') * -45 and 45 * -85 and 90 * -95 and 90 * -45 and 125 * -45 and 145 * 29.4803 and -88.6381 * -78.3251 and -159.036 ;Optional extra: Allow the input bearings to be any (finite) value. ;Test cases: * -70099.74233810938 and 29840.67437876723 * -165313.6666297357 and 33693.9894517456 * 1174.8380510598456 and -154146.66490124757 * 60175.77306795546 and 42213.07192354373
package main import "fmt" type bearing float64 var testCases = []struct{ b1, b2 bearing }{ {20, 45}, {-45, 45}, {-85, 90}, {-95, 90}, {-45, 125}, {-45, 145}, {29.4803, -88.6381}, {-78.3251, -159.036}, } func main() { for _, tc := range testCases { fmt.Println(tc.b2.Sub(tc.b1)) } } func (b2 bearing) Sub(b1 bearing) bearing { switch d := b2 - b1; { case d < -180: return d + 360 case d > 180: return d - 360 default: return d } }
Anti-primes
Go
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. ;Task: Generate and show here, the first twenty anti-primes. ;Related tasks: :* [[Factors of an integer]] :* [[Sieve of Eratosthenes]]
package main import "fmt" func countDivisors(n int) int { if n < 2 { return 1 } count := 2 // 1 and n for i := 2; i <= n/2; i++ { if n%i == 0 { count++ } } return count } func main() { fmt.Println("The first 20 anti-primes are:") maxDiv := 0 count := 0 for n := 1; count < 20; n++ { d := countDivisors(n) if d > maxDiv { fmt.Printf("%d ", n) maxDiv = d count++ } } fmt.Println() }
Apply a digital filter (direct form II transposed)
Go
Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [https://ccrma.stanford.edu/~jos/fp/Transposed_Direct_Forms.html] ;Task: Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667] The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589] ;See also: [Wikipedia on Butterworth filters]
package main import "fmt" type filter struct { b, a []float64 } func (f filter) filter(in []float64) []float64 { out := make([]float64, len(in)) s := 1. / f.a[0] for i := range in { tmp := 0. b := f.b if i+1 < len(b) { b = b[:i+1] } for j, bj := range b { tmp += bj * in[i-j] } a := f.a[1:] if i < len(a) { a = a[:i] } for j, aj := range a { tmp -= aj * out[i-j-1] } out[i] = tmp * s } return out } //Constants for a Butterworth filter (order 3, low pass) var bwf = filter{ a: []float64{1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17}, b: []float64{0.16666667, 0.5, 0.5, 0.16666667}, } var sig = []float64{ -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589, } func main() { for _, v := range bwf.filter(sig) { fmt.Printf("%9.6f\n", v) } }
Approximate equality
Go
Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the difference in floating point calculations between different language implementations becomes significant. For example, a difference between '''32''' bit and '''64''' bit floating point calculations may appear by about the 8th significant digit in base 10 arithmetic. ;Task: Create a function which returns true if two floating point numbers are approximately equal. The function should allow for differences in the magnitude of numbers, so that, for example, '''100000000000000.01''' may be approximately equal to '''100000000000000.011''', even though '''100.01''' is not approximately equal to '''100.011'''. If the language has such a feature in its standard library, this may be used instead of a custom function. Show the function results with comparisons on the following pairs of values: :# 100000000000000.01, 100000000000000.011 (note: should return ''true'') :# 100.01, 100.011 (note: should return ''false'') :# 10000000000000.001 / 10000.0, 1000000000.0000001000 :# 0.001, 0.0010000001 :# 0.000000000000000000000101, 0.0 :# sqrt(2) * sqrt(2), 2.0 :# -sqrt(2) * sqrt(2), -2.0 :# 3.14159265358979323846, 3.14159265358979324 Answers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution. __TOC__
package main import ( "fmt" "log" "math/big" ) func max(a, b *big.Float) *big.Float { if a.Cmp(b) > 0 { return a } return b } func isClose(a, b *big.Float) bool { relTol := big.NewFloat(1e-9) // same as default for Python's math.isclose() function t := new(big.Float) t.Sub(a, b) t.Abs(t) u, v, w := new(big.Float), new(big.Float), new(big.Float) u.Mul(relTol, max(v.Abs(a), w.Abs(b))) return t.Cmp(u) <= 0 } func nbf(s string) *big.Float { n, ok := new(big.Float).SetString(s) if !ok { log.Fatal("invalid floating point number") } return n } func main() { root2 := big.NewFloat(2.0) root2.Sqrt(root2) pairs := [][2]*big.Float{ {nbf("100000000000000.01"), nbf("100000000000000.011")}, {nbf("100.01"), nbf("100.011")}, {nbf("0").Quo(nbf("10000000000000.001"), nbf("10000.0")), nbf("1000000000.0000001000")}, {nbf("0.001"), nbf("0.0010000001")}, {nbf("0.000000000000000000000101"), nbf("0.0")}, {nbf("0").Mul(root2, root2), nbf("2.0")}, {nbf("0").Mul(nbf("0").Neg(root2), root2), nbf("-2.0")}, {nbf("100000000000000003.0"), nbf("100000000000000004.0")}, {nbf("3.14159265358979323846"), nbf("3.14159265358979324")}, } for _, pair := range pairs { s := "≉" if isClose(pair[0], pair[1]) { s = "≈" } fmt.Printf("% 21.19g %s %- 21.19g\n", pair[0], s, pair[1]) } }
Arena storage pool
Go
Dynamically allocated objects take their memory from a [[heap]]. The memory for an object is provided by an '''allocator''' which maintains the storage pool used for the [[heap]]. Often a call to allocator is denoted as P := new T where '''T''' is the type of an allocated object, and '''P''' is a [[reference]] to the object. The storage pool chosen by the allocator can be determined by either: * the object type '''T''' * the type of pointer '''P''' In the former case objects can be allocated only in one storage pool. In the latter case objects of the type can be allocated in any storage pool or on the [[stack]]. ;Task: The task is to show how allocators and user-defined storage pools are supported by the language. In particular: # define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups. # allocate some objects (e.g., integers) in the pool. Explain what controls the storage pool choice in the language.
package main import ( "fmt" "runtime" "sync" ) // New to Go 1.3 are sync.Pools, basically goroutine-safe free lists. // There is overhead in the goroutine-safety and if you do not need this // you might do better by implementing your own free list. func main() { // Task 1: Define a pool (of ints). Just as the task says, a sync.Pool // allocates individually and can free as a group. p := sync.Pool{New: func() interface{} { fmt.Println("pool empty") return new(int) }} // Task 2: Allocate some ints. i := new(int) j := new(int) // Show that they're usable. *i = 1 *j = 2 fmt.Println(*i + *j) // prints 3 // Task 2 continued: Put allocated ints in pool p. // Task explanation: Variable p has a pool as its value. Another pool // could be be created and assigned to a different variable. You choose // a pool simply by using the appropriate variable, p here. p.Put(i) p.Put(j) // Drop references to i and j. This allows them to be garbage collected; // that is, freed as a group. i = nil j = nil // Get ints for i and j again, this time from the pool. P.Get may reuse // an object allocated above as long as objects haven't been garbage // collected yet; otherwise p.Get will allocate a new object. i = p.Get().(*int) j = p.Get().(*int) *i = 4 *j = 5 fmt.Println(*i + *j) // prints 9 // One more test, this time forcing a garbage collection. p.Put(i) p.Put(j) i = nil j = nil runtime.GC() i = p.Get().(*int) j = p.Get().(*int) *i = 7 *j = 8 fmt.Println(*i + *j) // prints 15 }
Arithmetic-geometric mean
Go
{{wikipedia|Arithmetic-geometric mean}} ;Task: Write a function to compute the arithmetic-geometric mean of two numbers. The arithmetic-geometric mean of two numbers can be (usefully) denoted as \mathrm{agm}(a,g), and is equal to the limit of the sequence: : a_0 = a; \qquad g_0 = g : a_{n+1} = \tfrac{1}{2}(a_n + g_n); \quad g_{n+1} = \sqrt{a_n g_n}. Since the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method. Demonstrate the function by calculating: :\mathrm{agm}(1,1/\sqrt{2}) ;Also see: * mathworld.wolfram.com/Arithmetic-Geometric Mean
package main import ( "fmt" "math" ) const ε = 1e-14 func agm(a, g float64) float64 { for math.Abs(a-g) > math.Abs(a)*ε { a, g = (a+g)*.5, math.Sqrt(a*g) } return a } func main() { fmt.Println(agm(1, 1/math.Sqrt2)) }
Arithmetic-geometric mean/Calculate Pi
Go
Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate \pi. With the same notations used in [[Arithmetic-geometric mean]], we can summarize the paper by writing: \pi = \frac{4\; \mathrm{agm}(1, 1/\sqrt{2})^2} {1 - \sum\limits_{n=1}^{\infty} 2^{n+1}(a_n^2-g_n^2)} This allows you to make the approximation, for any large '''N''': \pi \approx \frac{4\; a_N^2} {1 - \sum\limits_{k=1}^N 2^{k+1}(a_k^2-g_k^2)} The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of \pi.
package main import ( "fmt" "math/big" ) func main() { one := big.NewFloat(1) two := big.NewFloat(2) four := big.NewFloat(4) prec := uint(768) // say a := big.NewFloat(1).SetPrec(prec) g := new(big.Float).SetPrec(prec) // temporary variables t := new(big.Float).SetPrec(prec) u := new(big.Float).SetPrec(prec) g.Quo(a, t.Sqrt(two)) sum := new(big.Float) pow := big.NewFloat(2) for a.Cmp(g) != 0 { t.Add(a, g) t.Quo(t, two) g.Sqrt(u.Mul(a, g)) a.Set(t) pow.Mul(pow, two) t.Sub(t.Mul(a, a), u.Mul(g, g)) sum.Add(sum, t.Mul(t, pow)) } t.Mul(a, a) t.Mul(t, four) pi := t.Quo(t, u.Sub(one, sum)) fmt.Println(pi) }
Arithmetic numbers
Go from Wren
Definition A positive integer '''n''' is an arithmetic number if the average of its positive divisors is also an integer. Clearly all odd primes '''p''' must be arithmetic numbers because their only divisors are '''1''' and '''p''' whose sum is even and hence their average must be an integer. However, the prime number '''2''' is not an arithmetic number because the average of its divisors is 1.5. ;Example 30 is an arithmetic number because its 7 divisors are: [1, 2, 3, 5, 6, 10, 15, 30], their sum is 72 and average 9 which is an integer. ;Task Calculate and show here: 1. The first 100 arithmetic numbers. 2. The '''x'''th arithmetic number where '''x''' = 1,000 and '''x''' = 10,000. 3. How many of the first '''x''' arithmetic numbers are composite. Note that, technically, the arithmetic number '''1''' is neither prime nor composite. ;Stretch Carry out the same exercise in 2. and 3. above for '''x''' = 100,000 and '''x''' = 1,000,000. ;References * Wikipedia: Arithmetic number * OEIS:A003601 - Numbers n such that the average of the divisors of n is an integer
package main import ( "fmt" "math" "rcu" "sort" ) func main() { arithmetic := []int{1} primes := []int{} limit := int(1e6) for n := 3; len(arithmetic) < limit; n++ { divs := rcu.Divisors(n) if len(divs) == 2 { primes = append(primes, n) arithmetic = append(arithmetic, n) } else { mean := float64(rcu.SumInts(divs)) / float64(len(divs)) if mean == math.Trunc(mean) { arithmetic = append(arithmetic, n) } } } fmt.Println("The first 100 arithmetic numbers are:") rcu.PrintTable(arithmetic[0:100], 10, 3, false) for _, x := range []int{1e3, 1e4, 1e5, 1e6} { last := arithmetic[x-1] lastc := rcu.Commatize(last) fmt.Printf("\nThe %sth arithmetic number is: %s\n", rcu.Commatize(x), lastc) pcount := sort.SearchInts(primes, last) + 1 if !rcu.IsPrime(last) { pcount-- } comp := x - pcount - 1 // 1 is not composite compc := rcu.Commatize(comp) fmt.Printf("The count of such numbers <= %s which are composite is %s.\n", lastc, compc) } }
Array length
Go
Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'.
package main import "fmt" func main() { arr := [...]string{"apple", "orange", "pear"} fmt.Printf("Length of %v is %v.\n", arr, len(arr)) }
Associative array/Merging
Go
Define two associative arrays, where one represents the following "base" data: ::::: {| class="wikitable" |+ | '''Key''' || '''Value''' |- | "name" || "Rocket Skates" |- | "price" || 12.75 |- | "color" || "yellow" |} And the other represents "update" data: ::::: {| class="wikitable" |+ | '''Key''' || '''Value''' |- | "price" || 15.25 |- | "color" || "red" |- | "year" || 1974 |} Merge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be: ::::: {| class="wikitable" |+ | '''Key''' || '''Value''' |- | "name" || "Rocket Skates" |- | "price" || 15.25 |- | "color" || "red" |- | "year" || 1974 |}
package main import "fmt" type assoc map[string]interface{} func merge(base, update assoc) assoc { result := make(assoc) for k, v := range base { result[k] = v } for k, v := range update { result[k] = v } return result } func main() { base := assoc{"name": "Rocket Skates", "price": 12.75, "color": "yellow"} update := assoc{"price": 15.25, "color": "red", "year": 1974} result := merge(base, update) fmt.Println(result) }
Attractive numbers
Go
A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime. ;Example: The number '''20''', whose prime decomposition is '''2 x 2 x 5''', is an ''attractive number'' because the number of its prime factors ('''3''') is also prime. ;Task: Show sequence items up to '''120'''. ;Reference: :* The OEIS entry: A063989: Numbers with a prime number of prime divisors.
package main import "fmt" func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } } func countPrimeFactors(n int) int { switch { case n == 1: return 0 case isPrime(n): return 1 default: count, f := 0, 2 for { if n%f == 0 { count++ n /= f if n == 1 { return count } if isPrime(n) { f = n } } else if f >= 3 { f += 2 } else { f = 3 } } return count } } func main() { const max = 120 fmt.Println("The attractive numbers up to and including", max, "are:") count := 0 for i := 1; i <= max; i++ { n := countPrimeFactors(i) if isPrime(n) { fmt.Printf("%4d", i) count++ if count % 20 == 0 { fmt.Println() } } } fmt.Println() }
Average loop length
Go
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence. ;Task: Write a program or a script that estimates, for each N, the average length until the first such repetition. Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one. This problem comes from the end of Donald Knuth's Christmas tree lecture 2011. Example of expected output: N average analytical (error) === ========= ============ ========= 1 1.0000 1.0000 ( 0.00%) 2 1.4992 1.5000 ( 0.05%) 3 1.8784 1.8889 ( 0.56%) 4 2.2316 2.2188 ( 0.58%) 5 2.4982 2.5104 ( 0.49%) 6 2.7897 2.7747 ( 0.54%) 7 3.0153 3.0181 ( 0.09%) 8 3.2429 3.2450 ( 0.07%) 9 3.4536 3.4583 ( 0.14%) 10 3.6649 3.6602 ( 0.13%) 11 3.8091 3.8524 ( 1.12%) 12 3.9986 4.0361 ( 0.93%) 13 4.2074 4.2123 ( 0.12%) 14 4.3711 4.3820 ( 0.25%) 15 4.5275 4.5458 ( 0.40%) 16 4.6755 4.7043 ( 0.61%) 17 4.8877 4.8579 ( 0.61%) 18 4.9951 5.0071 ( 0.24%) 19 5.1312 5.1522 ( 0.41%) 20 5.2699 5.2936 ( 0.45%)
package main import ( "fmt" "math" "math/rand" ) const nmax = 20 func main() { fmt.Println(" N average analytical (error)") fmt.Println("=== ========= ============ =========") for n := 1; n <= nmax; n++ { a := avg(n) b := ana(n) fmt.Printf("%3d %9.4f %12.4f (%6.2f%%)\n", n, a, b, math.Abs(a-b)/b*100) } } func avg(n int) float64 { const tests = 1e4 sum := 0 for t := 0; t < tests; t++ { var v [nmax]bool for x := 0; !v[x]; x = rand.Intn(n) { v[x] = true sum++ } } return float64(sum) / tests } func ana(n int) float64 { nn := float64(n) term := 1. sum := 1. for i := nn - 1; i >= 1; i-- { term *= i / nn sum += term } return sum }
Averages/Mean angle
Go
{{Related tasks/Statistical measures}}
package main import ( "fmt" "math" "math/cmplx" ) func deg2rad(d float64) float64 { return d * math.Pi / 180 } func rad2deg(r float64) float64 { return r * 180 / math.Pi } func mean_angle(deg []float64) float64 { sum := 0i for _, x := range deg { sum += cmplx.Rect(1, deg2rad(x)) } return rad2deg(cmplx.Phase(sum)) } func main() { for _, angles := range [][]float64{ {350, 10}, {90, 180, 270, 360}, {10, 20, 30}, } { fmt.Printf("The mean angle of %v is: %f degrees\n", angles, mean_angle(angles)) } }
Averages/Pythagorean means
Go
{{Related tasks/Statistical measures}}
package main import ( "fmt" "math" ) func main() { sum, sumr, prod := 0., 0., 1. for n := 1.; n <= 10; n++ { sum += n sumr += 1 / n prod *= n } a, g, h := sum/10, math.Pow(prod, .1), 10/sumr fmt.Println("A:", a, "G:", g, "H:", h) fmt.Println("A >= G >= H:", a >= g && g >= h) }
Averages/Root mean square
Go
Task Compute the Root mean square of the numbers 1..10. The ''root mean square'' is also known by its initials RMS (or rms), and as the '''quadratic mean'''. The RMS is calculated as the mean of the squares of the numbers, square-rooted: ::: x_{\mathrm{rms}} = \sqrt {{{x_1}^2 + {x_2}^2 + \cdots + {x_n}^2} \over n}. ;See also {{Related tasks/Statistical measures}}
package main import ( "fmt" "math" ) func main() { const n = 10 sum := 0. for x := 1.; x <= n; x++ { sum += x * x } fmt.Println(math.Sqrt(sum / n)) }
Babbage problem
Go
Charles Babbage Charles Babbage's analytical engine. Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: {{quote | What is the smallest positive integer whose square ends in the digits 269,696? | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125. }} He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain. ;Task The task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred. For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L]. ;Motivation The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
package main import "fmt" func main() { const ( target = 269696 modulus = 1000000 ) for n := 1; ; n++ { // Repeat with n=1, n=2, n=3, ... square := n * n ending := square % modulus if ending == target { fmt.Println("The smallest number whose square ends with", target, "is", n, ) return } } }
Balanced brackets
Go
'''Task''': * Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. * Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. ;Examples: (empty) OK [] OK [][] OK [[][]] OK ][ NOT OK ][][ NOT OK []][[] NOT OK
package main import ( "bytes" "fmt" "math/rand" "time" ) func init() { rand.Seed(time.Now().UnixNano()) } func generate(n uint) string { a := bytes.Repeat([]byte("[]"), int(n)) for i := len(a) - 1; i >= 1; i-- { j := rand.Intn(i + 1) a[i], a[j] = a[j], a[i] } return string(a) } func testBalanced(s string) { fmt.Print(s + ": ") open := 0 for _,c := range s { switch c { case '[': open++ case ']': if open == 0 { fmt.Println("not ok") return } open-- default: fmt.Println("not ok") return } } if open == 0 { fmt.Println("ok") } else { fmt.Println("not ok") } } func main() { rand.Seed(time.Now().UnixNano()) for i := uint(0); i < 10; i++ { testBalanced(generate(i)) } testBalanced("()") }
Balanced ternary
Go
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or -1. ;Examples: Decimal 11 = 32 + 31 - 30, thus it can be written as "++-" Decimal 6 = 32 - 31 + 0 x 30, thus it can be written as "+-0" ;Task: Implement balanced ternary representation of integers with the following: # Support arbitrarily large integers, both positive and negative; # Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5). # Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated. # Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first. # Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable"). '''Test case''' With balanced ternaries ''a'' from string "+-0++0+", ''b'' from native integer -436, ''c'' "+-++-": * write out ''a'', ''b'' and ''c'' in decimal notation; * calculate ''a'' x (''b'' - ''c''), write out the result in both ternary and decimal notations. '''Note:''' The pages floating point balanced ternary.
package main import ( "fmt" "strings" ) // R1: representation is a slice of int8 digits of -1, 0, or 1. // digit at index 0 is least significant. zero value of type is // representation of the number 0. type bt []int8 // R2: string conversion: // btString is a constructor. valid input is a string of any length // consisting of only '+', '-', and '0' characters. // leading zeros are allowed but are trimmed and not represented. // false return means input was invalid. func btString(s string) (*bt, bool) { s = strings.TrimLeft(s, "0") b := make(bt, len(s)) for i, last := 0, len(s)-1; i < len(s); i++ { switch s[i] { case '-': b[last-i] = -1 case '0': b[last-i] = 0 case '+': b[last-i] = 1 default: return nil, false } } return &b, true } // String method converts the other direction, returning a string of // '+', '-', and '0' characters representing the number. func (b bt) String() string { if len(b) == 0 { return "0" } last := len(b) - 1 r := make([]byte, len(b)) for i, d := range b { r[last-i] = "-0+"[d+1] } return string(r) } // R3: integer conversion // int chosen as "native integer" // btInt is a constructor like btString. func btInt(i int) *bt { if i == 0 { return new(bt) } var b bt var btDigit func(int) btDigit = func(digit int) { m := int8(i % 3) i /= 3 switch m { case 2: m = -1 i++ case -2: m = 1 i-- } if i == 0 { b = make(bt, digit+1) } else { btDigit(digit + 1) } b[digit] = m } btDigit(0) return &b } // Int method converts the other way, returning the value as an int type. // !ok means overflow occurred during conversion, not necessarily that the // value is not representable as an int. (Of course there are other ways // of doing it but this was chosen as "reasonable.") func (b bt) Int() (r int, ok bool) { pt := 1 for _, d := range b { dp := int(d) * pt neg := r < 0 r += dp if neg { if r > dp { return 0, false } } else { if r < dp { return 0, false } } pt *= 3 } return r, true } // R4: negation, addition, and multiplication func (z *bt) Neg(b *bt) *bt { if z != b { if cap(*z) < len(*b) { *z = make(bt, len(*b)) } else { *z = (*z)[:len(*b)] } } for i, d := range *b { (*z)[i] = -d } return z } func (z *bt) Add(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } r := *z r = r[:cap(r)] var carry int8 for i, da := range *a { if i == len(r) { n := make(bt, len(*a)+4) copy(n, r) r = n } sum := da + carry if i < len(*b) { sum += (*b)[i] } carry = sum / 3 sum %= 3 switch { case sum > 1: sum -= 3 carry++ case sum < -1: sum += 3 carry-- } r[i] = sum } last := len(*a) if carry != 0 { if len(r) == last { n := make(bt, last+4) copy(n, r) r = n } r[last] = carry *z = r[:last+1] return z } for { if last == 0 { *z = nil break } last-- if r[last] != 0 { *z = r[:last+1] break } } return z } func (z *bt) Mul(a, b *bt) *bt { if len(*a) < len(*b) { a, b = b, a } var na bt for _, d := range *b { if d == -1 { na.Neg(a) break } } r := make(bt, len(*a)+len(*b)) for i := len(*b) - 1; i >= 0; i-- { switch (*b)[i] { case 1: p := r[i:] p.Add(&p, a) case -1: p := r[i:] p.Add(&p, &na) } } i := len(r) for i > 0 && r[i-1] == 0 { i-- } *z = r[:i] return z } func main() { a, _ := btString("+-0++0+") b := btInt(-436) c, _ := btString("+-++-") show("a:", a) show("b:", b) show("c:", c) show("a(b-c):", a.Mul(a, b.Add(b, c.Neg(c)))) } func show(label string, b *bt) { fmt.Printf("%7s %12v ", label, b) if i, ok := b.Int(); ok { fmt.Printf("%7d\n", i) } else { fmt.Println("int overflow") } }
Barnsley fern
Go
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). ;Task: Create this fractal fern, using the following transformations: * f1 (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn * f2 (chosen 85% of the time) xn + 1 = 0.85 xn + 0.04 yn yn + 1 = -0.04 xn + 0.85 yn + 1.6 * f3 (chosen 7% of the time) xn + 1 = 0.2 xn - 0.26 yn yn + 1 = 0.23 xn + 0.22 yn + 1.6 * f4 (chosen 7% of the time) xn + 1 = -0.15 xn + 0.28 yn yn + 1 = 0.26 xn + 0.24 yn + 0.44. Starting position: x = 0, y = 0
package main import ( "image" "image/color" "image/draw" "image/png" "log" "math/rand" "os" ) // values from WP const ( xMin = -2.1820 xMax = 2.6558 yMin = 0. yMax = 9.9983 ) // parameters var ( width = 200 n = int(1e6) c = color.RGBA{34, 139, 34, 255} // forest green ) func main() { dx := xMax - xMin dy := yMax - yMin fw := float64(width) fh := fw * dy / dx height := int(fh) r := image.Rect(0, 0, width, height) img := image.NewRGBA(r) draw.Draw(img, r, &image.Uniform{color.White}, image.ZP, draw.Src) var x, y float64 plot := func() { // transform computed float x, y to integer image coordinates ix := int(fw * (x - xMin) / dx) iy := int(fh * (yMax - y) / dy) img.SetRGBA(ix, iy, c) } plot() for i := 0; i < n; i++ { switch s := rand.Intn(100); { case s < 85: x, y = .85*x+.04*y, -.04*x+.85*y+1.6 case s < 85+7: x, y = .2*x-.26*y, .23*x+.22*y+1.6 case s < 85+7+7: x, y = -.15*x+.28*y, .26*x+.24*y+.44 default: x, y = 0, .16*y } plot() } // write img to png file f, err := os.Create("bf.png") if err != nil { log.Fatal(err) } if err := png.Encode(f, img); err != nil { log.Fatal(err) } }
Base64 decode data
Go
See [[Base64 encode data]]. Now write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.
package main import ( "encoding/base64" "fmt" ) func main() { msg := "Rosetta Code Base64 decode data task" fmt.Println("Original :", msg) encoded := base64.StdEncoding.EncodeToString([]byte(msg)) fmt.Println("\nEncoded :", encoded) decoded, err := base64.StdEncoding.DecodeString(encoded) if err != nil { fmt.Println(err) return } fmt.Println("\nDecoded :", string(decoded)) }
Bell numbers
Go
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly '''n''' elements. Each element of the sequence '''Bn''' is the number of partitions of a set of size '''n''' where order of the elements and order of the partitions are non-significant. E.G.: '''{a b}''' is the same as '''{b a}''' and '''{a} {b}''' is the same as '''{b} {a}'''. ;So: :'''B0 = 1''' trivially. There is only one way to partition a set with zero elements. '''{ }''' :'''B1 = 1''' There is only one way to partition a set with one element. '''{a}''' :'''B2 = 2''' Two elements may be partitioned in two ways. '''{a} {b}, {a b}''' :'''B3 = 5''' Three elements may be partitioned in five ways '''{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}''' : and so on. A simple way to find the Bell numbers is construct a '''Bell triangle''', also known as an '''Aitken's array''' or '''Peirce triangle''', and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case. ;Task: Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the '''first 15''' and (if your language supports big Integers) '''50th''' elements of the sequence. If you ''do'' use the Bell triangle method to generate the numbers, also show the '''first ten rows''' of the Bell triangle. ;See also: :* '''OEIS:A000110 Bell or exponential numbers''' :* '''OEIS:A011971 Aitken's array'''
package main import ( "fmt" "math/big" ) func bellTriangle(n int) [][]*big.Int { tri := make([][]*big.Int, n) for i := 0; i < n; i++ { tri[i] = make([]*big.Int, i) for j := 0; j < i; j++ { tri[i][j] = new(big.Int) } } tri[1][0].SetUint64(1) for i := 2; i < n; i++ { tri[i][0].Set(tri[i-1][i-2]) for j := 1; j < i; j++ { tri[i][j].Add(tri[i][j-1], tri[i-1][j-1]) } } return tri } func main() { bt := bellTriangle(51) fmt.Println("First fifteen and fiftieth Bell numbers:") for i := 1; i <= 15; i++ { fmt.Printf("%2d: %d\n", i, bt[i][0]) } fmt.Println("50:", bt[50][0]) fmt.Println("\nThe first ten rows of Bell's triangle:") for i := 1; i <= 10; i++ { fmt.Println(bt[i]) } }
Benford's law
Go
{{Wikipedia|Benford's_law}} '''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit d (d \in \{1, \ldots, 9\}) occurs with probability :::: P(d) = \log_{10}(d+1)-\log_{10}(d) = \log_{10}\left(1+\frac{1}{d}\right) For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution. ''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them. ;See also: * numberphile.com. * A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.
package main import ( "fmt" "math" ) func Fib1000() []float64 { a, b, r := 0., 1., [1000]float64{} for i := range r { r[i], a, b = b, b, b+a } return r[:] } func main() { show(Fib1000(), "First 1000 Fibonacci numbers") } func show(c []float64, title string) { var f [9]int for _, v := range c { f[fmt.Sprintf("%g", v)[0]-'1']++ } fmt.Println(title) fmt.Println("Digit Observed Predicted") for i, n := range f { fmt.Printf(" %d %9.3f %8.3f\n", i+1, float64(n)/float64(len(c)), math.Log10(1+1/float64(i+1))) } }
Best shuffle
Go from Icon and Unicon
Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative. Display the result as follows: original string, shuffled string, (score) The score gives the number of positions whose character value did ''not'' change. ;Example: tree, eetr, (0) ;Test cases: abracadabra seesaw elk grrrrrr up a ;Related tasks * [[Anagrams/Deranged anagrams]] * [[Permutations/Derangements]]
package main import ( "fmt" "math/rand" "time" ) var ts = []string{"abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"} func main() { rand.Seed(time.Now().UnixNano()) for _, s := range ts { // create shuffled byte array of original string t := make([]byte, len(s)) for i, r := range rand.Perm(len(s)) { t[i] = s[r] } // algorithm of Icon solution for i := range t { for j := range t { if i != j && t[i] != s[j] && t[j] != s[i] { t[i], t[j] = t[j], t[i] break } } } // count unchanged and output var count int for i, ic := range t { if ic == s[i] { count++ } } fmt.Printf("%s -> %s (%d)\n", s, string(t), count) } }
Bin given limits
Go
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] ..'' bin[n-1] counts how many inputs are >= limit[n-2] and < limit[n-1] bin[n] counts how many inputs are >= limit[n-1] ;Task: The task is to create a function that given the ascending limits and a stream/ list of numbers, will return the bins; together with another function that given the same list of limits and the binning will ''print the limit of each bin together with the count of items that fell in the range''. Assume the numbers to bin are too large to practically sort. ;Task examples: Part 1: Bin using the following limits the given input data limits = [23, 37, 43, 53, 67, 83] data = [95,21,94,12,99,4,70,75,83,93,52,80,57,5,53,86,65,17,92,83,71,61,54,58,47, 16, 8, 9,32,84,7,87,46,19,30,37,96,6,98,40,79,97,45,64,60,29,49,36,43,55] Part 2: Bin using the following limits the given input data limits = [14, 18, 249, 312, 389, 392, 513, 591, 634, 720] data = [445,814,519,697,700,130,255,889,481,122,932, 77,323,525,570,219,367,523,442,933, 416,589,930,373,202,253,775, 47,731,685,293,126,133,450,545,100,741,583,763,306, 655,267,248,477,549,238, 62,678, 98,534,622,907,406,714,184,391,913, 42,560,247, 346,860, 56,138,546, 38,985,948, 58,213,799,319,390,634,458,945,733,507,916,123, 345,110,720,917,313,845,426, 9,457,628,410,723,354,895,881,953,677,137,397, 97, 854,740, 83,216,421, 94,517,479,292,963,376,981,480, 39,257,272,157, 5,316,395, 787,942,456,242,759,898,576, 67,298,425,894,435,831,241,989,614,987,770,384,692, 698,765,331,487,251,600,879,342,982,527,736,795,585, 40, 54,901,408,359,577,237, 605,847,353,968,832,205,838,427,876,959,686,646,835,127,621,892,443,198,988,791, 466, 23,707,467, 33,670,921,180,991,396,160,436,717,918, 8,374,101,684,727,749] Show output here, on this page.
package main import ( "fmt" "sort" ) func getBins(limits, data []int) []int { n := len(limits) bins := make([]int, n+1) for _, d := range data { index := sort.SearchInts(limits, d) // uses binary search if index < len(limits) && d == limits[index] { index++ } bins[index]++ } return bins } func printBins(limits, bins []int) { n := len(limits) fmt.Printf(" < %3d = %2d\n", limits[0], bins[0]) for i := 1; i < n; i++ { fmt.Printf(">= %3d and < %3d = %2d\n", limits[i-1], limits[i], bins[i]) } fmt.Printf(">= %3d = %2d\n", limits[n-1], bins[n]) fmt.Println() } func main() { limitsList := [][]int{ {23, 37, 43, 53, 67, 83}, {14, 18, 249, 312, 389, 392, 513, 591, 634, 720}, } dataList := [][]int{ { 95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55, }, { 445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749, }, } for i := 0; i < len(limitsList); i++ { fmt.Println("Example", i+1, "\b\n") bins := getBins(limitsList[i], dataList[i]) printBins(limitsList[i], bins) } }
Bioinformatics/Global alignment
Go from Julia
Global alignment is designed to search for highly similar regions in two or more DNA sequences, where the sequences appear in the same order and orientation, fitting the sequences in as pieces in a puzzle. Current DNA sequencers find the sequence for multiple small segments of DNA which have mostly randomly formed by splitting a much larger DNA molecule into shorter segments. When re-assembling such segments of DNA sequences into a larger sequence to form, for example, the DNA coding for the relevant gene, the overlaps between multiple shorter sequences are commonly used to decide how the longer sequence is to be assembled. For example, "AAGATGGA", GGAGCGCATC", and "ATCGCAATAAGGA" can be assembled into the sequence "AAGATGGAGCGCATCGCAATAAGGA" by noting that "GGA" is at the tail of the first string and head of the second string and "ATC" likewise is at the tail of the second and head of the third string. When looking for the best global alignment in the output strings produced by DNA sequences, there are typically a large number of such overlaps among a large number of sequences. In such a case, the ordering that results in the shortest common superstring is generrally preferred. Finding such a supersequence is an NP-hard problem, and many algorithms have been proposed to shorten calculations, especially when many very long sequences are matched. The shortest common superstring as used in bioinfomatics here differs from the string task [[Shortest_common_supersequence]]. In that task, a supersequence may have other characters interposed as long as the characters of each subsequence appear in order, so that (abcbdab, abdcaba) -> abdcabdab. In this task, (abcbdab, abdcaba) -> abcbdabdcaba. ;Task: :* Given N non-identical strings of characters A, C, G, and T representing N DNA sequences, find the shortest DNA sequence containing all N sequences. :* Handle cases where two sequences are identical or one sequence is entirely contained in another. :* Print the resulting sequence along with its size (its base count) and a count of each base in the sequence. :* Find the shortest common superstring for the following four examples: : ("TA", "AAG", "TA", "GAA", "TA") ("CATTAGGG", "ATTAG", "GGG", "TA") ("AAGAUGGA", "GGAGCGCAUC", "AUCGCAAUAAGGA") ("ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT", "GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT", "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA", "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT", "GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC", "CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT", "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC", "GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT", "TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA", "TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA") ;Related tasks: :* Bioinformatics base count. :* Bioinformatics sequence mutation.
package main import ( "fmt" "strings" ) /* Gets n! for small n. */ func factorial(n int) int { fact := 1 for i := 2; i <= n; i++ { fact *= i } return fact } /* Gets all permutations of a list of strings. */ func getPerms(input []string) [][]string { perms := [][]string{input} le := len(input) a := make([]string, le) copy(a, input) n := le - 1 fact := factorial(n + 1) for c := 1; c < fact; c++ { i := n - 1 j := n for i >= 0 && a[i] > a[i+1] { i-- } if i == -1 { i = n } for a[j] < a[i] { j-- } a[i], a[j] = a[j], a[i] j = n i++ if i == n+1 { i = 0 } for i < j { a[i], a[j] = a[j], a[i] i++ j-- } b := make([]string, le) copy(b, a) perms = append(perms, b) } return perms } /* Returns all distinct elements from a list of strings. */ func distinct(slist []string) []string { distinctSet := make(map[string]int, len(slist)) i := 0 for _, s := range slist { if _, ok := distinctSet[s]; !ok { distinctSet[s] = i i++ } } result := make([]string, len(distinctSet)) for s, i := range distinctSet { result[i] = s } return result } /* Given a DNA sequence, report the sequence, length and base counts. */ func printCounts(seq string) { bases := [][]rune{{'A', 0}, {'C', 0}, {'G', 0}, {'T', 0}} for _, c := range seq { for _, base := range bases { if c == base[0] { base[1]++ } } } sum := 0 fmt.Println("\nNucleotide counts for", seq, "\b:\n") for _, base := range bases { fmt.Printf("%10c%12d\n", base[0], base[1]) sum += int(base[1]) } le := len(seq) fmt.Printf("%10s%12d\n", "Other", le-sum) fmt.Printf(" ____________________\n%14s%8d\n", "Total length", le) } /* Return the position in s1 of the start of overlap of tail of string s1 with head of string s2. */ func headTailOverlap(s1, s2 string) int { for start := 0; ; start++ { ix := strings.IndexByte(s1[start:], s2[0]) if ix == -1 { return 0 } else { start += ix } if strings.HasPrefix(s2, s1[start:]) { return len(s1) - start } } } /* Remove duplicates and strings contained within a larger string from a list of strings. */ func deduplicate(slist []string) []string { var filtered []string arr := distinct(slist) for i, s1 := range arr { withinLarger := false for j, s2 := range arr { if j != i && strings.Contains(s2, s1) { withinLarger = true break } } if !withinLarger { filtered = append(filtered, s1) } } return filtered } /* Returns shortest common superstring of a list of strings. */ func shortestCommonSuperstring(slist []string) string { ss := deduplicate(slist) shortestSuper := strings.Join(ss, "") for _, perm := range getPerms(ss) { sup := perm[0] for i := 0; i < len(ss)-1; i++ { overlapPos := headTailOverlap(perm[i], perm[i+1]) sup += perm[i+1][overlapPos:] } if len(sup) < len(shortestSuper) { shortestSuper = sup } } return shortestSuper } func main() { testSequences := [][]string{ {"TA", "AAG", "TA", "GAA", "TA"}, {"CATTAGGG", "ATTAG", "GGG", "TA"}, {"AAGAUGGA", "GGAGCGCAUC", "AUCGCAAUAAGGA"}, { "ATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTAT", "GGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGT", "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA", "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "AACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT", "GCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTC", "CGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCT", "TGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGC", "GATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATT", "TTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATC", "CTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA", "TCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGA", }, } for _, test := range testSequences { scs := shortestCommonSuperstring(test) printCounts(scs) } }
Bioinformatics/Sequence mutation
Go
Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by: # Choosing a random base position in the sequence. # Mutate the sequence by doing one of either: ## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base) ## '''D'''elete the chosen base at the position. ## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position. # Randomly generate a test DNA sequence of at least 200 bases # "Pretty print" the sequence and a count of its size, and the count of each base in the sequence # Mutate the sequence ten times. # "Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence. ;Extra credit: * Give more information on the individual mutations applied. * Allow mutations to be weighted and/or chosen.
package main import ( "fmt" "math/rand" "sort" "time" ) const bases = "ACGT" // 'w' contains the weights out of 300 for each // of swap, delete or insert in that order. func mutate(dna string, w [3]int) string { le := len(dna) // get a random position in the dna to mutate p := rand.Intn(le) // get a random number between 0 and 299 inclusive r := rand.Intn(300) bytes := []byte(dna) switch { case r < w[0]: // swap base := bases[rand.Intn(4)] fmt.Printf(" Change @%3d %q to %q\n", p, bytes[p], base) bytes[p] = base case r < w[0]+w[1]: // delete fmt.Printf(" Delete @%3d %q\n", p, bytes[p]) copy(bytes[p:], bytes[p+1:]) bytes = bytes[0 : le-1] default: // insert base := bases[rand.Intn(4)] bytes = append(bytes, 0) copy(bytes[p+1:], bytes[p:]) fmt.Printf(" Insert @%3d %q\n", p, base) bytes[p] = base } return string(bytes) } // Generate a random dna sequence of given length. func generate(le int) string { bytes := make([]byte, le) for i := 0; i < le; i++ { bytes[i] = bases[rand.Intn(4)] } return string(bytes) } // Pretty print dna and stats. func prettyPrint(dna string, rowLen int) { fmt.Println("SEQUENCE:") le := len(dna) for i := 0; i < le; i += rowLen { k := i + rowLen if k > le { k = le } fmt.Printf("%5d: %s\n", i, dna[i:k]) } baseMap := make(map[byte]int) // allows for 'any' base for i := 0; i < le; i++ { baseMap[dna[i]]++ } var bases []byte for k := range baseMap { bases = append(bases, k) } sort.Slice(bases, func(i, j int) bool { // get bases into alphabetic order return bases[i] < bases[j] }) fmt.Println("\nBASE COUNT:") for _, base := range bases { fmt.Printf(" %c: %3d\n", base, baseMap[base]) } fmt.Println(" ------") fmt.Println(" Σ:", le) fmt.Println(" ======\n") } // Express weights as a string. func wstring(w [3]int) string { return fmt.Sprintf(" Change: %d\n Delete: %d\n Insert: %d\n", w[0], w[1], w[2]) } func main() { rand.Seed(time.Now().UnixNano()) dna := generate(250) prettyPrint(dna, 50) muts := 10 w := [3]int{100, 100, 100} // use e.g. {0, 300, 0} to choose only deletions fmt.Printf("WEIGHTS (ex 300):\n%s\n", wstring(w)) fmt.Printf("MUTATIONS (%d):\n", muts) for i := 0; i < muts; i++ { dna = mutate(dna, w) } fmt.Println() prettyPrint(dna, 50) }
Bioinformatics/base count
Go
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT ;Task: :* "Pretty print" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence :* print the total count of each base in the string.
package main import ( "fmt" "sort" ) func main() { dna := "" + "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" + "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" + "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" + "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" + "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" + "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" + "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" fmt.Println("SEQUENCE:") le := len(dna) for i := 0; i < le; i += 50 { k := i + 50 if k > le { k = le } fmt.Printf("%5d: %s\n", i, dna[i:k]) } baseMap := make(map[byte]int) // allows for 'any' base for i := 0; i < le; i++ { baseMap[dna[i]]++ } var bases []byte for k := range baseMap { bases = append(bases, k) } sort.Slice(bases, func(i, j int) bool { // get bases into alphabetic order return bases[i] < bases[j] }) fmt.Println("\nBASE COUNT:") for _, base := range bases { fmt.Printf(" %c: %3d\n", base, baseMap[base]) } fmt.Println(" ------") fmt.Println(" Σ:", le) fmt.Println(" ======") }
Biorhythms
Go from Wren
For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that unlike astrology, the math behind biorhythms is dead simple. It's based on the number of days since your birth. The premise is that three cycles of unspecified provenance govern certain aspects of everyone's lives - specifically, how they're feeling physically, emotionally, and mentally. The best part is that not only do these cycles somehow have the same respective lengths for all humans of any age, gender, weight, genetic background, etc, but those lengths are an exact number of days. And the pattern is in each case a perfect sine curve. Absolutely miraculous! To compute your biorhythmic profile for a given day, the first thing you need is the number of days between that day and your birth, so the answers in [[Days between dates]] are probably a good starting point. (Strictly speaking, the biorhythms start at 0 at the moment of your birth, so if you know time of day you can narrow things down further, but in general these operate at whole-day granularity.) Then take the residue of that day count modulo each of the the cycle lengths to calculate where the day falls on each of the three sinusoidal journeys. The three cycles and their lengths are as follows: :::{| class="wikitable" ! Cycle ! Length |- |Physical | 23 days |- |Emotional | 28 days |- |Mental | 33 days |} The first half of each cycle is in "plus" territory, with a peak at the quarter-way point; the second half in "minus" territory, with a valley at the three-quarters mark. You can calculate a specific value between -1 and +1 for the ''k''th day of an ''n''-day cycle by computing '''sin( 2p''k'' / ''n'' )'''. The days where a cycle crosses the axis in either direction are called "critical" days, although with a cycle value of 0 they're also said to be the most neutral, which seems contradictory. The task: write a subroutine, function, or program that will, given a birthdate and a target date, output the three biorhythmic values for the day. You may optionally include a text description of the position and the trend (e.g. "up and rising", "peak", "up but falling", "critical", "down and falling", "valley", "down but rising"), an indication of the date on which the next notable event (peak, valley, or crossing) falls, or even a graph of the cycles around the target date. Demonstrate the functionality for dates of your choice. Example run of my Raku implementation: raku br.raku 1943-03-09 1972-07-11
package main import ( "fmt" "log" "math" "time" ) const layout = "2006-01-02" // template for time.Parse var cycles = [3]string{"Physical day ", "Emotional day", "Mental day "} var lengths = [3]int{23, 28, 33} var quadrants = [4][2]string{ {"up and rising", "peak"}, {"up but falling", "transition"}, {"down and falling", "valley"}, {"down but rising", "transition"}, } func check(err error) { if err != nil { log.Fatal(err) } } // Parameters assumed to be in YYYY-MM-DD format. func biorhythms(birthDate, targetDate string) { bd, err := time.Parse(layout, birthDate) check(err) td, err := time.Parse(layout, targetDate) check(err) days := int(td.Sub(bd).Hours() / 24) fmt.Printf("Born %s, Target %s\n", birthDate, targetDate) fmt.Println("Day", days) for i := 0; i < 3; i++ { length := lengths[i] cycle := cycles[i] position := days % length quadrant := position * 4 / length percent := math.Sin(2 * math.Pi * float64(position) / float64(length)) percent = math.Floor(percent*1000) / 10 descript := "" if percent > 95 { descript = " peak" } else if percent < -95 { descript = " valley" } else if math.Abs(percent) < 5 { descript = " critical transition" } else { daysToAdd := (quadrant+1)*length/4 - position transition := td.Add(time.Hour * 24 * time.Duration(daysToAdd)) trend := quadrants[quadrant][0] next := quadrants[quadrant][1] transStr := transition.Format(layout) descript = fmt.Sprintf("%5.1f%% (%s, next %s %s)", percent, trend, next, transStr) } fmt.Printf("%s %2d : %s\n", cycle, position, descript) } fmt.Println() } func main() { datePairs := [][2]string{ {"1943-03-09", "1972-07-11"}, {"1809-01-12", "1863-11-19"}, {"1809-02-12", "1863-11-19"}, // correct DOB for Abraham Lincoln } for _, datePair := range datePairs { biorhythms(datePair[0], datePair[1]) } }
Bitcoin/address validation
Go from C
Write a program that takes a bitcoin address as argument, and checks whether or not this address is valid. A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters: :::* 0 zero :::* O uppercase oh :::* I uppercase eye :::* l lowercase ell With this encoding, a bitcoin address encodes 25 bytes: * the first byte is the version number, which will be zero for this task ; * the next twenty bytes are a [[RIPEMD-160]] digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ; * the last four bytes are a checksum check. They are the first four bytes of a double [[SHA-256]] digest of the previous 21 bytes. To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes. The program can either return a boolean value or throw an exception when not valid. You can use a digest library for [[SHA-256]]. ;Example of a bitcoin address: 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i It doesn't belong to anyone and is part of the test suite of the bitcoin software. You can change a few characters in this string and check that it'll fail the test.
<syntaxhighlight lang="go">package main import ( "bytes" "crypto/sha256" "errors" "os" ) // With at least one other bitcoin RC task, this source is styled more like // a package to show how functions of the two tasks might be combined into // a single package. It turns out there's not really that much shared code, // just the A25 type and doubleSHA256 method, but it's enough to suggest how // the code might be organized. Types, methods, and functions are capitalized // where they might be exported from a package. // A25 is a type for a 25 byte (not base58 encoded) bitcoin address. type A25 [25]byte func (a *A25) Version() byte { return a[0] } func (a *A25) EmbeddedChecksum() (c [4]byte) { copy(c[:], a[21:]) return } // DoubleSHA256 computes a double sha256 hash of the first 21 bytes of the // address. This is the one function shared with the other bitcoin RC task. // Returned is the full 32 byte sha256 hash. (The bitcoin checksum will be // the first four bytes of the slice.) func (a *A25) doubleSHA256() []byte { h := sha256.New() h.Write(a[:21]) d := h.Sum([]byte{}) h = sha256.New() h.Write(d) return h.Sum(d[:0]) } // ComputeChecksum returns a four byte checksum computed from the first 21 // bytes of the address. The embedded checksum is not updated. func (a *A25) ComputeChecksum() (c [4]byte) { copy(c[:], a.doubleSHA256()) return
Bitwise IO
Go
The aim of this task is to write functions (or create a class if yourlanguage is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence 0101011101010 (13 bits) must be 0101011101010; real I/O is performed always ''quantized'' by byte (avoiding endianness issues and relying on underlying buffering for performance), therefore you must obtain as output the bytes 0101 0111 0101 0'''000''' (bold bits are padding bits), i.e. in hexadecimal 57 50. As test, you can implement a '''rough''' (e.g. don't care about error handling or other issues) compression/decompression program for ASCII sequences of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output). These bit oriented I/O functions can be used to implement compressors and decompressors; e.g. Dynamic and Static Huffman encodings use variable length bits sequences, while LZW (see [[LZW compression]]) use fixed or variable ''words'' nine (or more) bits long. * Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed. * Errors handling is not mandatory
// Package bit provides bit-wise IO to an io.Writer and from an io.Reader. package bit import ( "bufio" "errors" "io" ) // Order specifies the bit ordering within a byte stream. type Order int const ( // LSB is for Least Significant Bits first LSB Order = iota // MSB is for Most Significant Bits first MSB ) // ==== Writing / Encoding ==== type writer interface { io.ByteWriter Flush() error } // Writer implements bit-wise writing to an io.Writer. type Writer struct { w writer order Order write func(uint32, uint) error // writeLSB or writeMSB bits uint32 nBits uint err error } // writeLSB writes `width` bits of `c` in LSB order. func (w *Writer) writeLSB(c uint32, width uint) error { w.bits |= c << w.nBits w.nBits += width for w.nBits >= 8 { if err := w.w.WriteByte(uint8(w.bits)); err != nil { return err } w.bits >>= 8 w.nBits -= 8 } return nil } // writeMSB writes `width` bits of `c` in MSB order. func (w *Writer) writeMSB(c uint32, width uint) error { w.bits |= c << (32 - width - w.nBits) w.nBits += width for w.nBits >= 8 { if err := w.w.WriteByte(uint8(w.bits >> 24)); err != nil { return err } w.bits <<= 8 w.nBits -= 8 } return nil } // WriteBits writes up to 16 bits of `c` to the underlying writer. // Even for MSB ordering the bits are taken from the lower bits of `c`. // (e.g. WriteBits(0x0f,4) writes four 1 bits). func (w *Writer) WriteBits(c uint16, width uint) error { if w.err == nil { w.err = w.write(uint32(c), width) } return w.err } var errClosed = errors.New("bit reader/writer is closed") // Close closes the writer, flushing any pending output. // It does not close the underlying writer. func (w *Writer) Close() error { if w.err != nil { if w.err == errClosed { return nil } return w.err } // Write the final bits (zero padded). if w.nBits > 0 { if w.order == MSB { w.bits >>= 24 } if w.err = w.w.WriteByte(uint8(w.bits)); w.err != nil { return w.err } } w.err = w.w.Flush() if w.err != nil { return w.err } // Make any future calls to Write return errClosed. w.err = errClosed return nil } // NewWriter returns a new bit Writer that writes completed bytes to `w`. func NewWriter(w io.Writer, order Order) *Writer { bw := &Writer{order: order} switch order { case LSB: bw.write = bw.writeLSB case MSB: bw.write = bw.writeMSB default: bw.err = errors.New("bit writer: unknown order") return bw } if byteWriter, ok := w.(writer); ok { bw.w = byteWriter } else { bw.w = bufio.NewWriter(w) } return bw } // ==== Reading / Decoding ==== // Reader implements bit-wise reading from an io.Reader. type Reader struct { r io.ByteReader bits uint32 nBits uint read func(width uint) (uint16, error) // readLSB or readMSB err error } func (r *Reader) readLSB(width uint) (uint16, error) { for r.nBits < width { x, err := r.r.ReadByte() if err != nil { return 0, err } r.bits |= uint32(x) << r.nBits r.nBits += 8 } bits := uint16(r.bits & (1<<width - 1)) r.bits >>= width r.nBits -= width return bits, nil } func (r *Reader) readMSB(width uint) (uint16, error) { for r.nBits < width { x, err := r.r.ReadByte() if err != nil { return 0, err } r.bits |= uint32(x) << (24 - r.nBits) r.nBits += 8 } bits := uint16(r.bits >> (32 - width)) r.bits <<= width r.nBits -= width return bits, nil } // ReadBits reads up to 16 bits from the underlying reader. func (r *Reader) ReadBits(width uint) (uint16, error) { var bits uint16 if r.err == nil { bits, r.err = r.read(width) } return bits, r.err } // Close closes the reader. // It does not close the underlying reader. func (r *Reader) Close() error { if r.err != nil && r.err != errClosed { return r.err } r.err = errClosed return nil } // NewReader returns a new bit Reader that reads bytes from `r`. func NewReader(r io.Reader, order Order) *Reader { br := new(Reader) switch order { case LSB: br.read = br.readLSB case MSB: br.read = br.readMSB default: br.err = errors.New("bit writer: unknown order") return br } if byteReader, ok := r.(io.ByteReader); ok { br.r = byteReader } else { br.r = bufio.NewReader(r) } return br }
Box the compass
Go
Avast me hearties! There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! ;Task description: # Create a function that takes a heading in degrees and returns the correct 32-point compass heading. # Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input: :[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance). ;Notes; * The headings and indices can be calculated from this pseudocode: for i in 0..32 inclusive: heading = i * 11.25 case i %3: if 1: heading += 5.62; break if 2: heading -= 5.62; break end index = ( i mod 32) + 1 * The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..
package main import "fmt" // function required by task func degrees2compasspoint(h float32) string { return compassPoint[cpx(h)] } // cpx returns integer index from 0 to 31 corresponding to compass point. // input heading h is in degrees. Note this index is a zero-based index // suitable for indexing into the table of printable compass points, // and is not the same as the index specified to be printed in the output. func cpx(h float32) int { x := int(h/11.25+.5) % 32 if x < 0 { x += 32 } return x } // printable compass points var compassPoint = []string{ "North", "North by east", "North-northeast", "Northeast by north", "Northeast", "Northeast by east", "East-northeast", "East by north", "East", "East by south", "East-southeast", "Southeast by east", "Southeast", "Southeast by south", "South-southeast", "South by east", "South", "South by west", "South-southwest", "Southwest by south", "Southwest", "Southwest by west", "West-southwest", "West by south", "West", "West by north", "West-northwest", "Northwest by west", "Northwest", "Northwest by north", "North-northwest", "North by west", } func main() { fmt.Println("Index Compass point Degree") for i, h := range []float32{0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38} { index := i%32 + 1 // printable index computed per pseudocode fmt.Printf("%4d %-19s %7.2f°\n", index, degrees2compasspoint(h), h) } }
Brazilian numbers
Go
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits. ;E.G.: :* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''. :* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same. :* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same. :* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same. :* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same. :* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same. :* ''and so on...'' All even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''. More common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1''' The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. All prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes > 2 ;Task: Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page; :* the first '''20''' Brazilian numbers; :* the first '''20 odd''' Brazilian numbers; :* the first '''20 prime''' Brazilian numbers; ;See also: :* '''OEIS:A125134 - Brazilian numbers''' :* '''OEIS:A257521 - Odd Brazilian numbers''' :* '''OEIS:A085104 - Prime Brazilian numbers'''
package main import "fmt" func sameDigits(n, b int) bool { f := n % b n /= b for n > 0 { if n%b != f { return false } n /= b } return true } func isBrazilian(n int) bool { if n < 7 { return false } if n%2 == 0 && n >= 8 { return true } for b := 2; b < n-1; b++ { if sameDigits(n, b) { return true } } return false } func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } } func main() { kinds := []string{" ", " odd ", " prime "} for _, kind := range kinds { fmt.Printf("First 20%sBrazilian numbers:\n", kind) c := 0 n := 7 for { if isBrazilian(n) { fmt.Printf("%d ", n) c++ if c == 20 { fmt.Println("\n") break } } switch kind { case " ": n++ case " odd ": n += 2 case " prime ": for { n += 2 if isPrime(n) { break } } } } } n := 7 for c := 0; c < 100000; n++ { if isBrazilian(n) { c++ } } fmt.Println("The 100,000th Brazilian number:", n-1) }
Brazilian numbers
Go from C# (speedier version)
Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil. Brazilian numbers are defined as: The set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits. ;E.G.: :* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''. :* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same. :* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same. :* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same. :* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same. :* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same. :* ''and so on...'' All even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''. More common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1''' The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. All prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes > 2 ;Task: Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page; :* the first '''20''' Brazilian numbers; :* the first '''20 odd''' Brazilian numbers; :* the first '''20 prime''' Brazilian numbers; ;See also: :* '''OEIS:A125134 - Brazilian numbers''' :* '''OEIS:A257521 - Odd Brazilian numbers''' :* '''OEIS:A085104 - Prime Brazilian numbers'''
package main import ( "fmt" "math" "time" ) // flags const ( prMk int8 = 0 // prime sqMk = 1 // prime square upMk = 2 // non-prime brMk = -2 // Brazilian prime excp = 121 // the only Brazilian square prime ) var ( pow = 9 max = 0 ps []int8 ) // typical sieve of Eratosthenes func primeSieve(top int) { ps = make([]int8, top) i, j := 2, 4 ps[j] = sqMk for j < top-2 { j += 2 ps[j] = upMk } i, j = 3, 9 ps[j] = sqMk for j < top-6 { j += 6 ps[j] = upMk } i = 5 for i*i < top { if ps[i] == prMk { j = (top - i) / i if (j & 1) == 0 { j-- } for { if ps[j] == prMk { ps[i*j] = upMk } j -= 2 if j <= i { break } } ps[i*i] = sqMk } for { i += 2 if ps[i] == prMk { break } } } } // returns whether a number is Brazilian func isBr(number int) bool { temp := ps[number] if temp < 0 { temp = -temp } return temp > sqMk } // shows the first few Brazilian numbers of several kinds func firstFew(kind string, amt int) { fmt.Printf("\nThe first %d %sBrazilian numbers are:\n", amt, kind) i := 7 for amt > 0 { if isBr(i) { amt-- fmt.Printf("%d ", i) } switch kind { case "odd ": i += 2 case "prime ": for { i += 2 if ps[i] == brMk && i != excp { break } } default: i++ } } fmt.Println() } // expands a 111_X number into an integer func expand(numberOfOnes, base int) int { res := 1 for numberOfOnes > 1 { numberOfOnes-- res = res*base + 1 } if res > max || res < 0 { res = 0 } return res } func toMs(d time.Duration) float64 { return float64(d) / 1e6 } func commatize(n int) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { start := time.Now() st0 := start p2 := pow << 1 p10 := int(math.Pow10(pow)) p, cnt := 10, 0 max = p10 * p2 / (p2 - 1) primeSieve(max) fmt.Printf("Sieving took %.4f ms\n", toMs(time.Since(start))) start = time.Now() primes := make([]int, 7) n := 3 for i := 0; i < len(primes); i++ { primes[i] = n for { n += 2 if ps[n] == 0 { break } } } fmt.Println("\nChecking first few prime numbers of sequential ones:") fmt.Println("ones checked found") for _, i := range primes { fmt.Printf("%4d", i) cnt, n = 0, 2 for { if (n-1)%i != 0 { br := expand(i, n) if br > 0 { if ps[br] < upMk { ps[br] = brMk cnt++ } } else { fmt.Printf("%8d%6d\n", n, cnt) break } } n++ } } ms := toMs(time.Since(start)) fmt.Printf("Adding Brazilian primes to the sieve took %.4f ms\n", ms) start = time.Now() for _, s := range []string{"", "odd ", "prime "} { firstFew(s, 20) } fmt.Printf("\nRequired output took %.4f ms\n", toMs(time.Since(start))) fmt.Println("\nDecade count of Brazilian numbers:") n, cnt = 6, 0 for { for cnt < p { n++ if isBr(n) { cnt++ } } ms = toMs(time.Since(start)) fmt.Printf("%15sth is %-15s time: %8.4f ms\n", commatize(cnt), commatize(n), ms) p *= 10 if p > p10 { break } } fmt.Printf("\nTotal elapsed was %.4f ms\n", toMs(time.Since(st0))) }
Break OO privacy
Go
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism. The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory. Note that cheating on your type system is almost universally regarded as unidiomatic at best, and poor programming practice at worst. Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.
package main import ( "bufio" "errors" "fmt" "os" "reflect" "unsafe" ) type foobar struct { Exported int // In Go identifiers that are capitalized are exported, unexported int // while lowercase identifiers are not. } func main() { obj := foobar{12, 42} fmt.Println("obj:", obj) examineAndModify(&obj) fmt.Println("obj:", obj) anotherExample() } // For simplicity this skips several checks. It assumes the thing in the // interface is a pointer without checking (v.Kind()==reflect.Ptr), // it then assumes it is a structure type with two int fields // (v.Kind()==reflect.Struct, f.Type()==reflect.TypeOf(int(0))). func examineAndModify(any interface{}) { v := reflect.ValueOf(any) // get a reflect.Value v = v.Elem() // dereference the pointer fmt.Println(" v:", v, "=", v.Interface()) t := v.Type() // Loop through the struct fields fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet") for i := 0; i < v.NumField(); i++ { f := v.Field(i) // reflect.Value of the field fmt.Printf(" %2d: %-10s %-4s %t\n", i, t.Field(i).Name, f.Type(), f.CanSet()) } // "Exported", field 0, has CanSet==true so we can do: v.Field(0).SetInt(16) // "unexported", field 1, has CanSet==false so the following // would fail at run-time with: // panic: reflect: reflect.Value.SetInt using value obtained using unexported field //v.Field(1).SetInt(43) // However, we can bypass this restriction with the unsafe // package once we know what type it is (so we can use the // correct pointer type, here *int): vp := v.Field(1).Addr() // Take the fields's address up := unsafe.Pointer(vp.Pointer()) // … get an int value of the address and convert it "unsafely" p := (*int)(up) // … and end up with what we want/need fmt.Printf(" vp has type %-14T = %v\n", vp, vp) fmt.Printf(" up has type %-14T = %#0x\n", up, up) fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p) *p = 43 // effectively obj.unexported = 43 // or an incr all on one ulgy line: *(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++ // Note that as-per the package "unsafe" documentation, // the return value from vp.Pointer *must* be converted to // unsafe.Pointer in the same expression; the result is fragile. // // I.e. it is invalid to do: // thisIsFragile := vp.Pointer() // up := unsafe.Pointer(thisIsFragile) } // This time we'll use an external package to demonstrate that it's not // restricted to things defined locally. We'll mess with bufio.Reader's // interal workings by happening to know they have a non-exported // "err error" field. Of course future versions of Go may not have this // field or use it in the same way :). func anotherExample() { r := bufio.NewReader(os.Stdin) // Do the dirty stuff in one ugly and unsafe statement: errp := (*error)(unsafe.Pointer( reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer())) *errp = errors.New("unsafely injected error value into bufio inner workings") _, err := r.ReadByte() fmt.Println("bufio.ReadByte returned error:", err) }
Burrows–Wheeler transform
Go from Python
{{Wikipedia|Burrows-Wheeler_transform}} The Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. More importantly, the transformation is reversible, without needing to store any additional data. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. Source: Burrows-Wheeler transform
package main import ( "fmt" "sort" "strings" ) const stx = "\002" const etx = "\003" func bwt(s string) (string, error) { if strings.Index(s, stx) >= 0 || strings.Index(s, etx) >= 0 { return "", fmt.Errorf("String can't contain STX or ETX") } s = stx + s + etx le := len(s) table := make([]string, le) table[0] = s for i := 1; i < le; i++ { table[i] = s[i:] + s[:i] } sort.Strings(table) lastBytes := make([]byte, le) for i := 0; i < le; i++ { lastBytes[i] = table[i][le-1] } return string(lastBytes), nil } func ibwt(r string) string { le := len(r) table := make([]string, le) for range table { for i := 0; i < le; i++ { table[i] = r[i:i+1] + table[i] } sort.Strings(table) } for _, row := range table { if strings.HasSuffix(row, etx) { return row[1 : le-1] } } return "" } func makePrintable(s string) string { // substitute ^ for STX and | for ETX to print results t := strings.Replace(s, stx, "^", 1) return strings.Replace(t, etx, "|", 1) } func main() { tests := []string{ "banana", "appellee", "dogwood", "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", "\002ABC\003", } for _, test := range tests { fmt.Println(makePrintable(test)) fmt.Print(" --> ") t, err := bwt(test) if err != nil { fmt.Println("ERROR:", err) } else { fmt.Println(makePrintable(t)) } r := ibwt(t) fmt.Println(" -->", r, "\n") } }
CSV data manipulation
Go
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. ;Task: Read a CSV file, change some values and save the changes back to a file. For this task we will use the following CSV file: C1,C2,C3,C4,C5 1,5,9,13,17 2,6,10,14,18 3,7,11,15,19 4,8,12,16,20 Suggestions Show how to add a column, headed 'SUM', of the sums of the rows. If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
CSV to HTML translation
Go
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be ''escaped'' when converted to HTML ;Task: Create a function that takes a string representation of the CSV data and returns a text string of an HTML table representing the CSV data. Use the following data as the CSV text to convert, and show your output. : Character,Speech : The multitude,The messiah! Show us the messiah! : Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! : The multitude,Who are you? : Brians mother,I'm his mother; that's who! : The multitude,Behold his mother! Behold his mother! ;Extra credit: ''Optionally'' allow special formatting for the first row of the table as if it is the tables header row (via preferably; CSS if you must).
package main import ( "bytes" "encoding/csv" "flag" "fmt" "html/template" "strings" ) var csvStr = `Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother!` func main() { headings := flag.Bool("h", false, "format first row as column headings") flag.Parse() if html, err := csvToHtml(csvStr, *headings); err != nil { fmt.Println(err) } else { fmt.Print(html) } } func csvToHtml(csvStr string, headings bool) (string, error) { data, err := csv.NewReader(bytes.NewBufferString(csvStr)).ReadAll() if err != nil { return "", err } tStr := tPlain if headings { tStr = tHeadings } var b strings.Builder err = template.Must(template.New("").Parse(tStr)).Execute(&b, data) return b.String(), err } const ( tPlain = `<table> {{range .}} <tr>{{range .}}<td>{{.}}</td>{{end}}</tr> {{end}}</table> ` tHeadings = `<table>{{if .}} {{range $x, $e := .}}{{if $x}} <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>{{else}} <thead> <tr>{{range .}}<th>{{.}}</th>{{end}}</tr> </thead> <tbody>{{end}}{{end}} </tbody>{{end}} </table> ` )
Calculating the value of e
Go from Kotlin
Calculate the value of ''e''. (''e'' is also known as ''Euler's number'' and ''Napier's constant''.) See details: Calculating the value of e
package main import ( "fmt" "math" ) const epsilon = 1.0e-15 func main() { fact := uint64(1) e := 2.0 n := uint64(2) for { e0 := e fact *= n n++ e += 1.0 / float64(fact) if math.Abs(e - e0) < epsilon { break } } fmt.Printf("e = %.15f\n", e) }
Calkin-Wilf sequence
Go from Wren
The '''Calkin-Wilf sequence''' contains every nonnegative rational number exactly once. It can be calculated recursively as follows: {{math|a1}} = {{math|1}} {{math|an+1}} = {{math|1/(2an+1-an)}} for n > 1 ;Task part 1: * Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: {{math|[a0; a1, a2, ..., an]}} = {{math|[a0; a1, a2 ,..., an-1, 1]}} ;Example: The fraction '''9/4''' has odd continued fraction representation {{math|2; 3, 1}}, giving a binary representation of '''100011''', which means '''9/4''' appears as the '''35th''' term of the sequence. ;Task part 2: * Find the position of the number '''83116''''''/''''''51639''' in the Calkin-Wilf sequence. ;See also: * Wikipedia entry: Calkin-Wilf tree * [[Continued fraction]] * [[Continued fraction/Arithmetic/Construct from rational number]]
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) func calkinWilf(n int) []*big.Rat { cw := make([]*big.Rat, n+1) cw[0] = big.NewRat(1, 1) one := big.NewRat(1, 1) two := big.NewRat(2, 1) for i := 1; i < n; i++ { t := new(big.Rat).Set(cw[i-1]) f, _ := t.Float64() f = math.Floor(f) t.SetFloat64(f) t.Mul(t, two) t.Sub(t, cw[i-1]) t.Add(t, one) t.Inv(t) cw[i] = new(big.Rat).Set(t) } return cw } func toContinued(r *big.Rat) []int { a := r.Num().Int64() b := r.Denom().Int64() var res []int for { res = append(res, int(a/b)) t := a % b a, b = b, t if a == 1 { break } } le := len(res) if le%2 == 0 { // ensure always odd res[le-1]-- res = append(res, 1) } return res } func getTermNumber(cf []int) int { b := "" d := "1" for _, n := range cf { b = strings.Repeat(d, n) + b if d == "1" { d = "0" } else { d = "1" } } i, _ := strconv.ParseInt(b, 2, 64) return int(i) } func commatize(n int) string { s := fmt.Sprintf("%d", n) if n < 0 { s = s[1:] } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if n >= 0 { return s } return "-" + s } func main() { cw := calkinWilf(20) fmt.Println("The first 20 terms of the Calkin-Wilf sequnence are:") for i := 1; i <= 20; i++ { fmt.Printf("%2d: %s\n", i, cw[i-1].RatString()) } fmt.Println() r := big.NewRat(83116, 51639) cf := toContinued(r) tn := getTermNumber(cf) fmt.Printf("%s is the %sth term of the sequence.\n", r.RatString(), commatize(tn)) }
Call a function
Go
Demonstrate the different syntax and semantics provided for calling a function. This may include: :* Calling a function that requires no arguments :* Calling a function with a fixed number of arguments :* Calling a function with optional arguments :* Calling a function with a variable number of arguments :* Calling a function with named arguments :* Using a function in statement context :* Using a function in first-class context within an expression :* Obtaining the return value of a function :* Distinguishing built-in functions and user-defined functions :* Distinguishing subroutines and functions ;* Stating whether arguments are passed by value or by reference ;* Is partial application possible and how This task is ''not'' about defining functions.
package main import "fmt" // int parameter, so arguments will be passed to it by value. func zeroval(ival int) { ival = 0 } // has an *int parameter, meaning that it takes an int pointer. func zeroptr(iptr *int) { *iptr = 0 } func main() { i := 1 fmt.Println("initial:", i) // prt initial: 1 zeroval(i) fmt.Println("zeroval:", i) // prt zeroval: 1 zeroptr(&i) fmt.Println("zeroptr:", i) // prt zeroptr: 0 fmt.Println("pointer:", &i) // prt pointer: 0xc0000140b8 }
Canonicalize CIDR
Go from Ruby
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address. ;Example: Given '''87.70.141.1/22''', your code should output '''87.70.140.0/22''' ;Explanation: An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion. In general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry. The example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 - 87.70.140.0. ;More examples for testing 36.18.154.103/12 - 36.16.0.0/12 62.62.197.11/29 - 62.62.197.8/29 67.137.119.181/4 - 64.0.0.0/4 161.214.74.21/24 - 161.214.74.0/24 184.232.176.184/18 - 184.232.128.0/18
package main import ( "fmt" "log" "strconv" "strings" ) func check(err error) { if err != nil { log.Fatal(err) } } // canonicalize a CIDR block: make sure none of the host bits are set func canonicalize(cidr string) string { // dotted-decimal / bits in network part split := strings.Split(cidr, "/") dotted := split[0] size, err := strconv.Atoi(split[1]) check(err) // get IP as binary string var bin []string for _, n := range strings.Split(dotted, ".") { i, err := strconv.Atoi(n) check(err) bin = append(bin, fmt.Sprintf("%08b", i)) } binary := strings.Join(bin, "") // replace the host part with all zeros binary = binary[0:size] + strings.Repeat("0", 32-size) // convert back to dotted-decimal var canon []string for i := 0; i < len(binary); i += 8 { num, err := strconv.ParseInt(binary[i:i+8], 2, 64) check(err) canon = append(canon, fmt.Sprintf("%d", num)) } // and return return strings.Join(canon, ".") + "/" + split[1] } func main() { tests := []string{ "87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29", "67.137.119.181/4", "161.214.74.21/24", "184.232.176.184/18", } for _, test := range tests { fmt.Printf("%-18s -> %s\n", test, canonicalize(test)) } }
Cantor set
Go from Kotlin
Draw a Cantor set. See details at this Wikipedia webpage: Cantor set
package main import "fmt" const ( width = 81 height = 5 ) var lines [height][width]byte func init() { for i := 0; i < height; i++ { for j := 0; j < width; j++ { lines[i][j] = '*' } } } func cantor(start, len, index int) { seg := len / 3 if seg == 0 { return } for i := index; i < height; i++ { for j := start + seg; j < start + 2 * seg; j++ { lines[i][j] = ' ' } } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } func main() { cantor(0, width, 1) for _, line := range lines { fmt.Println(string(line[:])) } }
Cartesian product of two or more lists
Go
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: ::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: ::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using your function/method, that the product of an empty list with any other list is empty. :: {1, 2} x {} = {} :: {} x {1, 2} = {} For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products: :: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1} :: {1, 2, 3} x {30} x {500, 100} :: {1, 2, 3} x {} x {500, 100}
package main import "fmt" type pair [2]int func cart2(a, b []int) []pair { p := make([]pair, len(a)*len(b)) i := 0 for _, a := range a { for _, b := range b { p[i] = pair{a, b} i++ } } return p } func main() { fmt.Println(cart2([]int{1, 2}, []int{3, 4})) fmt.Println(cart2([]int{3, 4}, []int{1, 2})) fmt.Println(cart2([]int{1, 2}, nil)) fmt.Println(cart2(nil, []int{1, 2})) }
Casting out nines
Go
Task (in three parts): ;Part 1 Write a procedure (say \mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky. Note that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application. With that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be "casting out nines", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1. ;Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: : Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]). : note that 318682 has the same checksum as (101558 + 217124); : note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); : note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2. Demonstrate that your procedure can be used to generate or filter a range of numbers with the property \mathit{co9}(k) = \mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. ;Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: : \mathit{co9}(x) is the residual of x mod 9; : the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k%(\mathit{Base}-1) == (k^2)%(\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. ;related tasks * [[First perfect square in base N with N unique digits]] * [[Kaprekar numbers]]
package main import ( "fmt" "log" "strconv" ) // A casting out nines algorithm. // Quoting from: http://mathforum.org/library/drmath/view/55926.html /* First, for any number we can get a single digit, which I will call the "check digit," by repeatedly adding the digits. That is, we add the digits of the number, then if there is more than one digit in the result we add its digits, and so on until there is only one digit left. ... You may notice that when you add the digits of 6395, if you just ignore the 9, and the 6+3 = 9, you still end up with 5 as your check digit. This is because any 9's make no difference in the result. That's why the process is called "casting out" nines. Also, at any step in the process, you can add digits, not just at the end: to do 8051647, I can say 8 + 5 = 13, which gives 4; plus 1 is 5, plus 6 is 11, which gives 2, plus 4 is 6, plus 7 is 13 which gives 4. I never have to work with numbers bigger than 18. */ // The twist is that co9Peterson returns a function to do casting out nines // in any specified base from 2 to 36. func co9Peterson(base int) (cob func(string) (byte, error), err error) { if base < 2 || base > 36 { return nil, fmt.Errorf("co9Peterson: %d invalid base", base) } // addDigits adds two digits in the specified base. // People perfoming casting out nines by hand would usually have their // addition facts memorized. In a program, a lookup table might be // analogous, but we expediently use features of the programming language // to add digits in the specified base. addDigits := func(a, b byte) (string, error) { ai, err := strconv.ParseInt(string(a), base, 64) if err != nil { return "", err } bi, err := strconv.ParseInt(string(b), base, 64) if err != nil { return "", err } return strconv.FormatInt(ai+bi, base), nil } // a '9' in the specified base. that is, the greatest digit. s9 := strconv.FormatInt(int64(base-1), base) b9 := s9[0] // define result function. The result function may return an error // if n is not a valid number in the specified base. cob = func(n string) (r byte, err error) { r = '0' for i := 0; i < len(n); i++ { // for each digit of the number d := n[i] switch { case d == b9: // if the digit is '9' of the base, cast it out continue // if the result so far is 0, the digit becomes the result case r == '0': r = d continue } // otherwise, add the new digit to the result digit s, err := addDigits(r, d) if err != nil { return 0, err } switch { case s == s9: // if the sum is "9" of the base, cast it out r = '0' continue // if the sum is a single digit, it becomes the result case len(s) == 1: r = s[0] continue } // otherwise, reduce this two digit intermediate result before // continuing. r, err = cob(s) if err != nil { return 0, err } } return } return } // Subset code required by task. Given a base and a range specified with // beginning and ending number in that base, return candidate Kaprekar numbers // based on the observation that k%(base-1) must equal (k*k)%(base-1). // For the % operation, rather than the language built-in operator, use // the method of casting out nines, which in fact implements %(base-1). func subset(base int, begin, end string) (s []string, err error) { // convert begin, end to native integer types for easier iteration begin64, err := strconv.ParseInt(begin, base, 64) if err != nil { return nil, fmt.Errorf("subset begin: %v", err) } end64, err := strconv.ParseInt(end, base, 64) if err != nil { return nil, fmt.Errorf("subset end: %v", err) } // generate casting out nines function for specified base cob, err := co9Peterson(base) if err != nil { return } for k := begin64; k <= end64; k++ { ks := strconv.FormatInt(k, base) rk, err := cob(ks) if err != nil { // assertion panic(err) // this would indicate a bug in subset } rk2, err := cob(strconv.FormatInt(k*k, base)) if err != nil { // assertion panic(err) // this would indicate a bug in subset } // test for candidate Kaprekar number if rk == rk2 { s = append(s, ks) } } return } var testCases = []struct { base int begin, end string kaprekar []string }{ {10, "1", "100", []string{"1", "9", "45", "55", "99"}}, {17, "10", "gg", []string{"3d", "d4", "gg"}}, } func main() { for _, tc := range testCases { fmt.Printf("\nTest case base = %d, begin = %s, end = %s:\n", tc.base, tc.begin, tc.end) s, err := subset(tc.base, tc.begin, tc.end) if err != nil { log.Fatal(err) } fmt.Println("Subset: ", s) fmt.Println("Kaprekar:", tc.kaprekar) sx := 0 for _, k := range tc.kaprekar { for { if sx == len(s) { fmt.Printf("Fail:", k, "not in subset") return } if s[sx] == k { sx++ break } sx++ } } fmt.Println("Valid subset.") } }
Catalan numbers/Pascal's triangle
Go from C++
Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle. ;See: * Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction. * Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition. * Sequence A000108 on OEIS has a lot of information on Catalan Numbers. ;Related Tasks: [[Pascal's triangle]]
package main import "fmt" func main() { const n = 15 t := [n + 2]uint64{0, 1} for i := 1; i <= n; i++ { for j := i; j > 1; j-- { t[j] += t[j-1] } t[i+1] = t[i] for j := i + 1; j > 1; j-- { t[j] += t[j-1] } fmt.Printf("%2d : %d\n", i, t[i+1]-t[i]) } }
Catamorphism
Go
''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. ;Task: Show how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language. ;See also: * Wikipedia article: Fold * Wikipedia article: Catamorphism
package main import ( "fmt" ) func main() { n := []int{1, 2, 3, 4, 5} fmt.Println(reduce(add, n)) fmt.Println(reduce(sub, n)) fmt.Println(reduce(mul, n)) } func add(a int, b int) int { return a + b } func sub(a int, b int) int { return a - b } func mul(a int, b int) int { return a * b } func reduce(rf func(int, int) int, m []int) int { r := m[0] for _, v := range m[1:] { r = rf(r, v) } return r }
Chaocipher
Go from Kotlin
Description: The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ;Task: Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
package main import( "fmt" "strings" "unicode/utf8" ) type Mode int const( Encrypt Mode = iota Decrypt ) const( lAlphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" rAlphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC" ) func Chao(text string, mode Mode, showSteps bool) string { len := len(text) if utf8.RuneCountInString(text) != len { fmt.Println("Text contains non-ASCII characters") return "" } left := lAlphabet right := rAlphabet eText := make([]byte, len) temp := make([]byte, 26) for i := 0; i < len; i++ { if showSteps { fmt.Println(left, " ", right) } var index int if mode == Encrypt { index = strings.IndexByte(right, text[i]) eText[i] = left[index] } else { index = strings.IndexByte(left, text[i]) eText[i] = right[index] } if i == len - 1 { break } // permute left for j := index; j < 26; j++ { temp[j - index] = left[j] } for j := 0; j < index; j++ { temp[26 - index + j] = left[j] } store := temp[1] for j := 2; j < 14; j++ { temp[j - 1] = temp[j] } temp[13] = store left = string(temp[:]) // permute right for j := index; j < 26; j++ { temp[j - index] = right[j] } for j := 0; j < index; j++ { temp[26 - index + j] = right[j] } store = temp[0] for j := 1; j < 26; j++ { temp[j - 1] = temp[j] } temp[25] = store store = temp[2] for j := 3; j < 14; j++ { temp[j - 1] = temp[j] } temp[13] = store right = string(temp[:]) } return string(eText[:]) } func main() { plainText := "WELLDONEISBETTERTHANWELLSAID" fmt.Println("The original plaintext is :", plainText) fmt.Print("\nThe left and right alphabets after each permutation ") fmt.Println("during encryption are :\n") cipherText := Chao(plainText, Encrypt, true) fmt.Println("\nThe ciphertext is :", cipherText) plainText2 := Chao(cipherText, Decrypt, false) fmt.Println("\nThe recovered plaintext is :", plainText2) }
Chaos game
Go
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. ;Task Play the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. ;See also * The Game of Chaos
package main import ( "fmt" "image" "image/color" "image/draw" "image/gif" "log" "math" "math/rand" "os" "time" ) var bwPalette = color.Palette{ color.Transparent, color.White, color.RGBA{R: 0xff, A: 0xff}, color.RGBA{G: 0xff, A: 0xff}, color.RGBA{B: 0xff, A: 0xff}, } func main() { const ( width = 160 frames = 100 pointsPerFrame = 50 delay = 100 * time.Millisecond filename = "chaos_anim.gif" ) var tan60 = math.Sin(math.Pi / 3) height := int(math.Round(float64(width) * tan60)) b := image.Rect(0, 0, width, height) vertices := [...]image.Point{ {0, height}, {width, height}, {width / 2, 0}, } // Make a filled triangle. m := image.NewPaletted(b, bwPalette) for y := b.Min.Y; y < b.Max.Y; y++ { bg := int(math.Round(float64(b.Max.Y-y) / 2 / tan60)) for x := b.Min.X + bg; x < b.Max.X-bg; x++ { m.SetColorIndex(x, y, 1) } } // Pick starting point var p image.Point rand.Seed(time.Now().UnixNano()) p.Y = rand.Intn(height) + b.Min.Y p.X = rand.Intn(width) + b.Min.X // TODO: make within triangle anim := newAnim(frames, delay) addFrame(anim, m) for i := 1; i < frames; i++ { for j := 0; j < pointsPerFrame; j++ { // Pick a random vertex vi := rand.Intn(len(vertices)) v := vertices[vi] // Move p halfway there p.X = (p.X + v.X) / 2 p.Y = (p.Y + v.Y) / 2 m.SetColorIndex(p.X, p.Y, uint8(2+vi)) } addFrame(anim, m) } if err := writeAnim(anim, filename); err != nil { log.Fatal(err) } fmt.Printf("wrote to %q\n", filename) } // Stuff for making a simple GIF animation. func newAnim(frames int, delay time.Duration) *gif.GIF { const gifDelayScale = 10 * time.Millisecond g := &gif.GIF{ Image: make([]*image.Paletted, 0, frames), Delay: make([]int, 1, frames), } g.Delay[0] = int(delay / gifDelayScale) return g } func addFrame(anim *gif.GIF, m *image.Paletted) { b := m.Bounds() dst := image.NewPaletted(b, m.Palette) draw.Draw(dst, b, m, image.ZP, draw.Src) anim.Image = append(anim.Image, dst) if len(anim.Delay) < len(anim.Image) { anim.Delay = append(anim.Delay, anim.Delay[0]) } } func writeAnim(anim *gif.GIF, filename string) error { f, err := os.Create(filename) if err != nil { return err } err = gif.EncodeAll(f, anim) if cerr := f.Close(); err == nil { err = cerr } return err }
Check Machin-like formulas
Go from Python
Machin-like formulas are useful for efficiently computing numerical approximations for \pi ;Task: Verify the following Machin-like formulas are correct by calculating the value of '''tan''' (''right hand side)'' for each equation using exact arithmetic and showing they equal '''1''': : {\pi\over4} = \arctan{1\over2} + \arctan{1\over3} : {\pi\over4} = 2 \arctan{1\over3} + \arctan{1\over7} : {\pi\over4} = 4 \arctan{1\over5} - \arctan{1\over239} : {\pi\over4} = 5 \arctan{1\over7} + 2 \arctan{3\over79} : {\pi\over4} = 5 \arctan{29\over278} + 7 \arctan{3\over79} : {\pi\over4} = \arctan{1\over2} + \arctan{1\over5} + \arctan{1\over8} : {\pi\over4} = 4 \arctan{1\over5} - \arctan{1\over70} + \arctan{1\over99} : {\pi\over4} = 5 \arctan{1\over7} + 4 \arctan{1\over53} + 2 \arctan{1\over4443} : {\pi\over4} = 6 \arctan{1\over8} + 2 \arctan{1\over57} + \arctan{1\over239} : {\pi\over4} = 8 \arctan{1\over10} - \arctan{1\over239} - 4 \arctan{1\over515} : {\pi\over4} = 12 \arctan{1\over18} + 8 \arctan{1\over57} - 5 \arctan{1\over239} : {\pi\over4} = 16 \arctan{1\over21} + 3 \arctan{1\over239} + 4 \arctan{3\over1042} : {\pi\over4} = 22 \arctan{1\over28} + 2 \arctan{1\over443} - 5 \arctan{1\over1393} - 10 \arctan{1\over11018} : {\pi\over4} = 22 \arctan{1\over38} + 17 \arctan{7\over601} + 10 \arctan{7\over8149} : {\pi\over4} = 44 \arctan{1\over57} + 7 \arctan{1\over239} - 12 \arctan{1\over682} + 24 \arctan{1\over12943} : {\pi\over4} = 88 \arctan{1\over172} + 51 \arctan{1\over239} + 32 \arctan{1\over682} + 44 \arctan{1\over5357} + 68 \arctan{1\over12943} and confirm that the following formula is ''incorrect'' by showing '''tan''' (''right hand side)'' is ''not'' '''1''': : {\pi\over4} = 88 \arctan{1\over172} + 51 \arctan{1\over239} + 32 \arctan{1\over682} + 44 \arctan{1\over5357} + 68 \arctan{1\over12944} These identities are useful in calculating the values: : \tan(a + b) = {\tan(a) + \tan(b) \over 1 - \tan(a) \tan(b)} : \tan\left(\arctan{a \over b}\right) = {a \over b} : \tan(-a) = -\tan(a) You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input. Note: to formally prove the formula correct, it would have to be shown that ''{-3 pi \over 4} < right hand side < {5 pi \over 4}'' due to ''\tan()'' periodicity.
package main import ( "fmt" "math/big" ) type mTerm struct { a, n, d int64 } var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, {{5, 1, 7}, {4, 1, 53}, {2, 1, 4443}}, {{6, 1, 8}, {2, 1, 57}, {1, 1, 239}}, {{8, 1, 10}, {-1, 1, 239}, {-4, 1, 515}}, {{12, 1, 18}, {8, 1, 57}, {-5, 1, 239}}, {{16, 1, 21}, {3, 1, 239}, {4, 3, 1042}}, {{22, 1, 28}, {2, 1, 443}, {-5, 1, 1393}, {-10, 1, 11018}}, {{22, 1, 38}, {17, 7, 601}, {10, 7, 8149}}, {{44, 1, 57}, {7, 1, 239}, {-12, 1, 682}, {24, 1, 12943}}, {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12943}}, {{88, 1, 172}, {51, 1, 239}, {32, 1, 682}, {44, 1, 5357}, {68, 1, 12944}}, } func main() { for _, m := range testCases { fmt.Printf("tan %v = %v\n", m, tans(m)) } } var one = big.NewRat(1, 1) func tans(m []mTerm) *big.Rat { if len(m) == 1 { return tanEval(m[0].a, big.NewRat(m[0].n, m[0].d)) } half := len(m) / 2 a := tans(m[:half]) b := tans(m[half:]) r := new(big.Rat) return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b))) } func tanEval(coef int64, f *big.Rat) *big.Rat { if coef == 1 { return f } if coef < 0 { r := tanEval(-coef, f) return r.Neg(r) } ca := coef / 2 cb := coef - ca a := tanEval(ca, f) b := tanEval(cb, f) r := new(big.Rat) return r.Quo(new(big.Rat).Add(a, b), r.Sub(one, r.Mul(a, b))) }
Check output device is a terminal
Go
Demonstrate how to check whether the output device is a terminal or not. ;Related task: * [[Check input device is a terminal]]
package main import ( "os" "fmt" ) func main() { if fileInfo, _ := os.Stdout.Stat(); (fileInfo.Mode() & os.ModeCharDevice) != 0 { fmt.Println("Hello terminal") } else { fmt.Println("Who are you? You're not a terminal") } }
Cheryl's birthday
Go
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. ;Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. ;Related task: * [[Sum and Product Puzzle]] ;References * Wikipedia article of the same name. * Tuple Relational Calculus
package main import ( "fmt" "time" ) type birthday struct{ month, day int } func (b birthday) String() string { return fmt.Sprintf("%s %d", time.Month(b.month), b.day) } func (b birthday) monthUniqueIn(bds []birthday) bool { count := 0 for _, bd := range bds { if bd.month == b.month { count++ } } if count == 1 { return true } return false } func (b birthday) dayUniqueIn(bds []birthday) bool { count := 0 for _, bd := range bds { if bd.day == b.day { count++ } } if count == 1 { return true } return false } func (b birthday) monthWithUniqueDayIn(bds []birthday) bool { for _, bd := range bds { if bd.month == b.month && bd.dayUniqueIn(bds) { return true } } return false } func main() { choices := []birthday{ {5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18}, {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17}, } // Albert knows the month but doesn't know the day. // So the month can't be unique within the choices. var filtered []birthday for _, bd := range choices { if !bd.monthUniqueIn(choices) { filtered = append(filtered, bd) } } // Albert also knows that Bernard doesn't know the answer. // So the month can't have a unique day. var filtered2 []birthday for _, bd := range filtered { if !bd.monthWithUniqueDayIn(filtered) { filtered2 = append(filtered2, bd) } } // Bernard now knows the answer. // So the day must be unique within the remaining choices. var filtered3 []birthday for _, bd := range filtered2 { if bd.dayUniqueIn(filtered2) { filtered3 = append(filtered3, bd) } } // Albert now knows the answer too. // So the month must be unique within the remaining choices. var filtered4 []birthday for _, bd := range filtered3 { if bd.monthUniqueIn(filtered3) { filtered4 = append(filtered4, bd) } } if len(filtered4) == 1 { fmt.Println("Cheryl's birthday is", filtered4[0]) } else { fmt.Println("Something went wrong!") } }
Chinese remainder theorem
Go
Suppose n_1, n_2, \ldots, n_k are positive [[integer]]s that are pairwise co-prime. Then, for any given sequence of integers a_1, a_2, \dots, a_k, there exists an integer x solving the following system of simultaneous congruences: ::: \begin{align} x &\equiv a_1 \pmod{n_1} \\ x &\equiv a_2 \pmod{n_2} \\ &{}\ \ \vdots \\ x &\equiv a_k \pmod{n_k} \end{align} Furthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\ldots n_k. ;Task: Write a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution s where 0 \leq s \leq n_1n_2\ldots n_k. ''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2]. '''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: ::: x \equiv a_i \pmod{n_i} \quad\mathrm{for}\; i = 1, \ldots, k Again, to begin, the product N = n_1n_2 \ldots n_k is defined. Then a solution x can be found as follows: For each i, the integers n_i and N/n_i are co-prime. Using the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. Then, one solution to the system of simultaneous congruences is: ::: x = \sum_{i=1}^k a_i s_i N/n_i and the minimal solution, ::: x \pmod{N}.
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Chinese zodiac
Go
Determine the Chinese zodiac sign and related associations for a given year. Traditionally, the Chinese have counted years using two lists of labels, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades. Years cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit. The celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang. Thus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin. ;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). ;Requisite information: * The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. * The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. * Each element gets two consecutive years; a yang followed by a yin. * The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from. Thus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle. ;Information for optional task: * The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". * The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).
package main import "fmt" var ( animalString = []string{"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"} stemYYString = []string{"Yang", "Yin"} elementString = []string{"Wood", "Fire", "Earth", "Metal", "Water"} stemCh = []rune("甲乙丙丁戊己庚辛壬癸") branchCh = []rune("子丑寅卯辰巳午未申酉戌亥") ) func cz(yr int) (animal, yinYang, element, stemBranch string, cycleYear int) { yr -= 4 stem := yr % 10 branch := yr % 12 return animalString[branch], stemYYString[stem%2], elementString[stem/2], string([]rune{stemCh[stem], branchCh[branch]}), yr%60 + 1 } func main() { for _, yr := range []int{1935, 1938, 1968, 1972, 1976} { a, yy, e, sb, cy := cz(yr) fmt.Printf("%d: %s %s, %s, Cycle year %d %s\n", yr, e, a, yy, cy, sb) } }
Church numerals
Go
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. * '''Church zero''' always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. * '''Church one''' applies its first argument f just once to its second argument x, yielding '''f(x)''' * '''Church two''' applies its first argument f twice to its second argument x, yielding '''f(f(x))''' * and each successive Church numeral applies its first argument one additional time to its second argument, '''f(f(f(x)))''', '''f(f(f(f(x))))''' ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: * Church Zero, * a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), * functions for Addition, Multiplication and Exponentiation over Church numerals, * a function to convert integers to corresponding Church numerals, * and a function to convert Church numerals to corresponding integers. You should: * Derive Church numerals three and four in terms of Church zero and a Church successor function. * use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, * similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, * convert each result back to an integer, and return it or print it to the console.
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } func (c church) add(d church) church { return func(f fn) fn { return func(x any) any { return c(f)(d(f)(x)) } } } func (c church) mul(d church) church { return func(f fn) fn { return func(x any) any { return c(d(f))(x) } } } func (c church) pow(d church) church { di := d.toInt() prod := c for i := 1; i < di; i++ { prod = prod.mul(c) } return prod } func (c church) toInt() int { return c(incr)(0).(int) } func intToChurch(i int) church { if i == 0 { return zero } else { return intToChurch(i - 1).succ() } } func incr(i any) any { return i.(int) + 1 } func main() { z := church(zero) three := z.succ().succ().succ() four := three.succ() fmt.Println("three ->", three.toInt()) fmt.Println("four ->", four.toInt()) fmt.Println("three + four ->", three.add(four).toInt()) fmt.Println("three * four ->", three.mul(four).toInt()) fmt.Println("three ^ four ->", three.pow(four).toInt()) fmt.Println("four ^ three ->", four.pow(three).toInt()) fmt.Println("5 -> five ->", intToChurch(5).toInt()) }
Circles of given radius through two points
Go
2 circles with a given radius through 2 points in 2D space. Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. ;Exceptions: # r==0.0 should be treated as never describing circles (except in the case where the points are coincident). # If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. # If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language. # If the points are too far apart then no circles can be drawn. ;Task detail: * Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''. * Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 ;Related task: * [[Total circles area]]. ;See also: * Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
package main import ( "fmt" "math" ) var ( Two = "Two circles." R0 = "R==0.0 does not describe circles." Co = "Coincident points describe an infinite number of circles." CoR0 = "Coincident points with r==0.0 describe a degenerate circle." Diam = "Points form a diameter and describe only a single circle." Far = "Points too far apart to form circles." ) type point struct{ x, y float64 } func circles(p1, p2 point, r float64) (c1, c2 point, Case string) { if p1 == p2 { if r == 0 { return p1, p1, CoR0 } Case = Co return } if r == 0 { return p1, p2, R0 } dx := p2.x - p1.x dy := p2.y - p1.y q := math.Hypot(dx, dy) if q > 2*r { Case = Far return } m := point{(p1.x + p2.x) / 2, (p1.y + p2.y) / 2} if q == 2*r { return m, m, Diam } d := math.Sqrt(r*r - q*q/4) ox := d * dx / q oy := d * dy / q return point{m.x - oy, m.y + ox}, point{m.x + oy, m.y - ox}, Two } var td = []struct { p1, p2 point r float64 }{ {point{0.1234, 0.9876}, point{0.8765, 0.2345}, 2.0}, {point{0.0000, 2.0000}, point{0.0000, 0.0000}, 1.0}, {point{0.1234, 0.9876}, point{0.1234, 0.9876}, 2.0}, {point{0.1234, 0.9876}, point{0.8765, 0.2345}, 0.5}, {point{0.1234, 0.9876}, point{0.1234, 0.9876}, 0.0}, } func main() { for _, tc := range td { fmt.Println("p1: ", tc.p1) fmt.Println("p2: ", tc.p2) fmt.Println("r: ", tc.r) c1, c2, Case := circles(tc.p1, tc.p2, tc.r) fmt.Println(" ", Case) switch Case { case CoR0, Diam: fmt.Println(" Center: ", c1) case Two: fmt.Println(" Center 1: ", c1) fmt.Println(" Center 2: ", c2) } fmt.Println() } }
Cistercian numerals
Go from Wren
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''. ;How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number: :* The '''upper-right''' quadrant represents the '''ones''' place. :* The '''upper-left''' quadrant represents the '''tens''' place. :* The '''lower-right''' quadrant represents the '''hundreds''' place. :* The '''lower-left''' quadrant represents the '''thousands''' place. Please consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg] ;Task :* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile). :* Use the routine to show the following Cistercian numerals: ::* 0 ::* 1 ::* 20 ::* 300 ::* 4000 ::* 5555 ::* 6789 ::* And a number of your choice! ;Notes Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed -- especially for text output. ;See also :* '''Numberphile - The Forgotten Number System''' :* '''dcode.fr - Online Cistercian numeral converter'''
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" } } func verti(r1, r2, c int) { for r := r1; r <= r2; r++ { n[r][c] = "x" } } func diagd(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r+c-c1][c] = "x" } } func diagu(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r-c+c1][c] = "x" } } var draw map[int]func() // map contains recursive closures func initDraw() { draw = map[int]func(){ 1: func() { horiz(6, 10, 0) }, 2: func() { horiz(6, 10, 4) }, 3: func() { diagd(6, 10, 0) }, 4: func() { diagu(6, 10, 4) }, 5: func() { draw[1](); draw[4]() }, 6: func() { verti(0, 4, 10) }, 7: func() { draw[1](); draw[6]() }, 8: func() { draw[2](); draw[6]() }, 9: func() { draw[1](); draw[8]() }, 10: func() { horiz(0, 4, 0) }, 20: func() { horiz(0, 4, 4) }, 30: func() { diagu(0, 4, 4) }, 40: func() { diagd(0, 4, 0) }, 50: func() { draw[10](); draw[40]() }, 60: func() { verti(0, 4, 0) }, 70: func() { draw[10](); draw[60]() }, 80: func() { draw[20](); draw[60]() }, 90: func() { draw[10](); draw[80]() }, 100: func() { horiz(6, 10, 14) }, 200: func() { horiz(6, 10, 10) }, 300: func() { diagu(6, 10, 14) }, 400: func() { diagd(6, 10, 10) }, 500: func() { draw[100](); draw[400]() }, 600: func() { verti(10, 14, 10) }, 700: func() { draw[100](); draw[600]() }, 800: func() { draw[200](); draw[600]() }, 900: func() { draw[100](); draw[800]() }, 1000: func() { horiz(0, 4, 14) }, 2000: func() { horiz(0, 4, 10) }, 3000: func() { diagd(0, 4, 10) }, 4000: func() { diagu(0, 4, 14) }, 5000: func() { draw[1000](); draw[4000]() }, 6000: func() { verti(10, 14, 0) }, 7000: func() { draw[1000](); draw[6000]() }, 8000: func() { draw[2000](); draw[6000]() }, 9000: func() { draw[1000](); draw[8000]() }, } } func printNumeral() { for i := 0; i < 15; i++ { for j := 0; j < 11; j++ { fmt.Printf("%s ", n[i][j]) } fmt.Println() } fmt.Println() } func main() { initDraw() numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999} for _, number := range numbers { initN() fmt.Printf("%d:\n", number) thousands := number / 1000 number %= 1000 hundreds := number / 100 number %= 100 tens := number / 10 ones := number % 10 if thousands > 0 { draw[thousands*1000]() } if hundreds > 0 { draw[hundreds*100]() } if tens > 0 { draw[tens*10]() } if ones > 0 { draw[ones]() } printNumeral() } }
Closures/Value capture
Go
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. ;Goal: Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: [[Multiple distinct objects]]
package main import "fmt" func main() { fs := make([]func() int, 10) for i := range fs { i := i fs[i] = func() int { return i * i } } fmt.Println("func #0:", fs[0]()) fmt.Println("func #3:", fs[3]()) }
Comma quibbling
Go
Comma quibbling is a task originally set by Eric Lippert in his blog. ;Task: Write a function to generate a string output which is the concatenation of input words from a list/sequence where: # An input of no words produces the output string of just the two brace characters "{}". # An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}". # An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}". # An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}". Test your function with the following series of inputs showing your output here on this page: * [] # (No input words). * ["ABC"] * ["ABC", "DEF"] * ["ABC", "DEF", "G", "H"] Note: Assume words are non-empty strings of uppercase characters for this task.
package main import ( "fmt" "strings" ) func q(s []string) string { switch len(s) { case 0: return "{}" case 1: return "{" + s[0] + "}" case 2: return "{" + s[0] + " and " + s[1] + "}" default: return "{" + strings.Join(s[:len(s)-1], ", ") + " and " + s[len(s)-1] + "}" } } func main() { fmt.Println(q([]string{})) fmt.Println(q([]string{"ABC"})) fmt.Println(q([]string{"ABC", "DEF"})) fmt.Println(q([]string{"ABC", "DEF", "G", "H"})) }
Command-line arguments
Go
{{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]]. See also [[Program name]]. For parsing command line arguments intelligently, see [[Parsing command-line arguments]]. Example command line: myprogram -c "alpha beta" -h "gamma"
package main import ( "fmt" "os" ) func main() { for i, x := range os.Args[1:] { fmt.Printf("the argument #%d is %s\n", i, x) } }
Compare a list of strings
Go
Given a list of arbitrarily many strings, show how to: * test if they are all lexically '''equal''' * test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)'' Each of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. If the input list has less than two elements, the tests should always return true. There is ''no'' need to provide a complete program and output. Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible. Try to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers. If you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature.
package cmp func AllEqual(strings []string) bool { for _, s := range strings { if s != strings[0] { return false } } return true } func AllLessThan(strings []string) bool { for i := 1; i < len(strings); i++ { if !(strings[i - 1] < s) { return false } } return true }
Compile-time calculation
Go
Some programming languages allow calculation of values at compile time. ;Task: Calculate 10! (ten factorial) at compile time. Print the result when the program is run. Discuss what limitations apply to compile-time calculations in your language.
package main import "fmt" func main() { fmt.Println(2*3*4*5*6*7*8*9*10) }
Compiler/AST interpreter
Go from C
The C and Python versions can be considered reference implementations. ;Related Tasks * Lexical Analyzer task * Syntax Analyzer task * Code Generator task * Virtual Machine Interpreter task __TOC__
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) type NodeType int const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ndDiv ndMod ndAdd ndSub ndLss ndLeq ndGtr ndGeq ndEql ndNeq ndAnd ndOr ) type Tree struct { nodeType NodeType left *Tree right *Tree value int } // dependency: Ordered by NodeType, must remain in same order as NodeType enum type atr struct { enumText string nodeType NodeType } var atrs = []atr{ {"Identifier", ndIdent}, {"String", ndString}, {"Integer", ndInteger}, {"Sequence", ndSequence}, {"If", ndIf}, {"Prtc", ndPrtc}, {"Prts", ndPrts}, {"Prti", ndPrti}, {"While", ndWhile}, {"Assign", ndAssign}, {"Negate", ndNegate}, {"Not", ndNot}, {"Multiply", ndMul}, {"Divide", ndDiv}, {"Mod", ndMod}, {"Add", ndAdd}, {"Subtract", ndSub}, {"Less", ndLss}, {"LessEqual", ndLeq}, {"Greater", ndGtr}, {"GreaterEqual", ndGeq}, {"Equal", ndEql}, {"NotEqual", ndNeq}, {"And", ndAnd}, {"Or", ndOr}, } var ( stringPool []string globalNames []string globalValues = make(map[int]int) ) var ( err error scanner *bufio.Scanner ) func reportError(msg string) { log.Fatalf("error : %s\n", msg) } func check(err error) { if err != nil { log.Fatal(err) } } func btoi(b bool) int { if b { return 1 } return 0 } func itob(i int) bool { if i == 0 { return false } return true } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, 0} } func makeLeaf(nodeType NodeType, value int) *Tree { return &Tree{nodeType, nil, nil, value} } func interp(x *Tree) int { // interpret the parse tree if x == nil { return 0 } switch x.nodeType { case ndInteger: return x.value case ndIdent: return globalValues[x.value] case ndString: return x.value case ndAssign: n := interp(x.right) globalValues[x.left.value] = n return n case ndAdd: return interp(x.left) + interp(x.right) case ndSub: return interp(x.left) - interp(x.right) case ndMul: return interp(x.left) * interp(x.right) case ndDiv: return interp(x.left) / interp(x.right) case ndMod: return interp(x.left) % interp(x.right) case ndLss: return btoi(interp(x.left) < interp(x.right)) case ndGtr: return btoi(interp(x.left) > interp(x.right)) case ndLeq: return btoi(interp(x.left) <= interp(x.right)) case ndEql: return btoi(interp(x.left) == interp(x.right)) case ndNeq: return btoi(interp(x.left) != interp(x.right)) case ndAnd: return btoi(itob(interp(x.left)) && itob(interp(x.right))) case ndOr: return btoi(itob(interp(x.left)) || itob(interp(x.right))) case ndNegate: return -interp(x.left) case ndNot: if interp(x.left) == 0 { return 1 } return 0 case ndIf: if interp(x.left) != 0 { interp(x.right.left) } else { interp(x.right.right) } return 0 case ndWhile: for interp(x.left) != 0 { interp(x.right) } return 0 case ndPrtc: fmt.Printf("%c", interp(x.left)) return 0 case ndPrti: fmt.Printf("%d", interp(x.left)) return 0 case ndPrts: fmt.Print(stringPool[interp(x.left)]) return 0 case ndSequence: interp(x.left) interp(x.right) return 0 default: reportError(fmt.Sprintf("interp: unknown tree type %d\n", x.nodeType)) } return 0 } func getEnumValue(name string) NodeType { for _, atr := range atrs { if atr.enumText == name { return atr.nodeType } } reportError(fmt.Sprintf("Unknown token %s\n", name)) return -1 } func fetchStringOffset(s string) int { var d strings.Builder s = s[1 : len(s)-1] for i := 0; i < len(s); i++ { if s[i] == '\\' && (i+1) < len(s) { if s[i+1] == 'n' { d.WriteByte('\n') i++ } else if s[i+1] == '\\' { d.WriteByte('\\') i++ } } else { d.WriteByte(s[i]) } } s = d.String() for i := 0; i < len(stringPool); i++ { if s == stringPool[i] { return i } } stringPool = append(stringPool, s) return len(stringPool) - 1 } func fetchVarOffset(name string) int { for i := 0; i < len(globalNames); i++ { if globalNames[i] == name { return i } } globalNames = append(globalNames, name) return len(globalNames) - 1 } func loadAst() *Tree { var nodeType NodeType var s string if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") tokens := strings.Fields(line) first := tokens[0] if first[0] == ';' { return nil } nodeType = getEnumValue(first) le := len(tokens) if le == 2 { s = tokens[1] } else if le > 2 { idx := strings.Index(line, `"`) s = line[idx:] } } check(scanner.Err()) if s != "" { var n int switch nodeType { case ndIdent: n = fetchVarOffset(s) case ndInteger: n, err = strconv.Atoi(s) check(err) case ndString: n = fetchStringOffset(s) default: reportError(fmt.Sprintf("Unknown node type: %s\n", s)) } return makeLeaf(nodeType, n) } left := loadAst() right := loadAst() return makeNode(nodeType, left, right) } func main() { ast, err := os.Open("ast.txt") check(err) defer ast.Close() scanner = bufio.NewScanner(ast) x := loadAst() interp(x) }
Compiler/code generator
Go from C
The C and Python versions can be considered reference implementations. ;Related Tasks * Lexical Analyzer task * Syntax Analyzer task * Virtual Machine Interpreter task * AST Interpreter task __TOC__
package main import ( "bufio" "encoding/binary" "fmt" "log" "os" "strconv" "strings" ) type NodeType int const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ndDiv ndMod ndAdd ndSub ndLss ndLeq ndGtr ndGeq ndEql ndNeq ndAnd ndOr ) type code = byte const ( fetch code = iota store push add sub mul div mod lt gt le ge eq ne and or neg not jmp jz prtc prts prti halt ) type Tree struct { nodeType NodeType left *Tree right *Tree value string } // dependency: Ordered by NodeType, must remain in same order as NodeType enum type atr struct { enumText string nodeType NodeType opcode code } var atrs = []atr{ {"Identifier", ndIdent, 255}, {"String", ndString, 255}, {"Integer", ndInteger, 255}, {"Sequence", ndSequence, 255}, {"If", ndIf, 255}, {"Prtc", ndPrtc, 255}, {"Prts", ndPrts, 255}, {"Prti", ndPrti, 255}, {"While", ndWhile, 255}, {"Assign", ndAssign, 255}, {"Negate", ndNegate, neg}, {"Not", ndNot, not}, {"Multiply", ndMul, mul}, {"Divide", ndDiv, div}, {"Mod", ndMod, mod}, {"Add", ndAdd, add}, {"Subtract", ndSub, sub}, {"Less", ndLss, lt}, {"LessEqual", ndLeq, le}, {"Greater", ndGtr, gt}, {"GreaterEqual", ndGeq, ge}, {"Equal", ndEql, eq}, {"NotEqual", ndNeq, ne}, {"And", ndAnd, and}, {"Or", ndOr, or}, } var ( stringPool []string globals []string object []code ) var ( err error scanner *bufio.Scanner ) func reportError(msg string) { log.Fatalf("error : %s\n", msg) } func check(err error) { if err != nil { log.Fatal(err) } } func nodeType2Op(nodeType NodeType) code { return atrs[nodeType].opcode } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, ""} } func makeLeaf(nodeType NodeType, value string) *Tree { return &Tree{nodeType, nil, nil, value} } /*** Code generator ***/ func emitByte(c code) { object = append(object, c) } func emitWord(n int) { bs := make([]byte, 4) binary.LittleEndian.PutUint32(bs, uint32(n)) for _, b := range bs { emitByte(code(b)) } } func emitWordAt(at, n int) { bs := make([]byte, 4) binary.LittleEndian.PutUint32(bs, uint32(n)) for i := at; i < at+4; i++ { object[i] = code(bs[i-at]) } } func hole() int { t := len(object) emitWord(0) return t } func fetchVarOffset(id string) int { for i := 0; i < len(globals); i++ { if globals[i] == id { return i } } globals = append(globals, id) return len(globals) - 1 } func fetchStringOffset(st string) int { for i := 0; i < len(stringPool); i++ { if stringPool[i] == st { return i } } stringPool = append(stringPool, st) return len(stringPool) - 1 } func codeGen(x *Tree) { if x == nil { return } var n, p1, p2 int switch x.nodeType { case ndIdent: emitByte(fetch) n = fetchVarOffset(x.value) emitWord(n) case ndInteger: emitByte(push) n, err = strconv.Atoi(x.value) check(err) emitWord(n) case ndString: emitByte(push) n = fetchStringOffset(x.value) emitWord(n) case ndAssign: n = fetchVarOffset(x.left.value) codeGen(x.right) emitByte(store) emitWord(n) case ndIf: codeGen(x.left) // if expr emitByte(jz) // if false, jump p1 = hole() // make room forjump dest codeGen(x.right.left) // if true statements if x.right.right != nil { emitByte(jmp) p2 = hole() } emitWordAt(p1, len(object)-p1) if x.right.right != nil { codeGen(x.right.right) emitWordAt(p2, len(object)-p2) } case ndWhile: p1 = len(object) codeGen(x.left) // while expr emitByte(jz) // if false, jump p2 = hole() // make room for jump dest codeGen(x.right) // statements emitByte(jmp) // back to the top emitWord(p1 - len(object)) // plug the top emitWordAt(p2, len(object)-p2) // plug the 'if false, jump' case ndSequence: codeGen(x.left) codeGen(x.right) case ndPrtc: codeGen(x.left) emitByte(prtc) case ndPrti: codeGen(x.left) emitByte(prti) case ndPrts: codeGen(x.left) emitByte(prts) case ndLss, ndGtr, ndLeq, ndGeq, ndEql, ndNeq, ndAnd, ndOr, ndSub, ndAdd, ndDiv, ndMul, ndMod: codeGen(x.left) codeGen(x.right) emitByte(nodeType2Op(x.nodeType)) case ndNegate, ndNot: codeGen(x.left) emitByte(nodeType2Op(x.nodeType)) default: msg := fmt.Sprintf("error in code generator - found %d, expecting operator\n", x.nodeType) reportError(msg) } } func codeFinish() { emitByte(halt) } func listCode() { fmt.Printf("Datasize: %d Strings: %d\n", len(globals), len(stringPool)) for _, s := range stringPool { fmt.Println(s) } pc := 0 for pc < len(object) { fmt.Printf("%5d ", pc) op := object[pc] pc++ switch op { case fetch: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("fetch [%d]\n", x) pc += 4 case store: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("store [%d]\n", x) pc += 4 case push: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("push %d\n", x) pc += 4 case add: fmt.Println("add") case sub: fmt.Println("sub") case mul: fmt.Println("mul") case div: fmt.Println("div") case mod: fmt.Println("mod") case lt: fmt.Println("lt") case gt: fmt.Println("gt") case le: fmt.Println("le") case ge: fmt.Println("ge") case eq: fmt.Println("eq") case ne: fmt.Println("ne") case and: fmt.Println("and") case or: fmt.Println("or") case neg: fmt.Println("neg") case not: fmt.Println("not") case jmp: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("jmp (%d) %d\n", x, int32(pc)+x) pc += 4 case jz: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) fmt.Printf("jz (%d) %d\n", x, int32(pc)+x) pc += 4 case prtc: fmt.Println("prtc") case prti: fmt.Println("prti") case prts: fmt.Println("prts") case halt: fmt.Println("halt") default: reportError(fmt.Sprintf("listCode: Unknown opcode %d", op)) } } } func getEnumValue(name string) NodeType { for _, atr := range atrs { if atr.enumText == name { return atr.nodeType } } reportError(fmt.Sprintf("Unknown token %s\n", name)) return -1 } func loadAst() *Tree { var nodeType NodeType var s string if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") tokens := strings.Fields(line) first := tokens[0] if first[0] == ';' { return nil } nodeType = getEnumValue(first) le := len(tokens) if le == 2 { s = tokens[1] } else if le > 2 { idx := strings.Index(line, `"`) s = line[idx:] } } check(scanner.Err()) if s != "" { return makeLeaf(nodeType, s) } left := loadAst() right := loadAst() return makeNode(nodeType, left, right) } func main() { ast, err := os.Open("ast.txt") check(err) defer ast.Close() scanner = bufio.NewScanner(ast) codeGen(loadAst()) codeFinish() listCode() }
Compiler/lexical analyzer
Go from FreeBASIC
The C and Python versions can be considered reference implementations. ;Related Tasks * Syntax Analyzer task * Code Generator task * Virtual Machine Interpreter task * AST Interpreter task
package main import ( "bufio" "fmt" "log" "os" ) type TokenType int const ( tkEOI TokenType = iota tkMul tkDiv tkMod tkAdd tkSub tkNegate tkNot tkLss tkLeq tkGtr tkGeq tkEq tkNeq tkAssign tkAnd tkOr tkIf tkElse tkWhile tkPrint tkPutc tkLparen tkRparen tkLbrace tkRbrace tkSemi tkComma tkIdent tkInteger tkString ) type Symbol struct { name string tok TokenType } // symbol table var symtab []Symbol var scanner *bufio.Scanner var ( curLine = "" curCh byte lineNum = 0 colNum = 0 ) const etx byte = 4 // used to signify EOI func isDigit(ch byte) bool { return ch >= '0' && ch <= '9' } func isAlnum(ch byte) bool { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || isDigit(ch) } func errorMsg(eline, ecol int, msg string) { log.Fatalf("(%d:%d) %s", eline, ecol, msg) } // add an identifier to the symbol table func install(name string, tok TokenType) { sym := Symbol{name, tok} symtab = append(symtab, sym) } // search for an identifier in the symbol table func lookup(name string) int { for i := 0; i < len(symtab); i++ { if symtab[i].name == name { return i } } return -1 } // read the next line of input from the source file func nextLine() { if scanner.Scan() { curLine = scanner.Text() lineNum++ colNum = 0 if curLine == "" { // skip blank lines nextLine() } } else { err := scanner.Err() if err == nil { // EOF curCh = etx curLine = "" lineNum++ colNum = 1 } else { log.Fatal(err) } } } // get the next char func nextChar() { if colNum >= len(curLine) { nextLine() } if colNum < len(curLine) { curCh = curLine[colNum] colNum++ } } func follow(eline, ecol int, expect byte, ifyes, ifno TokenType) TokenType { if curCh == expect { nextChar() return ifyes } if ifno == tkEOI { errorMsg(eline, ecol, "follow unrecognized character: "+string(curCh)) } return ifno } func gettok() (eline, ecol int, tok TokenType, v string) { // skip whitespace for curCh == ' ' || curCh == '\t' || curCh == '\n' { nextChar() } eline = lineNum ecol = colNum switch curCh { case etx: tok = tkEOI return case '{': tok = tkLbrace nextChar() return case '}': tok = tkRbrace nextChar() return case '(': tok = tkLparen nextChar() return case ')': tok = tkRparen nextChar() return case '+': tok = tkAdd nextChar() return case '-': tok = tkSub nextChar() return case '*': tok = tkMul nextChar() return case '%': tok = tkMod nextChar() return case ';': tok = tkSemi nextChar() return case ',': tok = tkComma nextChar() return case '/': // div or comment nextChar() if curCh != '*' { tok = tkDiv return } // skip comments nextChar() for { if curCh == '*' { nextChar() if curCh == '/' { nextChar() eline, ecol, tok, v = gettok() return } } else if curCh == etx { errorMsg(eline, ecol, "EOF in comment") } else { nextChar() } } case '\'': // single char literals nextChar() v = fmt.Sprintf("%d", curCh) if curCh == '\'' { errorMsg(eline, ecol, "Empty character constant") } if curCh == '\\' { nextChar() if curCh == 'n' { v = "10" } else if curCh == '\\' { v = "92" } else { errorMsg(eline, ecol, "unknown escape sequence: "+string(curCh)) } } nextChar() if curCh != '\'' { errorMsg(eline, ecol, "multi-character constant") } nextChar() tok = tkInteger return case '<': nextChar() tok = follow(eline, ecol, '=', tkLeq, tkLss) return case '>': nextChar() tok = follow(eline, ecol, '=', tkGeq, tkGtr) return case '!': nextChar() tok = follow(eline, ecol, '=', tkNeq, tkNot) return case '=': nextChar() tok = follow(eline, ecol, '=', tkEq, tkAssign) return case '&': nextChar() tok = follow(eline, ecol, '&', tkAnd, tkEOI) return case '|': nextChar() tok = follow(eline, ecol, '|', tkOr, tkEOI) return case '"': // string v = string(curCh) nextChar() for curCh != '"' { if curCh == '\n' { errorMsg(eline, ecol, "EOL in string") } if curCh == etx { errorMsg(eline, ecol, "EOF in string") } v += string(curCh) nextChar() } v += string(curCh) nextChar() tok = tkString return default: // integers or identifiers isNumber := isDigit(curCh) v = "" for isAlnum(curCh) || curCh == '_' { if !isDigit(curCh) { isNumber = false } v += string(curCh) nextChar() } if len(v) == 0 { errorMsg(eline, ecol, "unknown character: "+string(curCh)) } if isDigit(v[0]) { if !isNumber { errorMsg(eline, ecol, "invalid number: "+string(curCh)) } tok = tkInteger return } index := lookup(v) if index == -1 { tok = tkIdent } else { tok = symtab[index].tok } return } } func initLex() { install("else", tkElse) install("if", tkIf) install("print", tkPrint) install("putc", tkPutc) install("while", tkWhile) nextChar() } func process() { tokMap := make(map[TokenType]string) tokMap[tkEOI] = "End_of_input" tokMap[tkMul] = "Op_multiply" tokMap[tkDiv] = "Op_divide" tokMap[tkMod] = "Op_mod" tokMap[tkAdd] = "Op_add" tokMap[tkSub] = "Op_subtract" tokMap[tkNegate] = "Op_negate" tokMap[tkNot] = "Op_not" tokMap[tkLss] = "Op_less" tokMap[tkLeq] = "Op_lessequal" tokMap[tkGtr] = "Op_greater" tokMap[tkGeq] = "Op_greaterequal" tokMap[tkEq] = "Op_equal" tokMap[tkNeq] = "Op_notequal" tokMap[tkAssign] = "Op_assign" tokMap[tkAnd] = "Op_and" tokMap[tkOr] = "Op_or" tokMap[tkIf] = "Keyword_if" tokMap[tkElse] = "Keyword_else" tokMap[tkWhile] = "Keyword_while" tokMap[tkPrint] = "Keyword_print" tokMap[tkPutc] = "Keyword_putc" tokMap[tkLparen] = "LeftParen" tokMap[tkRparen] = "RightParen" tokMap[tkLbrace] = "LeftBrace" tokMap[tkRbrace] = "RightBrace" tokMap[tkSemi] = "Semicolon" tokMap[tkComma] = "Comma" tokMap[tkIdent] = "Identifier" tokMap[tkInteger] = "Integer" tokMap[tkString] = "String" for { eline, ecol, tok, v := gettok() fmt.Printf("%5d %5d %-16s", eline, ecol, tokMap[tok]) if tok == tkInteger || tok == tkIdent || tok == tkString { fmt.Println(v) } else { fmt.Println() } if tok == tkEOI { return } } } func check(err error) { if err != nil { log.Fatal(err) } } func main() { if len(os.Args) < 2 { fmt.Println("Filename required") return } f, err := os.Open(os.Args[1]) check(err) defer f.Close() scanner = bufio.NewScanner(f) initLex() process() }
Compiler/syntax analyzer
Go from C
The C and Python versions can be considered reference implementations. ;Related Tasks * Lexical Analyzer task * Code Generator task * Virtual Machine Interpreter task * AST Interpreter task __TOC__
package main import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) type TokenType int const ( tkEOI TokenType = iota tkMul tkDiv tkMod tkAdd tkSub tkNegate tkNot tkLss tkLeq tkGtr tkGeq tkEql tkNeq tkAssign tkAnd tkOr tkIf tkElse tkWhile tkPrint tkPutc tkLparen tkRparen tkLbrace tkRbrace tkSemi tkComma tkIdent tkInteger tkString ) type NodeType int const ( ndIdent NodeType = iota ndString ndInteger ndSequence ndIf ndPrtc ndPrts ndPrti ndWhile ndAssign ndNegate ndNot ndMul ndDiv ndMod ndAdd ndSub ndLss ndLeq ndGtr ndGeq ndEql ndNeq ndAnd ndOr ) type tokS struct { tok TokenType errLn int errCol int text string // ident or string literal or integer value } type Tree struct { nodeType NodeType left *Tree right *Tree value string } // dependency: Ordered by tok, must remain in same order as TokenType consts type atr struct { text string enumText string tok TokenType rightAssociative bool isBinary bool isUnary bool precedence int nodeType NodeType } var atrs = []atr{ {"EOI", "End_of_input", tkEOI, false, false, false, -1, -1}, {"*", "Op_multiply", tkMul, false, true, false, 13, ndMul}, {"/", "Op_divide", tkDiv, false, true, false, 13, ndDiv}, {"%", "Op_mod", tkMod, false, true, false, 13, ndMod}, {"+", "Op_add", tkAdd, false, true, false, 12, ndAdd}, {"-", "Op_subtract", tkSub, false, true, false, 12, ndSub}, {"-", "Op_negate", tkNegate, false, false, true, 14, ndNegate}, {"!", "Op_not", tkNot, false, false, true, 14, ndNot}, {"<", "Op_less", tkLss, false, true, false, 10, ndLss}, {"<=", "Op_lessequal", tkLeq, false, true, false, 10, ndLeq}, {">", "Op_greater", tkGtr, false, true, false, 10, ndGtr}, {">=", "Op_greaterequal", tkGeq, false, true, false, 10, ndGeq}, {"==", "Op_equal", tkEql, false, true, false, 9, ndEql}, {"!=", "Op_notequal", tkNeq, false, true, false, 9, ndNeq}, {"=", "Op_assign", tkAssign, false, false, false, -1, ndAssign}, {"&&", "Op_and", tkAnd, false, true, false, 5, ndAnd}, {"||", "Op_or", tkOr, false, true, false, 4, ndOr}, {"if", "Keyword_if", tkIf, false, false, false, -1, ndIf}, {"else", "Keyword_else", tkElse, false, false, false, -1, -1}, {"while", "Keyword_while", tkWhile, false, false, false, -1, ndWhile}, {"print", "Keyword_print", tkPrint, false, false, false, -1, -1}, {"putc", "Keyword_putc", tkPutc, false, false, false, -1, -1}, {"(", "LeftParen", tkLparen, false, false, false, -1, -1}, {")", "RightParen", tkRparen, false, false, false, -1, -1}, {"{", "LeftBrace", tkLbrace, false, false, false, -1, -1}, {"}", "RightBrace", tkRbrace, false, false, false, -1, -1}, {";", "Semicolon", tkSemi, false, false, false, -1, -1}, {",", "Comma", tkComma, false, false, false, -1, -1}, {"Ident", "Identifier", tkIdent, false, false, false, -1, ndIdent}, {"Integer literal", "Integer", tkInteger, false, false, false, -1, ndInteger}, {"String literal", "String", tkString, false, false, false, -1, ndString}, } var displayNodes = []string{ "Identifier", "String", "Integer", "Sequence", "If", "Prtc", "Prts", "Prti", "While", "Assign", "Negate", "Not", "Multiply", "Divide", "Mod", "Add", "Subtract", "Less", "LessEqual", "Greater", "GreaterEqual", "Equal", "NotEqual", "And", "Or", } var ( err error token tokS scanner *bufio.Scanner ) func reportError(errLine, errCol int, msg string) { log.Fatalf("(%d, %d) error : %s\n", errLine, errCol, msg) } func check(err error) { if err != nil { log.Fatal(err) } } func getEum(name string) TokenType { // return internal version of name# for _, atr := range atrs { if atr.enumText == name { return atr.tok } } reportError(0, 0, fmt.Sprintf("Unknown token %s\n", name)) return tkEOI } func getTok() tokS { tok := tokS{} if scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") fields := strings.Fields(line) // [ ]*{lineno}[ ]+{colno}[ ]+token[ ]+optional tok.errLn, err = strconv.Atoi(fields[0]) check(err) tok.errCol, err = strconv.Atoi(fields[1]) check(err) tok.tok = getEum(fields[2]) le := len(fields) if le == 4 { tok.text = fields[3] } else if le > 4 { idx := strings.Index(line, `"`) tok.text = line[idx:] } } check(scanner.Err()) return tok } func makeNode(nodeType NodeType, left *Tree, right *Tree) *Tree { return &Tree{nodeType, left, right, ""} } func makeLeaf(nodeType NodeType, value string) *Tree { return &Tree{nodeType, nil, nil, value} } func expect(msg string, s TokenType) { if token.tok == s { token = getTok() return } reportError(token.errLn, token.errCol, fmt.Sprintf("%s: Expecting '%s', found '%s'\n", msg, atrs[s].text, atrs[token.tok].text)) } func expr(p int) *Tree { var x, node *Tree switch token.tok { case tkLparen: x = parenExpr() case tkSub, tkAdd: op := token.tok token = getTok() node = expr(atrs[tkNegate].precedence) if op == tkSub { x = makeNode(ndNegate, node, nil) } else { x = node } case tkNot: token = getTok() x = makeNode(ndNot, expr(atrs[tkNot].precedence), nil) case tkIdent: x = makeLeaf(ndIdent, token.text) token = getTok() case tkInteger: x = makeLeaf(ndInteger, token.text) token = getTok() default: reportError(token.errLn, token.errCol, fmt.Sprintf("Expecting a primary, found: %s\n", atrs[token.tok].text)) } for atrs[token.tok].isBinary && atrs[token.tok].precedence >= p { op := token.tok token = getTok() q := atrs[op].precedence if !atrs[op].rightAssociative { q++ } node = expr(q) x = makeNode(atrs[op].nodeType, x, node) } return x } func parenExpr() *Tree { expect("parenExpr", tkLparen) t := expr(0) expect("parenExpr", tkRparen) return t } func stmt() *Tree { var t, v, e, s, s2 *Tree switch token.tok { case tkIf: token = getTok() e = parenExpr() s = stmt() s2 = nil if token.tok == tkElse { token = getTok() s2 = stmt() } t = makeNode(ndIf, e, makeNode(ndIf, s, s2)) case tkPutc: token = getTok() e = parenExpr() t = makeNode(ndPrtc, e, nil) expect("Putc", tkSemi) case tkPrint: // print '(' expr {',' expr} ')' token = getTok() for expect("Print", tkLparen); ; expect("Print", tkComma) { if token.tok == tkString { e = makeNode(ndPrts, makeLeaf(ndString, token.text), nil) token = getTok() } else { e = makeNode(ndPrti, expr(0), nil) } t = makeNode(ndSequence, t, e) if token.tok != tkComma { break } } expect("Print", tkRparen) expect("Print", tkSemi) case tkSemi: token = getTok() case tkIdent: v = makeLeaf(ndIdent, token.text) token = getTok() expect("assign", tkAssign) e = expr(0) t = makeNode(ndAssign, v, e) expect("assign", tkSemi) case tkWhile: token = getTok() e = parenExpr() s = stmt() t = makeNode(ndWhile, e, s) case tkLbrace: // {stmt} for expect("Lbrace", tkLbrace); token.tok != tkRbrace && token.tok != tkEOI; { t = makeNode(ndSequence, t, stmt()) } expect("Lbrace", tkRbrace) case tkEOI: // do nothing default: reportError(token.errLn, token.errCol, fmt.Sprintf("expecting start of statement, found '%s'\n", atrs[token.tok].text)) } return t } func parse() *Tree { var t *Tree token = getTok() for { t = makeNode(ndSequence, t, stmt()) if t == nil || token.tok == tkEOI { break } } return t } func prtAst(t *Tree) { if t == nil { fmt.Print(";\n") } else { fmt.Printf("%-14s ", displayNodes[t.nodeType]) if t.nodeType == ndIdent || t.nodeType == ndInteger || t.nodeType == ndString { fmt.Printf("%s\n", t.value) } else { fmt.Println() prtAst(t.left) prtAst(t.right) } } } func main() { source, err := os.Open("source.txt") check(err) defer source.Close() scanner = bufio.NewScanner(source) prtAst(parse()) }
Compiler/virtual machine interpreter
Go from Python
The C and Python versions can be considered reference implementations. ;Related Tasks * Lexical Analyzer task * Syntax Analyzer task * Code Generator task * AST Interpreter task __TOC__
package main import ( "bufio" "encoding/binary" "fmt" "log" "math" "os" "strconv" "strings" ) type code = byte const ( fetch code = iota store push add sub mul div mod lt gt le ge eq ne and or neg not jmp jz prtc prts prti halt ) var codeMap = map[string]code{ "fetch": fetch, "store": store, "push": push, "add": add, "sub": sub, "mul": mul, "div": div, "mod": mod, "lt": lt, "gt": gt, "le": le, "ge": ge, "eq": eq, "ne": ne, "and": and, "or": or, "neg": neg, "not": not, "jmp": jmp, "jz": jz, "prtc": prtc, "prts": prts, "prti": prti, "halt": halt, } var ( err error scanner *bufio.Scanner object []code stringPool []string ) func reportError(msg string) { log.Fatalf("error : %s\n", msg) } func check(err error) { if err != nil { log.Fatal(err) } } func btoi(b bool) int32 { if b { return 1 } return 0 } func itob(i int32) bool { if i != 0 { return true } return false } func emitByte(c code) { object = append(object, c) } func emitWord(n int) { bs := make([]byte, 4) binary.LittleEndian.PutUint32(bs, uint32(n)) for _, b := range bs { emitByte(code(b)) } } /*** Virtual Machine interpreter ***/ func runVM(dataSize int) { stack := make([]int32, dataSize+1) pc := int32(0) for { op := object[pc] pc++ switch op { case fetch: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) stack = append(stack, stack[x]) pc += 4 case store: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) ln := len(stack) stack[x] = stack[ln-1] stack = stack[:ln-1] pc += 4 case push: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) stack = append(stack, x) pc += 4 case add: ln := len(stack) stack[ln-2] += stack[ln-1] stack = stack[:ln-1] case sub: ln := len(stack) stack[ln-2] -= stack[ln-1] stack = stack[:ln-1] case mul: ln := len(stack) stack[ln-2] *= stack[ln-1] stack = stack[:ln-1] case div: ln := len(stack) stack[ln-2] = int32(float64(stack[ln-2]) / float64(stack[ln-1])) stack = stack[:ln-1] case mod: ln := len(stack) stack[ln-2] = int32(math.Mod(float64(stack[ln-2]), float64(stack[ln-1]))) stack = stack[:ln-1] case lt: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] < stack[ln-1]) stack = stack[:ln-1] case gt: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] > stack[ln-1]) stack = stack[:ln-1] case le: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] <= stack[ln-1]) stack = stack[:ln-1] case ge: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] >= stack[ln-1]) stack = stack[:ln-1] case eq: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] == stack[ln-1]) stack = stack[:ln-1] case ne: ln := len(stack) stack[ln-2] = btoi(stack[ln-2] != stack[ln-1]) stack = stack[:ln-1] case and: ln := len(stack) stack[ln-2] = btoi(itob(stack[ln-2]) && itob(stack[ln-1])) stack = stack[:ln-1] case or: ln := len(stack) stack[ln-2] = btoi(itob(stack[ln-2]) || itob(stack[ln-1])) stack = stack[:ln-1] case neg: ln := len(stack) stack[ln-1] = -stack[ln-1] case not: ln := len(stack) stack[ln-1] = btoi(!itob(stack[ln-1])) case jmp: x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) pc += x case jz: ln := len(stack) v := stack[ln-1] stack = stack[:ln-1] if v != 0 { pc += 4 } else { x := int32(binary.LittleEndian.Uint32(object[pc : pc+4])) pc += x } case prtc: ln := len(stack) fmt.Printf("%c", stack[ln-1]) stack = stack[:ln-1] case prts: ln := len(stack) fmt.Printf("%s", stringPool[stack[ln-1]]) stack = stack[:ln-1] case prti: ln := len(stack) fmt.Printf("%d", stack[ln-1]) stack = stack[:ln-1] case halt: return default: reportError(fmt.Sprintf("Unknown opcode %d\n", op)) } } } func translate(s string) string { var d strings.Builder for i := 0; i < len(s); i++ { if s[i] == '\\' && (i+1) < len(s) { if s[i+1] == 'n' { d.WriteByte('\n') i++ } else if s[i+1] == '\\' { d.WriteByte('\\') i++ } } else { d.WriteByte(s[i]) } } return d.String() } func loadCode() int { var dataSize int firstLine := true for scanner.Scan() { line := strings.TrimRight(scanner.Text(), " \t") if len(line) == 0 { if firstLine { reportError("empty line") } else { break } } lineList := strings.Fields(line) if firstLine { dataSize, err = strconv.Atoi(lineList[1]) check(err) nStrings, err := strconv.Atoi(lineList[3]) check(err) for i := 0; i < nStrings; i++ { scanner.Scan() s := strings.Trim(scanner.Text(), "\"\n") stringPool = append(stringPool, translate(s)) } firstLine = false continue } offset, err := strconv.Atoi(lineList[0]) check(err) instr := lineList[1] opCode, ok := codeMap[instr] if !ok { reportError(fmt.Sprintf("Unknown instruction %s at %d", instr, opCode)) } emitByte(opCode) switch opCode { case jmp, jz: p, err := strconv.Atoi(lineList[3]) check(err) emitWord(p - offset - 1) case push: value, err := strconv.Atoi(lineList[2]) check(err) emitWord(value) case fetch, store: value, err := strconv.Atoi(strings.Trim(lineList[2], "[]")) check(err) emitWord(value) } } check(scanner.Err()) return dataSize } func main() { codeGen, err := os.Open("codegen.txt") check(err) defer codeGen.Close() scanner = bufio.NewScanner(codeGen) runVM(loadCode()) }