title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
Superellipse
JavaScript
A superellipse is a geometric figure defined as the set of all points (x, y) with ::: \left|\frac{x}{a}\right|^n\! + \left|\frac{y}{b}\right|^n\! = 1, where ''n'', ''a'', and ''b'' are positive numbers. ;Task Draw a superellipse with n = 2.5, and a = b = 200
var n = 2.5, a = 200, b = 200, ctx; function point( x, y ) { ctx.fillRect( x, y, 1, 1); } function start() { var can = document.createElement('canvas'); can.width = can.height = 600; ctx = can.getContext( "2d" ); ctx.rect( 0, 0, can.width, can.height ); ctx.fillStyle = "#000000"; ctx.fill(); document.body.appendChild( can ); ctx.fillStyle = "#ffffff"; for( var t = 0; t < 1000; t += .1 ) { x = Math.pow( Math.abs( Math.cos( t ) ), 2 / n ) * a * Math.sign( Math.cos( t ) ); y = Math.pow( Math.abs( Math.sin( t ) ), 2 / n ) * b * Math.sign( Math.sin( t ) ); point( x + ( can.width >> 1 ), y + ( can.height >> 1 ) ); } }
Teacup rim text
JavaScript
On a set of coasters we have, there's a picture of a teacup. On the rim of the teacup the word '''TEA''' appears a number of times separated by bullet characters (*). It occurred to me that if the bullet were removed and the words run together, you could start at any letter and still end up with a meaningful three-letter word. So start at the '''T''' and read '''TEA'''. Start at the '''E''' and read '''EAT''', or start at the '''A''' and read '''ATE'''. That got me thinking that maybe there are other words that could be used rather that '''TEA'''. And that's just English. What about Italian or Greek or ... um ... Telugu. For English, we will use the unixdict (now) located at: unixdict.txt. (This will maintain continuity with other Rosetta Code tasks that also use it.) ;Task: Search for a set of words that could be printed around the edge of a teacup. The words in each set are to be of the same length, that length being greater than two (thus precluding '''AH''' and '''HA''', for example.) Having listed a set, for example ['''ate tea eat'''], refrain from displaying permutations of that set, e.g.: ['''eat tea ate'''] etc. The words should also be made of more than one letter (thus precluding '''III''' and '''OOO''' etc.) The relationship between these words is (using ATE as an example) that the first letter of the first becomes the last letter of the second. The first letter of the second becomes the last letter of the third. So '''ATE''' becomes '''TEA''' and '''TEA''' becomes '''EAT'''. All of the possible permutations, using this particular permutation technique, must be words in the list. The set you generate for '''ATE''' will never included the word '''ETA''' as that cannot be reached via the first-to-last movement method. Display one line for each set of teacup rim words.
===Set() objects=== Reading a local dictionary with the macOS JS for Automation library:
Temperature conversion
JavaScript
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. : 0 degrees Celsius corresponds to 273.15 kelvin. : 0 kelvin is absolute zero. The Fahrenheit and Rankine scales also have the same magnitude, but different null points. : 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine. : 0 degrees Rankine is absolute zero. The Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9. ;Task Write code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. ;Example: K 21.00 C -252.15 F -421.87 R 37.80
var k2c = k => k - 273.15 var k2r = k => k * 1.8 var k2f = k => k2r(k) - 459.67 Number.prototype.toMaxDecimal = function (d) { return +this.toFixed(d) + '' } function kCnv(k) { document.write( k,'K° = ', k2c(k).toMaxDecimal(2),'C° = ', k2r(k).toMaxDecimal(2),'R° = ', k2f(k).toMaxDecimal(2),'F°<br>' ) } kCnv(21) kCnv(295)
The Name Game
JavaScript
Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song "The Name Game". The regular verse Unless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules. The verse for the name 'Gary' would be like this: Gary, Gary, bo-bary Banana-fana fo-fary Fee-fi-mo-mary Gary! At the end of every line, the name gets repeated without the first letter: Gary becomes ary If we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this: (X), (X), bo-b(Y) Banana-fana fo-f(Y) Fee-fi-mo-m(Y) (X)! Vowel as first letter of the name If you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name. The verse looks like this: Earl, Earl, bo-bearl Banana-fana fo-fearl Fee-fi-mo-mearl Earl! 'B', 'F' or 'M' as first letter of the name In case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule. The line which would 'rebuild' the name (e.g. bo-billy) is sung without the first letter of the name. The verse for the name Billy looks like this: Billy, Billy, bo-illy Banana-fana fo-filly Fee-fi-mo-milly Billy! For the name 'Felix', this would be right: Felix, Felix, bo-belix Banana-fana fo-elix Fee-fi-mo-melix Felix!
function singNameGame(name) { // normalize name name = name.toLowerCase(); name = name[0].toUpperCase() + name.slice(1); // ... and sometimes y // let's pray this works let firstVowelPos = (function() { let vowels = 'aeiouàáâãäåæèéêëìíîïòóôõöøùúûüāăąēĕėęěĩīĭįıijōŏőœũūŭůűų' .split(''); function isVowel(char) { return vowels.indexOf(char) >= 0; } if (isVowel(name[0].toLowerCase())) return 0; if (name[0] == 'Y' && !isVowel(name[1])) return 0; if (name[0] == 'Y' && isVowel(name[1])) return 1; vowels = vowels.concat(vowels, 'yÿý'.split('')); for (let i = 1; i < name.length; i++) if (isVowel(name[i])) return i; })(); let init = name[0].toLowerCase(), trunk = name.slice(firstVowelPos).toLowerCase(), b = trunk, f = trunk, m = trunk; switch (init) { case 'b': f = 'f' + trunk; m = 'm' + trunk; break; case 'f': b = 'b' + trunk; m = 'm' + trunk; break; case 'm': b = 'b' + trunk; f = 'f' + trunk; break; default: b = 'b' + trunk; f = 'f' + trunk; m = 'm' + trunk; } return ` <p>${name}, ${name}, bo-${b}<br> Banana-fana fo-${f}<br> Fee-fi-fo-mo-${m}<br> ${name}!<br></p> ` } // testing let names = 'Gary Earl Billy Felix Mary Christine Brian Yvonne Yannick'.split(' '); for (let i = 0; i < names.length; i++) document.write(singNameGame(names[i]));
The Twelve Days of Christmas
JavaScript
Write a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)
JSON.stringify( (function ( strPrepn, strHoliday, strUnit, strRole, strProcess, strRecipient ) { var lstOrdinal = 'first second third fourth fifth sixth\ seventh eighth ninth tenth eleventh twelfth' .split(/\s+/), lngUnits = lstOrdinal.length, lstGoods = 'A partridge in a pear tree.\ Two turtle doves\ Three french hens\ Four calling birds\ Five golden rings\ Six geese a-laying\ Seven swans a-swimming\ Eight maids a-milking\ Nine ladies dancing\ Ten lords a-leaping\ Eleven pipers piping\ Twelve drummers drumming' .split(/\s{2,}/), lstReversed = (function () { var lst = lstGoods.slice(0); return (lst.reverse(), lst); })(), strProvenance = [strRole, strProcess, strRecipient + ':'].join(' '), strPenultimate = lstReversed[lngUnits - 2] + ' and', strFinal = lstGoods[0]; return lstOrdinal.reduce( function (sofar, day, i) { return sofar.concat( [ [ [ // abstraction of line 1 strPrepn, 'the', lstOrdinal[i], strUnit, 'of', strHoliday ].join(' '), strProvenance ].concat( // reversed descent through memory (i > 1 ? [lstGoods[i]] : []).concat( lstReversed.slice( lngUnits - i, lngUnits - 2 ) ).concat( // penultimate line ends with 'and' [ strPenultimate, strFinal ].slice(i ? 0 : 1) ) ) ] ); }, [] ); })( 'On', 'Christmas', 'day', 'my true love', 'gave to', 'me' ), null, 2 );
Thue-Morse
JavaScript from Java
Create a Thue-Morse sequence. ;See also * YouTube entry: The Fairest Sharing Sequence Ever * YouTube entry: Math and OCD - My story with the Thue-Morse sequence * Task: [[Fairshare between two and more]]
(() => { 'use strict'; // thueMorsePrefixes :: () -> [[Int]] const thueMorsePrefixes = () => iterate( ap(append)( map(x => 1 - x) ) )([0]); // ----------------------- TEST ----------------------- const main = () => // Fifth iteration. // 2 ^ 5 = 32 terms of the Thue-Morse sequence. showList( index(thueMorsePrefixes())( 5 ) ); // ---------------- GENERIC FUNCTIONS ----------------- // ap :: (a -> b -> c) -> (a -> b) -> a -> c const ap = f => // Applicative instance for functions. // f(x) applied to g(x). g => x => f(x)( g(x) ); // append (++) :: [a] -> [a] -> [a] // append (++) :: String -> String -> String const append = xs => // A list or string composed by // the concatenation of two others. ys => xs.concat(ys); // index (!!) :: Generator (Int, a) -> Int -> Maybe a const index = xs => i => (take(i)(xs), xs.next().value); // iterate :: (a -> a) -> a -> Gen [a] const iterate = f => function*(x) { let v = x; while (true) { yield(v); v = f(v); } }; // map :: (a -> b) -> [a] -> [b] const map = f => // The list obtained by applying f // to each element of xs. // (The image of xs under f). xs => xs.map(f); // showList :: [a] -> String const showList = xs => '[' + xs.map(x => x.toString()) .join(',') .replace(/[\"]/g, '') + ']'; // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = n => // The first n elements of a list, // string of characters, or stream. xs => 'GeneratorFunction' !== xs .constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat.apply([], Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; })); // MAIN --- return main(); })();
Top rank per group
JavaScript
Find the top ''N'' salaries in each department, where ''N'' is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett,E10297,32000,D101 John Rappl,E21437,47000,D050 George Woltman,E00127,53500,D101 Adam Smith,E63535,18000,D202 Claire Buckman,E39876,27800,D202 David McClellan,E04242,41500,D101 Rich Holcomb,E01234,49500,D202 Nathan Adams,E41298,21900,D050 Richard Potter,E43128,15900,D101 David Motsinger,E27002,19250,D202 Tim Sampair,E03033,27000,D101 Kim Arlich,E10001,57000,D190 Timothy Grove,E16398,29900,D190
var data = [ {name: "Tyler Bennett", id: "E10297", salary: 32000, dept: "D101"}, {name: "John Rappl", id: "E21437", salary: 47000, dept: "D050"}, {name: "George Woltman", id: "E00127", salary: 53500, dept: "D101"}, {name: "Adam Smith", id: "E63535", salary: 18000, dept: "D202"}, {name: "Claire Buckman", id: "E39876", salary: 27800, dept: "D202"}, {name: "David McClellan", id: "E04242", salary: 41500, dept: "D101"}, {name: "Rich Holcomb", id: "E01234", salary: 49500, dept: "D202"}, {name: "Nathan Adams", id: "E41298", salary: 21900, dept: "D050"}, {name: "Richard Potter", id: "E43128", salary: 15900, dept: "D101"}, {name: "David Motsinger", id: "E27002", salary: 19250, dept: "D202"}, {name: "Tim Sampair", id: "E03033", salary: 27000, dept: "D101"}, {name: "Kim Arlich", id: "E10001", salary: 57000, dept: "D190"}, {name: "Timothy Grove", id: "E16398", salary: 29900, dept: "D190"}, ]; function top_rank(n) { var by_dept = group_by_dept(data); for (var dept in by_dept) { output(dept); for (var i = 0; i < n && i < by_dept[dept].length; i++) { var emp = by_dept[dept][i]; output(emp.name + ", id=" + emp.id + ", salary=" + emp.salary); } output(""); } } // group by dept, and sort by salary function group_by_dept(data) { var by_dept = {}; for (var idx in data) { var dept = data[idx].dept; if ( ! has_property(by_dept, dept)) { by_dept[dept] = new Array(); } by_dept[dept].push(data[idx]); } for (var dept in by_dept) { // numeric sort by_dept[dept].sort(function (a,b){return b.salary - a.salary}); } return by_dept; } function has_property(obj, propname) { return typeof(obj[propname]) != "undefined"; } function output(str) { try { WScript.Echo(str); // WSH } catch(err) { print(str); // Rhino } } top_rank(3);
Trabb Pardo–Knuth algorithm
JavaScript
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm. From the wikipedia entry: '''ask''' for 11 numbers to be read into a sequence ''S'' '''reverse''' sequence ''S'' '''for each''' ''item'' '''in''' sequence ''S'' ''result'' ''':=''' '''call''' a function to do an ''operation'' '''if''' ''result'' overflows '''alert''' user '''else''' '''print''' ''result'' The task is to implement the algorithm: # Use the function: f(x) = |x|^{0.5} + 5x^3 # The overflow condition is an answer of greater than 400. # The 'user alert' should not stop processing of other items of the sequence. # Print a prompt before accepting '''eleven''', textual, numeric inputs. # You may optionally print the item as well as its associated result, but the results must be in reverse order of input. # The sequence ''' ''S'' ''' may be 'implied' and so not shown explicitly. # ''Print and show the program in action from a typical run here''. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
#!/usr/bin/env js function main() { var nums = getNumbers(11); nums.reverse(); for (var i in nums) { pardoKnuth(nums[i], fn, 400); } } function pardoKnuth(n, f, max) { var res = f(n); putstr('f(' + String(n) + ')'); if (res > max) { print(' is too large'); } else { print(' = ' + String(res)); } } function fn(x) { return Math.pow(Math.abs(x), 0.5) + 5 * Math.pow(x, 3); } function getNumbers(n) { var nums = []; print('Enter', n, 'numbers.'); for (var i = 1; i <= n; i++) { putstr(' ' + i + ': '); var num = readline(); nums.push(Number(num)); } return nums; } main();
Truth table
JavaScript
A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function. ;Task: # Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. (One can assume that the user input is correct). # Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function. # Either reverse-polish or infix notation expressions are allowed. ;Related tasks: * [[Boolean values]] * [[Ternary logic]] ;See also: * Wolfram MathWorld entry on truth tables. * some "truth table" examples from Google.
<!DOCTYPE html><html><head><title>Truth table</title><script> var elem,expr,vars; function isboolop(chr){return "&|!^".indexOf(chr)!=-1;} function varsindexof(chr){ var i; for(i=0;i<vars.length;i++){if(vars[i][0]==chr)return i;} return -1; } function printtruthtable(){ var i,str; elem=document.createElement("pre"); expr=prompt("Boolean expression:\nAccepts single-character variables (except for \"T\" and \"F\", which specify explicit true or false values), postfix, with \"&|!^\" for and, or, not, xor, respectively; optionally seperated by whitespace.").replace(/\s/g,""); vars=[]; for(i=0;i<expr.length;i++)if(!isboolop(expr[i])&&expr[i]!="T"&&expr[i]!="F"&&varsindexof(expr[i])==-1)vars.push([expr[i],-1]); if(vars.length==0)return; str=""; for(i=0;i<vars.length;i++)str+=vars[i][0]+" "; elem.innerHTML="<b>"+str+expr+"</b>\n"; vars[0][1]=false; truthpartfor(1); vars[0][1]=true; truthpartfor(1); vars[0][1]=-1; document.body.appendChild(elem); } function truthpartfor(index){ if(index==vars.length){ var str,i; str=""; for(i=0;i<index;i++)str+=(vars[i][1]?"<b>T</b>":"F")+" "; elem.innerHTML+=str+(parsebool()?"<b>T</b>":"F")+"\n"; return; } vars[index][1]=false; truthpartfor(index+1); vars[index][1]=true; truthpartfor(index+1); vars[index][1]=-1; } function parsebool(){ var stack,i,idx; console.log(vars); stack=[]; for(i=0;i<expr.length;i++){ if(expr[i]=="T")stack.push(true); else if(expr[i]=="F")stack.push(false); else if((idx=varsindexof(expr[i]))!=-1)stack.push(vars[idx][1]); else if(isboolop(expr[i])){ switch(expr[i]){ case "&":stack.push(stack.pop()&stack.pop());break; case "|":stack.push(stack.pop()|stack.pop());break; case "!":stack.push(!stack.pop());break; case "^":stack.push(stack.pop()^stack.pop());break; } } else alert("Non-conformant character "+expr[i]+" in expression. Should not be possible."); console.log(stack); } return stack[0]; } </script></head><body onload="printtruthtable()"></body></html>
Two bullet roulette
JavaScript
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. If a bullet is seen, the cylinder is rotated one chamber clockwise and the next chamber checked until an empty chamber is found. 2. A cartridge containing a bullet is placed in the empty chamber. 3. The cylinder is then rotated one chamber clockwise. To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take a random position from 1 to 6 chamber rotations clockwise from its starting position. When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just counterclockwise from the loading position. The gun is unloaded by removing all cartridges from the cylinder. According to the legend, a suicidal Russian imperial military officer plays a game of Russian roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice. If the gun fires with a trigger pull, this is considered a successful suicide. The cylinder is always spun before the first shot, but it may or may not be spun after putting in the first bullet and may or may not be spun after taking the first shot. Which of the following situations produces the highest probability of suicide? A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot. B. Spinning the cylinder after loading the first bullet only. C. Spinning the cylinder after firing the first shot only. D. Not spinning the cylinder either after loading the first bullet or after the first shot. E. The probability is the same for all cases. ;Task: # Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios. # Show the results as a percentage of deaths for each type of scenario. # The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. ;Reference: Youtube video on the Russian 1895 Nagant revolver [[https://www.youtube.com/watch?v=Dh1mojMaEtM]]
let Pistol = function(method) { this.fired = false; this.cylinder = new Array(6).fill(false); this.trigger = 0; this.rshift = function() { this.trigger = this.trigger == 0 ? 5 : this.trigger-1; } this.load = function() { while (this.cylinder[this.trigger]) this.rshift(); this.cylinder[this.trigger] = true; this.rshift(); } // actually we don't need this here: just for completeness this.unload = function() { this.cylinder.fill(false); } this.spin = function() { this.trigger = Math.floor(Math.random() * 6); } this.fire = function() { if (this.cylinder[this.trigger]) this.fired = true; this.rshift(); } this.exec = function() { if (!method) console.error('No method provided'); else { method = method.toUpperCase(); for (let x = 0; x < method.length; x++) switch (method[x]) { case 'F' : this.fire(); break; case 'L' : this.load(); break; case 'S' : this.spin(); break; case 'U' : this.unload(); break; default: console.error(`Unknown character in method: ${method[x]}`); } return this.fired; } } } // simulating const ITERATIONS = 25e4; let methods = 'lslsfsf lslsff llsfsf llsff'.split(' '), bodyCount; console.log(`@ ${ITERATIONS.toLocaleString('en')} iterations:`); console.log(); for (let x = 0; x < methods.length; x++) { bodyCount = 0; for (let y = 1; y <= ITERATIONS; y++) if (new Pistol(methods[x]).exec()) bodyCount++; console.log(`${methods[x]}:`); console.log(`deaths: ${bodyCount.toLocaleString('en')} (${(bodyCount / ITERATIONS * 100).toPrecision(3)} %) `); console.log(); }
URL encoding
JavaScript
Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. For the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default: * ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). * ASCII symbols (Character ranges 32-47 decimal (20-2F hex)) * ASCII symbols (Character ranges 58-64 decimal (3A-40 hex)) * ASCII symbols (Character ranges 91-96 decimal (5B-60 hex)) * ASCII symbols (Character ranges 123-126 decimal (7B-7E hex)) * Extended characters with character codes of 128 decimal (80 hex) and above. ;Example: The string "http://foo bar/" would be encoded as "http%3A%2F%2Ffoo%20bar%2F". ;Variations: * Lowercase escapes are legal, as in "http%3a%2f%2ffoo%20bar%2f". * Special characters have different encodings for different standards: ** RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says to preserve "-._~". ** HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve "-._*", and to encode space " " to "+". ** encodeURI function in Javascript will preserve "-._~" (RFC 3986) and ";,/?:@&=+$!*'()#". ;Options: It is permissible to use an exception string (containing a set of symbols that do not need to be converted). However, this is an optional feature and is not a requirement of this task. ;Related tasks: * [[URL decoding]] * [[URL parser]]
var normal = 'http://foo/bar/'; var encoded = encodeURIComponent(normal);
URL parser
JavaScript
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id ;Task: Parse a well-formed URL to retrieve the relevant information: '''scheme''', '''domain''', '''path''', ... Note: this task has nothing to do with [[URL encoding]] or [[URL decoding]]. According to the standards, the characters: :::: ! * ' ( ) ; : @ & = + $ , / ? % # [ ] only need to be percent-encoded ('''%''') in case of possible confusion. Also note that the '''path''', '''query''' and '''fragment''' are case sensitive, even if the '''scheme''' and '''domain''' are not. The way the returned information is provided (set of variables, array, structured, record, object,...) is language-dependent and left to the programmer, but the code should be clear enough to reuse. Extra credit is given for clear error diagnostics. * Here is the official standard: https://tools.ietf.org/html/rfc3986, * and here is a simpler BNF: http://www.w3.org/Addressing/URL/5_URI_BNF.html. ;Test cases: According to T. Berners-Lee '''foo://example.com:8042/over/there?name=ferret#nose''' should parse into: ::* scheme = foo ::* domain = example.com ::* port = :8042 ::* path = over/there ::* query = name=ferret ::* fragment = nose '''urn:example:animal:ferret:nose''' should parse into: ::* scheme = urn ::* path = example:animal:ferret:nose '''other URLs that must be parsed include:''' :* jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true :* ftp://ftp.is.co.za/rfc/rfc1808.txt :* http://www.ietf.org/rfc/rfc2396.txt#header1 :* ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two :* mailto:[email protected] :* news:comp.infosystems.www.servers.unix :* tel:+1-816-555-1212 :* telnet://192.0.2.16:80/ :* urn:oasis:names:specification:docbook:dtd:xml:4.1.2
[ { "hash": "#nose", "host": "example.com:8042", "hostname": "example.com", "origin": "foo://example.com:8042", "pathname": "/over/there", "port": "8042", "protocol": "foo:", "search": "?name=ferret" }, { "hash": "", "host": "", "hostname": "", "origin": "urn://", "pathname": "example:animal:ferret:nose", "port": "", "protocol": "urn:", "search": "" }, { "hash": "", "host": "", "hostname": "", "origin": "jdbc://", "pathname": "mysql://test_user:ouupppssss@localhost:3306/sakila", "port": "", "protocol": "jdbc:", "search": "?profileSQL=true" }, { "hash": "", "host": "ftp.is.co.za", "hostname": "ftp.is.co.za", "origin": "ftp://ftp.is.co.za", "pathname": "/rfc/rfc1808.txt", "port": "", "protocol": "ftp:", "search": "" }, { "hash": "#header1", "host": "www.ietf.org", "hostname": "www.ietf.org", "origin": "http://www.ietf.org", "pathname": "/rfc/rfc2396.txt", "port": "", "protocol": "http:", "search": "" }, { "hash": "", "host": "[2001:db8::7]", "hostname": "[2001:db8::7]", "origin": "ldap://[2001:db8::7]", "pathname": "/c=GB", "port": "", "protocol": "ldap:", "search": "?objectClass=one&objectClass=two" }, { "hash": "", "host": "", "hostname": "", "origin": "mailto://", "pathname": "[email protected]", "port": "", "protocol": "mailto:", "search": "" }, { "hash": "", "host": "", "hostname": "", "origin": "news://", "pathname": "comp.infosystems.www.servers.unix", "port": "", "protocol": "news:", "search": "" }, { "hash": "", "host": "", "hostname": "", "origin": "tel://", "pathname": "+1-816-555-1212", "port": "", "protocol": "tel:", "search": "" }, { "hash": "", "host": "192.0.2.16:80", "hostname": "192.0.2.16", "origin": "telnet://192.0.2.16:80", "pathname": "/", "port": "80", "protocol": "telnet:", "search": "" }, { "hash": "", "host": "", "hostname": "", "origin": "urn://", "pathname": "oasis:names:specification:docbook:dtd:xml:4.1.2", "port": "", "protocol": "urn:", "search": "" }, { "hash": "", "host": "example.com", "hostname": "example.com", "origin": "ssh://example.com", "pathname": "", "port": "", "protocol": "ssh:", "search": "" }, { "hash": "", "host": "example.com", "hostname": "example.com", "origin": "https://example.com", "pathname": "/place", "port": "", "protocol": "https:", "search": "" }, { "hash": "", "host": "example.com", "hostname": "example.com", "origin": "http://example.com", "pathname": "/", "port": "", "protocol": "http:", "search": "?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64" } ]
UTF-8 encode and decode
JavaScript
As described in Wikipedia, UTF-8 is a popular encoding of (multi-byte) [[Unicode]] code-points into eight-bit octets. The goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. Then you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character. Demonstrate the functionality of your encoder and decoder on the following five characters: Character Name Unicode UTF-8 encoding (hex) --------------------------------------------------------------------------------- A LATIN CAPITAL LETTER A U+0041 41 o LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6 Zh CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96 EUR EURO SIGN U+20AC E2 82 AC MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E Provided below is a reference implementation in Common Lisp.
/***************************************************************************\ |* Pure UTF-8 handling without detailed error reporting functionality. *| |***************************************************************************| |* utf8encode *| |* < String character or UInt32 code point *| |* > Uint8Array encoded_character *| |* | ErrorString *| |* *| |* utf8encode takes a string or uint32 representing a single code point *| |* as its argument and returns an array of length 1 up to 4 containing *| |* utf8 code units representing that character. *| |***************************************************************************| |* utf8decode *| |* < Unit8Array [highendbyte highmidendbyte lowmidendbyte lowendbyte] *| |* > uint32 character *| |* | ErrorString *| |* *| |* utf8decode takes an array of one to four uint8 representing utf8 code *| |* units and returns a uint32 representing that code point. *| \***************************************************************************/ const utf8encode= n=> (m=> m<0x80 ?Uint8Array.from( [ m>>0&0x7f|0x00]) :m<0x800 ?Uint8Array.from( [ m>>6&0x1f|0xc0,m>>0&0x3f|0x80]) :m<0x10000 ?Uint8Array.from( [ m>>12&0x0f|0xe0,m>>6&0x3f|0x80,m>>0&0x3f|0x80]) :m<0x110000 ?Uint8Array.from( [ m>>18&0x07|0xf0,m>>12&0x3f|0x80,m>>6&0x3f|0x80,m>>0&0x3f|0x80]) :(()=>{throw'Invalid Unicode Code Point!'})()) ( typeof n==='string' ?n.codePointAt(0) :n&0x1fffff), utf8decode= ([m,n,o,p])=> m<0x80 ?( m&0x7f)<<0 :0xc1<m&&m<0xe0&&n===(n&0xbf) ?( m&0x1f)<<6|( n&0x3f)<<0 :( m===0xe0&&0x9f<n&&n<0xc0 ||0xe0<m&&m<0xed&&0x7f<n&&n<0xc0 ||m===0xed&&0x7f<n&&n<0xa0 ||0xed<m&&m<0xf0&&0x7f<n&&n<0xc0) &&o===o&0xbf ?( m&0x0f)<<12|( n&0x3f)<<6|( o&0x3f)<<0 :( m===0xf0&&0x8f<n&&n<0xc0 ||m===0xf4&&0x7f<n&&n<0x90 ||0xf0<m&&m<0xf4&&0x7f<n&&n<0xc0) &&o===o&0xbf&&p===p&0xbf ?( m&0x07)<<18|( n&0x3f)<<12|( o&0x3f)<<6|( p&0x3f)<<0 :(()=>{throw'Invalid UTF-8 encoding!'})()
Van Eck sequence
JavaScript from Python
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. ;Example: Using A: :0 Using B: :0 0 Using C: :0 0 1 Using B: :0 0 1 0 Using C: (zero last occurred two steps back - before the one) :0 0 1 0 2 Using B: :0 0 1 0 2 0 Using C: (two last occurred two steps back - before the zero) :0 0 1 0 2 0 2 2 Using C: (two last occurred one step back) :0 0 1 0 2 0 2 2 1 Using C: (one last appeared six steps back) :0 0 1 0 2 0 2 2 1 6 ... ;Task: # Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers. # Use it to display here, on this page: :# The first ten terms of the sequence. :# Terms 991 - to - 1000 of the sequence. ;References: * Don't Know (the Van Eck Sequence) - Numberphile video. * Wikipedia Article: Van Eck's Sequence. * OEIS sequence: A181391.
(() => { "use strict"; // vanEck :: Int -> [Int] const vanEck = n => // First n terms of the vanEck series. [0].concat(mapAccumL( ([x, seen]) => i => { const prev = seen[x], v = Boolean(prev) ? ( i - prev ) : 0; return [ [v, (seen[x] = i, seen)], v ]; })( [0, {}] )( enumFromTo(1)(n - 1) )[1]); // ----------------------- TEST ------------------------ const main = () => fTable( "Terms of the VanEck series:\n" )( n => `${str(n - 10)}-${str(n)}` )( xs => JSON.stringify(xs.slice(-10)) )( vanEck )([10, 1000, 10000]); // ----------------- GENERIC FUNCTIONS ----------------- // enumFromTo :: Int -> Int -> [Int] const enumFromTo = m => n => Array.from({ length: 1 + n - m }, (_, i) => m + i); // fTable :: String -> (a -> String) -> // (b -> String) -> (a -> b) -> [a] -> String const fTable = s => // Heading -> x display function -> // fx display function -> // f -> values -> tabular string xShow => fxShow => f => xs => { const ys = xs.map(xShow), w = Math.max(...ys.map(y => [...y].length)), table = zipWith( a => b => `${a.padStart(w, " ")} -> ${b}` )(ys)( xs.map(x => fxShow(f(x))) ).join("\n"); return `${s}\n${table}`; }; // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> // [x] -> (acc, [y]) const mapAccumL = f => // A tuple of an accumulation and a list // obtained by a combined map and fold, // with accumulation from left to right. acc => xs => [...xs].reduce( ([a, bs], x) => second( v => bs.concat(v) )( f(a)(x) ), [acc, []] ); // second :: (a -> b) -> ((c, a) -> (c, b)) const second = f => // A function over a simple value lifted // to a function over a tuple. // f (a, b) -> (a, f(b)) ([x, y]) => [x, f(y)]; // str :: a -> String const str = x => x.toString(); // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = f => // A list constructed by zipping with a // custom function, rather than with the // default tuple constructor. xs => ys => xs.map( (x, i) => f(x)(ys[i]) ).slice( 0, Math.min(xs.length, ys.length) ); // MAIN --- return main(); })();
Variable declaration reset
JavaScript
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based. The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration. There is no particular judgement of right or wrong here, just a plain-speaking statement of subtle differences. Should your first attempt bomb with "unassigned variable" exceptions, feel free to code it as (say) // int prev // crashes with unassigned variable int prev = -1 // predictably no output If your programming language does not support block scope (eg assembly) it should be omitted from this task.
<!DOCTYPE html> <html lang="en" > <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>variable declaration reset</title> </head> <body> <script> "use strict"; let s = [1, 2, 2, 3, 4, 4, 5]; for (let i=0; i<7; i+=1) { let curr = s[i], prev; if (i>0 && (curr===prev)) { console.log(i); } prev = curr; } </script> </body> </html>
Vector products
JavaScript
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z). If you imagine a graph with the '''x''' and '''y''' axis being at right angles to each other and having a third, '''z''' axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point. Given the vectors: A = (a1, a2, a3) B = (b1, b2, b3) C = (c1, c2, c3) then the following common vector products are defined: * '''The dot product''' (a scalar quantity) :::: A * B = a1b1 + a2b2 + a3b3 * '''The cross product''' (a vector quantity) :::: A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1) * '''The scalar triple product''' (a scalar quantity) :::: A * (B x C) * '''The vector triple product''' (a vector quantity) :::: A x (B x C) ;Task: Given the three vectors: a = ( 3, 4, 5) b = ( 4, 3, 5) c = (-5, -12, -13) # Create a named function/subroutine/method to compute the dot product of two vectors. # Create a function to compute the cross product of two vectors. # Optionally create a function to compute the scalar triple product of three vectors. # Optionally create a function to compute the vector triple product of three vectors. # Compute and display: a * b # Compute and display: a x b # Compute and display: a * (b x c), the scalar triple product. # Compute and display: a x (b x c), the vector triple product. ;References: * A starting page on Wolfram MathWorld is {{Wolfram|Vector|Multiplication}}. * Wikipedia dot product. * Wikipedia cross product. * Wikipedia triple product. ;Related tasks: * [[Dot product]] * [[Quaternion type]]
function dotProduct() { var len = arguments[0] && arguments[0].length; var argsLen = arguments.length; var i, j = len; var prod, sum = 0; // If no arguments supplied, return undefined if (!len) { return; } // If all vectors not same length, return undefined i = argsLen; while (i--) { if (arguments[i].length != len) { return; // return undefined } } // Sum terms while (j--) { i = argsLen; prod = 1; while (i--) { prod *= arguments[i][j]; } sum += prod; } return sum; } function crossProduct(a, b) { // Check lengths if (a.length != 3 || b.length != 3) { return; } return [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]]; } function scalarTripleProduct(a, b, c) { return dotProduct(a, crossProduct(b, c)); } function vectorTripleProduct(a, b, c) { return crossProduct(a, crossProduct(b, c)); } // Run tests (function () { var a = [3, 4, 5]; var b = [4, 3, 5]; var c = [-5, -12, -13]; alert( 'A . B: ' + dotProduct(a, b) + '\n' + 'A x B: ' + crossProduct(a, b) + '\n' + 'A . (B x C): ' + scalarTripleProduct(a, b, c) + '\n' + 'A x (B x C): ' + vectorTripleProduct(a, b, c) ); }());
Visualize a tree
JavaScript
A tree structure (i.e. a rooted, connected acyclic graph) is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as: :::* indented text (a la unix tree command) :::* nested HTML tables :::* hierarchical GUI widgets :::* 2D or 3D images :::* etc. ;Task: Write a program to produce a visual representation of some tree. The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. Make do with the vague term "friendly" the best you can.
<!doctype html> <html id="doc"> <head><meta charset="utf-8"/> <title>Stuff</title> <script type="application/javascript"> function gid(id) { return document.getElementById(id); } function ce(tag, cls, parent_node) { var e = document.createElement(tag); e.className = cls; if (parent_node) parent_node.appendChild(e); return e; } function dom_tree(id) { gid('tree').textContent = ""; gid('tree').appendChild(mktree(gid(id), null)); } function mktree(e, p) { var t = ce("div", "tree", p); var tog = ce("span", "toggle", t); var h = ce("span", "tag", t); if (e.tagName === undefined) { h.textContent = "#Text"; var txt = e.textContent; if (txt.length > 0 && txt.match(/\S/)) { h = ce("div", "txt", t); h.textContent = txt; } return t; } tog.textContent = "−"; tog.onclick = function () { clicked(tog); } h.textContent = e.nodeName; var l = e.childNodes; for (var i = 0; i != l.length; i++) mktree(l[i], t); return t; } function clicked(e) { var is_on = e.textContent == "−"; e.textContent = is_on ? "+" : "−"; e.parentNode.className = is_on ? "tree-hide" : "tree"; } </script> <style> #tree { white-space: pre; font-family: monospace; border: 1px solid } .tree > .tree-hide, .tree > .tree { margin-left: 2em; border-left: 1px dotted rgba(0,0,0,.2)} .tree-hide > .tree, .tree-hide > .tree-hide { display: none } .tag { color: navy } .tree-hide > .tag { color: maroon } .txt { color: gray; padding: 0 .5em; margin: 0 .5em 0 2em; border: 1px dotted rgba(0,0,0,.1) } .toggle { display: inline-block; width: 2em; text-align: center } </style> </head> <body> <article> <section> <h1>Headline</h1> Blah blah </section> <section> <h1>More headline</h1> <blockquote>Something something</blockquote> <section><h2>Nested section</h2> Somethin somethin list: <ul> <li>Apples</li> <li>Oranges</li> <li>Cetera Fruits</li> </ul> </section> </section> </article> <div id="tree"><a href="javascript:dom_tree('doc')">click me</a></div> </body> </html>
Visualize a tree
JavaScript from Python
A tree structure (i.e. a rooted, connected acyclic graph) is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as: :::* indented text (a la unix tree command) :::* nested HTML tables :::* hierarchical GUI widgets :::* 2D or 3D images :::* etc. ;Task: Write a program to produce a visual representation of some tree. The content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. Make do with the vague term "friendly" the best you can.
(() => { 'use strict'; // UTF8 character-drawn tree, with options for compacting vs // centering parents, and for pruning out nodeless lines. const example = ` ┌ Epsilon ┌─ Beta ┼─── Zeta │ └──── Eta Alpha ┼ Gamma ─── Theta │ ┌─── Iota └ Delta ┼── Kappa └─ Lambda` // drawTree2 :: Bool -> Bool -> Tree String -> String const drawTree2 = blnCompact => blnPruned => tree => { // Tree design and algorithm inspired by the Haskell snippet at: // https://doisinkidney.com/snippets/drawing-trees.html const // Lefts, Middle, Rights lmrFromStrings = xs => { const [ls, rs] = Array.from(splitAt( Math.floor(xs.length / 2), xs )); return Tuple3(ls, rs[0], rs.slice(1)); }, stringsFromLMR = lmr => Array.from(lmr).reduce((a, x) => a.concat(x), []), fghOverLMR = (f, g, h) => lmr => { const [ls, m, rs] = Array.from(lmr); return Tuple3(ls.map(f), g(m), rs.map(h)); }; const lmrBuild = (f, w) => wsTree => { const leftPad = n => s => ' '.repeat(n) + s, xs = wsTree.nest, lng = xs.length, [nChars, x] = Array.from(wsTree.root); // LEAF NODE -------------------------------------- return 0 === lng ? ( Tuple3([], '─'.repeat(w - nChars) + x, []) // NODE WITH SINGLE CHILD ------------------------- ) : 1 === lng ? (() => { const indented = leftPad(1 + w); return fghOverLMR( indented, z => '─'.repeat(w - nChars) + x + '─' + z, indented )(f(xs[0])); // NODE WITH CHILDREN ----------------------------- })() : (() => { const cFix = x => xs => x + xs, treeFix = (l, m, r) => compose( stringsFromLMR, fghOverLMR(cFix(l), cFix(m), cFix(r)) ), _x = '─'.repeat(w - nChars) + x, indented = leftPad(w), lmrs = xs.map(f); return fghOverLMR( indented, s => _x + ({ '┌': '┬', '├': '┼', '│': '┤', '└': '┴' })[s[0]] + s.slice(1), indented )(lmrFromStrings( intercalate( blnCompact ? [] : ['│'], [treeFix(' ', '┌', '│')(lmrs[0])] .concat(init(lmrs.slice(1)).map( treeFix('│', '├', '│') )) .concat([treeFix('│', '└', ' ')( lmrs[lmrs.length - 1] )]) ) )); })(); }; const measuredTree = fmapTree( v => { const s = ' ' + v + ' '; return Tuple(s.length, s) }, tree ), levelWidths = init(levels(measuredTree)) .reduce( (a, level) => a.concat(maximum(level.map(fst))), [] ), treeLines = stringsFromLMR( levelWidths.reduceRight( lmrBuild, x => x )(measuredTree) ); return unlines( blnPruned ? ( treeLines.filter( s => s.split('') .some(c => !' │'.includes(c)) ) ) : treeLines ); }; // TESTS ---------------------------------------------- const main = () => { // tree :: Tree String const tree = Node( 'Alpha', [ Node('Beta', [ Node('Epsilon', []), Node('Zeta', []), Node('Eta', []) ]), Node('Gamma', [Node('Theta', [])]), Node('Delta', [ Node('Iota', []), Node('Kappa', []), Node('Lambda', []) ]) ]); // tree2 :: Tree Int const tree2 = Node( 1, [ Node(2, [ Node(4, []), Node(5, [Node(7, [])]) ]), Node(3, [ Node(6, [ Node(8, []), Node(9, []) ]) ]) ] ); // strTrees :: String const strTrees = ([ 'Compacted (parents not all vertically centered):', drawTree2(true)(false)(tree2), 'Fully expanded, with vertical centering:', drawTree2(false)(false)(tree), 'Vertically centered, with nodeless lines pruned out:', drawTree2(false)(true)(tree), ].join('\n\n')); return ( console.log(strTrees), strTrees ); }; // GENERIC FUNCTIONS ---------------------------------- // Node :: a -> [Tree a] -> Tree a const Node = (v, xs) => ({ type: 'Node', root: v, // any type of value (consistent across tree) nest: xs || [] }); // Tuple (,) :: a -> b -> (a, b) const Tuple = (a, b) => ({ type: 'Tuple', '0': a, '1': b, length: 2 }); // Tuple3 (,,) :: a -> b -> c -> (a, b, c) const Tuple3 = (a, b, c) => ({ type: 'Tuple3', '0': a, '1': b, '2': c, length: 3 }); // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c const compose = (f, g) => x => f(g(x)); // concat :: [[a]] -> [a] // concat :: [String] -> String const concat = xs => 0 < xs.length ? (() => { const unit = 'string' !== typeof xs[0] ? ( [] ) : ''; return unit.concat.apply(unit, xs); })() : []; // fmapTree :: (a -> b) -> Tree a -> Tree b const fmapTree = (f, tree) => { const go = node => Node( f(node.root), node.nest.map(go) ); return go(tree); }; // fst :: (a, b) -> a const fst = tpl => tpl[0]; // identity :: a -> a const identity = x => x; // init :: [a] -> [a] const init = xs => 0 < xs.length ? ( xs.slice(0, -1) ) : undefined; // intercalate :: [a] -> [[a]] -> [a] // intercalate :: String -> [String] -> String const intercalate = (sep, xs) => 0 < xs.length && 'string' === typeof sep && 'string' === typeof xs[0] ? ( xs.join(sep) ) : concat(intersperse(sep, xs)); // intersperse(0, [1,2,3]) -> [1, 0, 2, 0, 3] // intersperse :: a -> [a] -> [a] // intersperse :: Char -> String -> String const intersperse = (sep, xs) => { const bln = 'string' === typeof xs; return xs.length > 1 ? ( (bln ? concat : x => x)( (bln ? ( xs.split('') ) : xs) .slice(1) .reduce((a, x) => a.concat([sep, x]), [xs[0]]) )) : xs; }; // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a] const iterateUntil = (p, f, x) => { const vs = [x]; let h = x; while (!p(h))(h = f(h), vs.push(h)); return vs; }; // Returns Infinity over objects without finite length. // This enables zip and zipWith to choose the shorter // argument when one is non-finite, like cycle, repeat etc // length :: [a] -> Int const length = xs => (Array.isArray(xs) || 'string' === typeof xs) ? ( xs.length ) : Infinity; // levels :: Tree a -> [[a]] const levels = tree => iterateUntil( xs => 1 > xs.length, ys => [].concat(...ys.map(nest)), [tree] ).map(xs => xs.map(root)); // maximum :: Ord a => [a] -> a const maximum = xs => 0 < xs.length ? ( xs.slice(1).reduce((a, x) => x > a ? x : a, xs[0]) ) : undefined; // nest :: Tree a -> [a] const nest = tree => tree.nest; // root :: Tree a -> a const root = tree => tree.root; // splitAt :: Int -> [a] -> ([a], [a]) const splitAt = (n, xs) => Tuple(xs.slice(0, n), xs.slice(n)); // unlines :: [String] -> String const unlines = xs => xs.join('\n'); // MAIN --- return main(); })();
Voronoi diagram
JavaScript
A Voronoi diagram is a diagram consisting of a number of sites. Each Voronoi site ''s'' also has a Voronoi cell consisting of all points closest to ''s''. ;Task: Demonstrate how to generate and display a Voroni diagram. See algo [[K-means++ clustering]].
===Version #1.=== The obvious route to this in JavaScript would be to use Mike Bostock's D3.js library. There are various examples of Voronoi tesselations, some dynamic: https://bl.ocks.org/mbostock/d1d81455dc21e10f742f some interactive: https://bl.ocks.org/mbostock/4060366 and all with source code, at https://bl.ocks.org/mbostock ===Version #2.=== I would agree: using D3.js library can be very helpful. But having stable and compact algorithm in Python (Sidef) made it possible to develop looking the same Voronoi diagram in "pure" JavaScript. A few custom helper functions simplified code, and they can be used for any other applications.
Water collected between towers
JavaScript from Haskell
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, completely filling all convex enclosures in the chart with water. 9 ## 9 ## 8 ## 8 ## 7 ## ## 7 #### 6 ## ## ## 6 ###### 5 ## ## ## #### 5 ########## 4 ## ## ######## 4 ############ 3 ###### ######## 3 ############## 2 ################ ## 2 ################## 1 #################### 1 #################### In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water. Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart. Calculate the number of water units that could be collected by bar charts representing each of the following seven series: [[1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6]] See, also: * Four Solutions to a Trivial Problem - a Google Tech Talk by Guy Steele * Water collected between towers on Stack Overflow, from which the example above is taken) * An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
(() => { "use strict"; // --------- WATER COLLECTED BETWEEN TOWERS ---------- // waterCollected :: [Int] -> Int const waterCollected = xs => sum(filter(lt(0))( zipWith(subtract)(xs)( zipWith(min)( scanl1(max)(xs) )( scanr1(max)(xs) ) ) )); // ---------------------- TEST ----------------------- const main = () => [ [1, 5, 3, 7, 2], [5, 3, 7, 2, 6, 4, 5, 9, 1, 2], [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1], [5, 5, 5, 5], [5, 6, 7, 8], [8, 7, 7, 6], [6, 7, 10, 7, 6] ].map(waterCollected); // --------------------- GENERIC --------------------- // Tuple (,) :: a -> b -> (a, b) const Tuple = a => b => ({ type: "Tuple", "0": a, "1": b, length: 2 }); // filter :: (a -> Bool) -> [a] -> [a] const filter = p => // The elements of xs which match // the predicate p. xs => [...xs].filter(p); // lt (<) :: Ord a => a -> a -> Bool const lt = a => b => a < b; // max :: Ord a => a -> a -> a const max = a => // b if its greater than a, // otherwise a. b => a > b ? a : b; // min :: Ord a => a -> a -> a const min = a => b => b < a ? b : a; // scanl :: (b -> a -> b) -> b -> [a] -> [b] const scanl = f => startValue => xs => xs.reduce((a, x) => { const v = f(a[0])(x); return Tuple(v)(a[1].concat(v)); }, Tuple(startValue)([startValue]))[1]; // scanl1 :: (a -> a -> a) -> [a] -> [a] const scanl1 = f => // scanl1 is a variant of scanl that // has no starting value argument. xs => xs.length > 0 ? ( scanl(f)( xs[0] )(xs.slice(1)) ) : []; // scanr :: (a -> b -> b) -> b -> [a] -> [b] const scanr = f => startValue => xs => xs.reduceRight( (a, x) => { const v = f(x)(a[0]); return Tuple(v)([v].concat(a[1])); }, Tuple(startValue)([startValue]) )[1]; // scanr1 :: (a -> a -> a) -> [a] -> [a] const scanr1 = f => // scanr1 is a variant of scanr that has no // seed-value argument, and assumes that // xs is not empty. xs => xs.length > 0 ? ( scanr(f)( xs.slice(-1)[0] )(xs.slice(0, -1)) ) : []; // subtract :: Num -> Num -> Num const subtract = x => y => y - x; // sum :: [Num] -> Num const sum = xs => // The numeric sum of all values in xs. xs.reduce((a, x) => a + x, 0); // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = f => // A list constructed by zipping with a // custom function, rather than with the // default tuple constructor. xs => ys => xs.map( (x, i) => f(x)(ys[i]) ).slice( 0, Math.min(xs.length, ys.length) ); // MAIN --- return main(); })();
Weird numbers
JavaScript from Haskell
In number theory, a perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is ''abundant''), but no subset of those divisors sums to the number itself (the number is not ''semiperfect''). For example: * '''12''' is ''not'' a weird number. ** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12), ** but it ''is'' semiperfect, e.g.: '''6 + 4 + 2 == 12'''. * '''70''' ''is'' a weird number. ** It is abundant; its proper divisors '''1, 2, 5, 7, 10, 14, 35''' sum to '''74''' (which ''is'' > 70), ** and there is no subset of proper divisors that sum to '''70'''. ;Task: Find and display, here on this page, the first '''25''' weird numbers. ;Related tasks: :* Abundant, deficient and perfect number classifications :* Proper divisors ;See also: :* OEIS: A006037 weird numbers :* Wikipedia: weird number :* MathWorld: weird number
(() => { 'use strict'; // main :: IO () const main = () => take(25, weirds()); // weirds :: Gen [Int] function* weirds() { let x = 1, i = 1; while (true) { x = until(isWeird, succ, x) console.log(i.toString() + ' -> ' + x) yield x; x = 1 + x; i = 1 + i; } } // isWeird :: Int -> Bool const isWeird = n => { const ds = descProperDivisors(n), d = sum(ds) - n; return 0 < d && !hasSum(d, ds) }; // hasSum :: Int -> [Int] -> Bool const hasSum = (n, xs) => { const go = (n, xs) => 0 < xs.length ? (() => { const h = xs[0], t = xs.slice(1); return n < h ? ( go(n, t) ) : ( n == h || hasSum(n - h, t) || hasSum(n, t) ); })() : false; return go(n, xs); }; // descProperDivisors :: Int -> [Int] const descProperDivisors = n => { const rRoot = Math.sqrt(n), intRoot = Math.floor(rRoot), blnPerfect = rRoot === intRoot, lows = enumFromThenTo(intRoot, intRoot - 1, 1) .filter(x => (n % x) === 0); return ( reverse(lows) .slice(1) .map(x => n / x) ).concat((blnPerfect ? tail : id)(lows)) }; // GENERIC FUNCTIONS ---------------------------- // enumFromThenTo :: Int -> Int -> Int -> [Int] const enumFromThenTo = (x1, x2, y) => { const d = x2 - x1; return Array.from({ length: Math.floor(y - x2) / d + 2 }, (_, i) => x1 + (d * i)); }; // id :: a -> a const id = x => x; // reverse :: [a] -> [a] const reverse = xs => 'string' !== typeof xs ? ( xs.slice(0).reverse() ) : xs.split('').reverse().join(''); // succ :: Enum a => a -> a const succ = x => 1 + x; // sum :: [Num] -> Num const sum = xs => xs.reduce((a, x) => a + x, 0); // tail :: [a] -> [a] const tail = xs => 0 < xs.length ? xs.slice(1) : []; // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = (n, xs) => 'GeneratorFunction' !== xs.constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat.apply([], Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; })); // until :: (a -> Bool) -> (a -> a) -> a -> a const until = (p, f, x) => { let v = x; while (!p(v)) v = f(v); return v; }; // MAIN --- return main(); })();
Word wrap
JavaScript
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.
function wrap (text, limit) { if (text.length > limit) { // find the last space within limit var edge = text.slice(0, limit).lastIndexOf(' '); if (edge > 0) { var line = text.slice(0, edge); var remainder = text.slice(edge + 1); return line + '\n' + wrap(remainder, limit); } } return text; }
Zeckendorf number representation
JavaScript from Haskell
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]]
(() => { 'use strict'; const main = () => unlines( map(n => concat(zeckendorf(n)), enumFromTo(0, 20) ) ); // zeckendorf :: Int -> String const zeckendorf = n => { const go = (n, x) => n < x ? ( Tuple(n, '0') ) : Tuple(n - x, '1') return 0 < n ? ( snd(mapAccumL( go, n, reverse(fibUntil(n)) )) ) : ['0']; }; // fibUntil :: Int -> [Int] const fibUntil = n => cons(1, takeWhile(x => n >= x, map(snd, iterateUntil( tpl => n <= fst(tpl), tpl => { const x = snd(tpl); return Tuple(x, x + fst(tpl)); }, Tuple(1, 2) )))); // GENERIC FUNCTIONS ---------------------------- // Tuple (,) :: a -> b -> (a, b) const Tuple = (a, b) => ({ type: 'Tuple', '0': a, '1': b, length: 2 }); // concat :: [[a]] -> [a] // concat :: [String] -> String const concat = xs => 0 < xs.length ? (() => { const unit = 'string' !== typeof xs[0] ? ( [] ) : ''; return unit.concat.apply(unit, xs); })() : []; // cons :: a -> [a] -> [a] const cons = (x, xs) => Array.isArray(xs) ? ( [x].concat(xs) ) : (x + xs); // enumFromTo :: Int -> Int -> [Int] const enumFromTo = (m, n) => m <= n ? iterateUntil( x => n <= x, x => 1 + x, m ) : []; // fst :: (a, b) -> a const fst = tpl => tpl[0]; // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a] const iterateUntil = (p, f, x) => { const vs = [x]; let h = x; while (!p(h))(h = f(h), vs.push(h)); return vs; }; // map :: (a -> b) -> [a] -> [b] const map = (f, xs) => xs.map(f); // 'The mapAccumL function behaves like a combination of map and foldl; // it applies a function to each element of a list, passing an accumulating // parameter from left to right, and returning a final value of this // accumulator together with the new list.' (See Hoogle) // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) const mapAccumL = (f, acc, xs) => xs.reduce((a, x, i) => { const pair = f(a[0], x, i); return Tuple(pair[0], a[1].concat(pair[1])); }, Tuple(acc, [])); // reverse :: [a] -> [a] const reverse = xs => 'string' !== typeof xs ? ( xs.slice(0).reverse() ) : xs.split('').reverse().join(''); // snd :: (a, b) -> b const snd = tpl => tpl[1]; // tail :: [a] -> [a] const tail = xs => 0 < xs.length ? xs.slice(1) : []; // takeWhile :: (a -> Bool) -> [a] -> [a] // takeWhile :: (Char -> Bool) -> String -> String const takeWhile = (p, xs) => { const lng = xs.length; return 0 < lng ? xs.slice( 0, until( i => i === lng || !p(xs[i]), i => 1 + i, 0 ) ) : []; }; // unlines :: [String] -> String const unlines = xs => xs.join('\n'); // until :: (a -> Bool) -> (a -> a) -> a -> a const until = (p, f, x) => { let v = x; while (!p(v)) v = f(v); return v; }; // MAIN --- return main(); })();
Zhang-Suen thinning algorithm
JavaScript from Java
This is an algorithm used to thin a black and white i.e. one bit per pixel images. For example, with an input image of: ################# ############# ################## ################ ################### ################## ######## ####### ################### ###### ####### ####### ###### ###### ####### ####### ################# ####### ################ ####### ################# ####### ###### ####### ####### ###### ####### ####### ###### ####### ####### ###### ######## ####### ################### ######## ####### ###### ################## ###### ######## ####### ###### ################ ###### ######## ####### ###### ############# ###### It produces the thinned output: # ########## ####### ## # #### # # # ## # # # # # # # # # ############ # # # # # # # # # # # # # # ## # ############ ### ### ;Algorithm: Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes. The algorithm operates on all black pixels P1 that can have eight neighbours. The neighbours are, in order, arranged as: P9 P2 P3 P8 P1 P4 P7 P6 P5 Obviously the boundary pixels of the image cannot have the full eight neighbours. * Define A(P1) = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular). * Define B(P1) = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) ) ;Step 1: All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage. * (0) The pixel is black and has eight neighbours * (1) 2 <= B(P1) <= 6 * (2) A(P1) = 1 * (3) At least one of P2 and P4 and P6 is white * (4) At least one of P4 and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white. ;Step 2: All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage. * (0) The pixel is black and has eight neighbours * (1) 2 <= B(P1) <= 6 * (2) A(P1) = 1 * (3) At least one of P2 and P4 and '''P8''' is white * (4) At least one of '''P2''' and P6 and P8 is white After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white. ;Iteration: If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed. ;Task: # Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes. # Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. 00000000000000000000000000000000 01111111110000000111111110000000 01110001111000001111001111000000 01110000111000001110000111000000 01110001111000001110000000000000 01111111110000001110000000000000 01110111100000001110000111000000 01110011110011101111001111011100 01110001111011100111111110011100 00000000000000000000000000000000 ;Reference: * Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza. * "Character Recognition Systems: A Guide for Students and Practitioners" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen
function Point(x, y) { this.x = x; this.y = y; } var ZhangSuen = (function () { function ZhangSuen() { } ZhangSuen.image = [" ", " ################# ############# ", " ################## ################ ", " ################### ################## ", " ######## ####### ################### ", " ###### ####### ####### ###### ", " ###### ####### ####### ", " ################# ####### ", " ################ ####### ", " ################# ####### ", " ###### ####### ####### ", " ###### ####### ####### ", " ###### ####### ####### ###### ", " ######## ####### ################### ", " ######## ####### ###### ################## ###### ", " ######## ####### ###### ################ ###### ", " ######## ####### ###### ############# ###### ", " "]; ZhangSuen.nbrs = [[0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1]]; ZhangSuen.nbrGroups = [[[0, 2, 4], [2, 4, 6]], [[0, 2, 6], [0, 4, 6]]]; ZhangSuen.toWhite = new Array(); ; ZhangSuen.main = function (args) { ZhangSuen.grid = new Array(ZhangSuen.image.length); for (var r = 0; r < ZhangSuen.image.length; r++) ZhangSuen.grid[r] = (ZhangSuen.image[r]).split(''); ZhangSuen.thinImage(); }; ZhangSuen.thinImage = function () { var firstStep = false; var hasChanged; do { hasChanged = false; firstStep = !firstStep; for (var r = 1; r < ZhangSuen.grid.length - 1; r++) { for (var c = 1; c < ZhangSuen.grid[0].length - 1; c++) { if (ZhangSuen.grid[r][c] !== '#') continue; var nn = ZhangSuen.numNeighbors(r, c); if (nn < 2 || nn > 6) continue; if (ZhangSuen.numTransitions(r, c) !== 1) continue; if (!ZhangSuen.atLeastOneIsWhite(r, c, firstStep ? 0 : 1)) continue; ZhangSuen.toWhite.push(new Point(c, r)); hasChanged = true; } } for (let i = 0; i < ZhangSuen.toWhite.length; i++) { var p = ZhangSuen.toWhite[i]; ZhangSuen.grid[p.y][p.x] = ' '; } ZhangSuen.toWhite = new Array(); } while ((firstStep || hasChanged)); ZhangSuen.printResult(); }; ZhangSuen.numNeighbors = function (r, c) { var count = 0; for (var i = 0; i < ZhangSuen.nbrs.length - 1; i++) if (ZhangSuen.grid[r + ZhangSuen.nbrs[i][1]][c + ZhangSuen.nbrs[i][0]] === '#') count++; return count; }; ZhangSuen.numTransitions = function (r, c) { var count = 0; for (var i = 0; i < ZhangSuen.nbrs.length - 1; i++) if (ZhangSuen.grid[r + ZhangSuen.nbrs[i][1]][c + ZhangSuen.nbrs[i][0]] === ' ') { if (ZhangSuen.grid[r + ZhangSuen.nbrs[i + 1][1]][c + ZhangSuen.nbrs[i + 1][0]] === '#') count++; } return count; }; ZhangSuen.atLeastOneIsWhite = function (r, c, step) { var count = 0; var group = ZhangSuen.nbrGroups[step]; for (var i = 0; i < 2; i++) for (var j = 0; j < group[i].length; j++) { var nbr = ZhangSuen.nbrs[group[i][j]]; if (ZhangSuen.grid[r + nbr[1]][c + nbr[0]] === ' ') { count++; break; } } return count > 1; }; ZhangSuen.printResult = function () { for (var i = 0; i < ZhangSuen.grid.length; i++) { var row = ZhangSuen.grid[i]; console.log(row.join('')); } }; return ZhangSuen; }()); ZhangSuen.main(null);
100 doors
Kotlin
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.
fun oneHundredDoors(): List<Int> { val doors = BooleanArray(100) { false } repeat(doors.size) { i -> for (j in i until doors.size step (i + 1)) { doors[j] = !doors[j] } } return doors .foldIndexed(emptyList()) { i, acc, door -> if (door) acc + (i + 1) else acc } }
100 prisoners
Kotlin
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.
val playOptimal: () -> Boolean = { val secrets = (0..99).toMutableList() var ret = true secrets.shuffle() prisoner@ for(i in 0 until 100){ var prev = i draw@ for(j in 0 until 50){ if (secrets[prev] == i) continue@prisoner prev = secrets[prev] } ret = false break@prisoner } ret } val playRandom: ()->Boolean = { var ret = true val secrets = (0..99).toMutableList() secrets.shuffle() prisoner@ for(i in 0 until 100){ val opened = mutableListOf<Int>() val genNum : () ->Int = { var r = (0..99).random() while (opened.contains(r)) { r = (0..99).random() } r } for(j in 0 until 50){ val draw = genNum() if ( secrets[draw] == i) continue@prisoner opened.add(draw) } ret = false break@prisoner } ret } fun exec(n:Int, play:()->Boolean):Double{ var succ = 0 for (i in IntRange(0, n-1)){ succ += if(play()) 1 else 0 } return (succ*100.0)/n } fun main() { val N = 100_000 println("# of executions: $N") println("Optimal play success rate: ${exec(N, playOptimal)}%") println("Random play success rate: ${exec(N, playRandom)}%") }
15 puzzle game
Kotlin from Java
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]]
// version 1.1.3 import java.awt.BorderLayout import java.awt.Color import java.awt.Dimension import java.awt.Font import java.awt.Graphics import java.awt.Graphics2D import java.awt.RenderingHints import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.util.Random import javax.swing.JFrame import javax.swing.JPanel import javax.swing.SwingUtilities class FifteenPuzzle(dim: Int, val margin: Int) : JPanel() { private val rand = Random() private val tiles = IntArray(16) private val tileSize = (dim - 2 * margin) / 4 private val gridSize = tileSize * 4 private var blankPos = 0 init { preferredSize = Dimension(dim, dim) background = Color.white val cornflowerBlue = 0x6495ED foreground = Color(cornflowerBlue) font = Font("SansSerif", Font.BOLD, 60) addMouseListener(object : MouseAdapter() { override fun mousePressed(e: MouseEvent) { val ex = e.x - margin val ey = e.y - margin if (ex !in 0..gridSize || ey !in 0..gridSize) return val c1 = ex / tileSize val r1 = ey / tileSize val c2 = blankPos % 4 val r2 = blankPos / 4 if ((c1 == c2 && Math.abs(r1 - r2) == 1) || (r1 == r2 && Math.abs(c1 - c2) == 1)) { val clickPos = r1 * 4 + c1 tiles[blankPos] = tiles[clickPos] tiles[clickPos] = 0 blankPos = clickPos } repaint() } }) shuffle() } private fun shuffle() { do { reset() // don't include the blank space in the shuffle, // leave it in the home position var n = 15 while (n > 1) { val r = rand.nextInt(n--) val tmp = tiles[r] tiles[r] = tiles[n] tiles[n] = tmp } } while (!isSolvable()) } private fun reset() { for (i in 0 until tiles.size) { tiles[i] = (i + 1) % tiles.size } blankPos = 15 } /* Only half the permutations of the puzzle are solvable. Whenever a tile is preceded by a tile with higher value it counts as an inversion. In our case, with the blank space in the home position, the number of inversions must be even for the puzzle to be solvable. */ private fun isSolvable(): Boolean { var countInversions = 0 for (i in 0 until 15) { (0 until i) .filter { tiles[it] > tiles[i] } .forEach { countInversions++ } } return countInversions % 2 == 0 } private fun drawGrid(g: Graphics2D) { for (i in 0 until tiles.size) { if (tiles[i] == 0) continue val r = i / 4 val c = i % 4 val x = margin + c * tileSize val y = margin + r * tileSize with(g) { color = foreground fillRoundRect(x, y, tileSize, tileSize, 25, 25) color = Color.black drawRoundRect(x, y, tileSize, tileSize, 25, 25) color = Color.white } drawCenteredString(g, tiles[i].toString(), x, y) } } private fun drawCenteredString(g: Graphics2D, s: String, x: Int, y: Int) { val fm = g.fontMetrics val asc = fm.ascent val des = fm.descent val xx = x + (tileSize - fm.stringWidth(s)) / 2 val yy = y + (asc + (tileSize - (asc + des)) / 2) g.drawString(s, xx, yy) } override fun paintComponent(gg: Graphics) { super.paintComponent(gg) val g = gg as Graphics2D g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) drawGrid(g) } } fun main(args: Array<String>) { SwingUtilities.invokeLater { val f = JFrame() with(f) { defaultCloseOperation = JFrame.EXIT_ON_CLOSE title = "Fifteen Puzzle" isResizable = false add(FifteenPuzzle(640, 80), BorderLayout.CENTER) pack() setLocationRelativeTo(null) isVisible = true } } }
24 game
Kotlin
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.
import java.util.Random import java.util.Scanner import java.util.Stack internal object Game24 { fun run() { val r = Random() val digits = IntArray(4).map { r.nextInt(9) + 1 } println("Make 24 using these digits: $digits") print("> ") val s = Stack<Float>() var total = 0L val cin = Scanner(System.`in`) for (c in cin.nextLine()) { when (c) { in '0'..'9' -> { val d = c - '0' total += (1 shl (d * 5)).toLong() s += d.toFloat() } else -> if ("+/-*".indexOf(c) != -1) { s += c.applyOperator(s.pop(), s.pop()) } } } when { tally(digits) != total -> print("Not the same digits. ") s.peek().compareTo(target) == 0 -> println("Correct!") else -> print("Not correct.") } } private fun Char.applyOperator(a: Float, b: Float) = when (this) { '+' -> a + b '-' -> b - a '*' -> a * b '/' -> b / a else -> Float.NaN } private fun tally(a: List<Int>): Long = a.reduce({ t, i -> t + (1 shl (i * 5)) }).toLong() private val target = 24 } fun main(args: Array<String>) = Game24.run()
24 game/Solve
Kotlin from C
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]]
// version 1.1.3 import java.util.Random const val N_CARDS = 4 const val SOLVE_GOAL = 24 const val MAX_DIGIT = 9 class Frac(val num: Int, val den: Int) enum class OpType { NUM, ADD, SUB, MUL, DIV } class Expr( var op: OpType = OpType.NUM, var left: Expr? = null, var right: Expr? = null, var value: Int = 0 ) fun showExpr(e: Expr?, prec: OpType, isRight: Boolean) { if (e == null) return val op = when (e.op) { OpType.NUM -> { print(e.value); return } OpType.ADD -> " + " OpType.SUB -> " - " OpType.MUL -> " x " OpType.DIV -> " / " } if ((e.op == prec && isRight) || e.op < prec) print("(") showExpr(e.left, e.op, false) print(op) showExpr(e.right, e.op, true) if ((e.op == prec && isRight) || e.op < prec) print(")") } fun evalExpr(e: Expr?): Frac { if (e == null) return Frac(0, 1) if (e.op == OpType.NUM) return Frac(e.value, 1) val l = evalExpr(e.left) val r = evalExpr(e.right) return when (e.op) { OpType.ADD -> Frac(l.num * r.den + l.den * r.num, l.den * r.den) OpType.SUB -> Frac(l.num * r.den - l.den * r.num, l.den * r.den) OpType.MUL -> Frac(l.num * r.num, l.den * r.den) OpType.DIV -> Frac(l.num * r.den, l.den * r.num) else -> throw IllegalArgumentException("Unknown op: ${e.op}") } } fun solve(ea: Array<Expr?>, len: Int): Boolean { if (len == 1) { val final = evalExpr(ea[0]) if (final.num == final.den * SOLVE_GOAL && final.den != 0) { showExpr(ea[0], OpType.NUM, false) return true } } val ex = arrayOfNulls<Expr>(N_CARDS) for (i in 0 until len - 1) { for (j in i + 1 until len) ex[j - 1] = ea[j] val node = Expr() ex[i] = node for (j in i + 1 until len) { node.left = ea[i] node.right = ea[j] for (k in OpType.values().drop(1)) { node.op = k if (solve(ex, len - 1)) return true } node.left = ea[j] node.right = ea[i] node.op = OpType.SUB if (solve(ex, len - 1)) return true node.op = OpType.DIV if (solve(ex, len - 1)) return true ex[j] = ea[j] } ex[i] = ea[i] } return false } fun solve24(n: IntArray) = solve (Array(N_CARDS) { Expr(value = n[it]) }, N_CARDS) fun main(args: Array<String>) { val r = Random() val n = IntArray(N_CARDS) for (j in 0..9) { for (i in 0 until N_CARDS) { n[i] = 1 + r.nextInt(MAX_DIGIT) print(" ${n[i]}") } print(": ") println(if (solve24(n)) "" else "No solution") } }
4-rings or 4-squares puzzle
Kotlin from C
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]]
// version 1.1.2 class FourSquares( private val lo: Int, private val hi: Int, private val unique: Boolean, private val show: Boolean ) { private var a = 0 private var b = 0 private var c = 0 private var d = 0 private var e = 0 private var f = 0 private var g = 0 private var s = 0 init { println() if (show) { println("a b c d e f g") println("-------------") } acd() println("\n$s ${if (unique) "unique" else "non-unique"} solutions in $lo to $hi") } private fun acd() { c = lo while (c <= hi) { d = lo while (d <= hi) { if (!unique || c != d) { a = c + d if ((a in lo..hi) && (!unique || (c != 0 && d!= 0))) ge() } d++ } c++ } } private fun bf() { f = lo while (f <= hi) { if (!unique || (f != a && f != c && f != d && f != e && f!= g)) { b = e + f - c if ((b in lo..hi) && (!unique || (b != a && b != c && b != d && b != e && b != f && b!= g))) { s++ if (show) println("$a $b $c $d $e $f $g") } } f++ } } private fun ge() { e = lo while (e <= hi) { if (!unique || (e != a && e != c && e != d)) { g = d + e if ((g in lo..hi) && (!unique || (g != a && g != c && g != d && g != e))) bf() } e++ } } } fun main(args: Array<String>) { FourSquares(1, 7, true, true) FourSquares(3, 9, true, true) FourSquares(0, 9, false, false) }
99 bottles of beer
Kotlin
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
fun main(args: Array<String>) { for (i in 99.downTo(1)) { println("$i bottles of beer on the wall") println("$i bottles of beer") println("Take one down, pass it around") } println("No more bottles of beer on the wall!") }
9 billion names of God the integer
Kotlin from Swift
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]]
import java.lang.Math.min import java.math.BigInteger import java.util.ArrayList import java.util.Arrays.asList fun namesOfGod(n: Int): List<BigInteger> { val cache = ArrayList<List<BigInteger>>() cache.add(asList(BigInteger.ONE)) (cache.size..n).forEach { l -> val r = ArrayList<BigInteger>() r.add(BigInteger.ZERO) (1..l).forEach { x -> r.add(r[r.size - 1] + cache[l - x][min(x, l - x)]) } cache.add(r) } return cache[n] } fun row(n: Int) = namesOfGod(n).let { r -> (0 until n).map { r[it + 1] - r[it] } } fun main(args: Array<String>) { println("Rows:") (1..25).forEach { System.out.printf("%2d: %s%n", it, row(it)) } println("\nSums:") intArrayOf(23, 123, 1234, 1234).forEach { val c = namesOfGod(it) System.out.printf("%s %s%n", it, c[c.size - 1]) } }
A+B
Kotlin
'''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 |}
// version 1.0.5-2 fun main(args: Array<String>) { val r = Regex("""-?\d+[ ]+-?\d+""") while(true) { print("Enter two integers separated by space(s) or q to quit: ") val input: String = readLine()!!.trim() if (input == "q" || input == "Q") break if (!input.matches(r)) { println("Invalid input, try again") continue } val index = input.lastIndexOf(' ') val a = input.substring(0, index).trimEnd().toInt() val b = input.substring(index + 1).toInt() if (Math.abs(a) > 1000 || Math.abs(b) > 1000) { println("Both numbers must be in the interval [-1000, 1000] - try again") } else { println("Their sum is ${a + b}\n") } } }
ABC problem
Kotlin from Java
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
object ABC_block_checker { fun run() { println("\"\": " + blocks.canMakeWord("")) for (w in words) println("$w: " + blocks.canMakeWord(w)) } private fun Array<String>.swap(i: Int, j: Int) { val tmp = this[i] this[i] = this[j] this[j] = tmp } private fun Array<String>.canMakeWord(word: String): Boolean { if (word.isEmpty()) return true val c = word.first().toUpperCase() var i = 0 forEach { b -> if (b.first().toUpperCase() == c || b[1].toUpperCase() == c) { swap(0, i) if (drop(1).toTypedArray().canMakeWord(word.substring(1))) return true swap(0, i) } i++ } return false } private val blocks = arrayOf( "BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM" ) private val words = arrayOf("A", "BARK", "book", "treat", "COMMON", "SQuAd", "CONFUSE") } fun main(args: Array<String>) = ABC_block_checker.run()
AVL tree
Kotlin from Java
{{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]]
class AvlTree { private var root: Node? = null private class Node(var key: Int, var parent: Node?) { var balance: Int = 0 var left : Node? = null var right: Node? = null } fun insert(key: Int): Boolean { if (root == null) root = Node(key, null) else { var n: Node? = root var parent: Node while (true) { if (n!!.key == key) return false parent = n val goLeft = n.key > key n = if (goLeft) n.left else n.right if (n == null) { if (goLeft) parent.left = Node(key, parent) else parent.right = Node(key, parent) rebalance(parent) break } } } return true } fun delete(delKey: Int) { if (root == null) return var n: Node? = root var parent: Node? = root var delNode: Node? = null var child: Node? = root while (child != null) { parent = n n = child child = if (delKey >= n.key) n.right else n.left if (delKey == n.key) delNode = n } if (delNode != null) { delNode.key = n!!.key child = if (n.left != null) n.left else n.right if (0 == root!!.key.compareTo(delKey)) { root = child if (null != root) { root!!.parent = null } } else { if (parent!!.left == n) parent.left = child else parent.right = child if (null != child) { child.parent = parent } rebalance(parent) } } private fun rebalance(n: Node) { setBalance(n) var nn = n if (nn.balance == -2) if (height(nn.left!!.left) >= height(nn.left!!.right)) nn = rotateRight(nn) else nn = rotateLeftThenRight(nn) else if (nn.balance == 2) if (height(nn.right!!.right) >= height(nn.right!!.left)) nn = rotateLeft(nn) else nn = rotateRightThenLeft(nn) if (nn.parent != null) rebalance(nn.parent!!) else root = nn } private fun rotateLeft(a: Node): Node { val b: Node? = a.right b!!.parent = a.parent a.right = b.left if (a.right != null) a.right!!.parent = a b.left = a a.parent = b if (b.parent != null) { if (b.parent!!.right == a) b.parent!!.right = b else b.parent!!.left = b } setBalance(a, b) return b } private fun rotateRight(a: Node): Node { val b: Node? = a.left b!!.parent = a.parent a.left = b.right if (a.left != null) a.left!!.parent = a b.right = a a.parent = b if (b.parent != null) { if (b.parent!!.right == a) b.parent!!.right = b else b.parent!!.left = b } setBalance(a, b) return b } private fun rotateLeftThenRight(n: Node): Node { n.left = rotateLeft(n.left!!) return rotateRight(n) } private fun rotateRightThenLeft(n: Node): Node { n.right = rotateRight(n.right!!) return rotateLeft(n) } private fun height(n: Node?): Int { if (n == null) return -1 return 1 + Math.max(height(n.left), height(n.right)) } private fun setBalance(vararg nodes: Node) { for (n in nodes) n.balance = height(n.right) - height(n.left) } fun printKey() { printKey(root) println() } private fun printKey(n: Node?) { if (n != null) { printKey(n.left) print("${n.key} ") printKey(n.right) } } fun printBalance() { printBalance(root) println() } private fun printBalance(n: Node?) { if (n != null) { printBalance(n.left) print("${n.balance} ") printBalance(n.right) } } } fun main(args: Array<String>) { val tree = AvlTree() println("Inserting values 1 to 10") for (i in 1..10) tree.insert(i) print("Printing key : ") tree.printKey() print("Printing balance : ") tree.printBalance() }
Abbreviations, automatic
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.
// version 1.1.4-3 import java.io.File val r = Regex("[ ]+") fun main(args: Array<String>) { val lines = File("days_of_week.txt").readLines() for ((i, line) in lines.withIndex()) { if (line.trim().isEmpty()) { println() continue } val days = line.trim().split(r) if (days.size != 7) throw RuntimeException("There aren't 7 days in line ${i + 1}") if (days.distinct().size < 7) { // implies some days have the same name println(" ∞ $line") continue } var len = 1 while (true) { if (days.map { it.take(len) }.distinct().size == 7) { println("${"%2d".format(len)} $line") break } len++ } } }
Abbreviations, easy
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
// version 1.1.4-3 val r = Regex("[ ]+") val 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 " fun validate(commands: List<String>, minLens: List<Int>, words: List<String>): List<String> { if (words.isEmpty()) return emptyList<String>() val results = mutableListOf<String>() for (word in words) { var matchFound = false for ((i, command) in commands.withIndex()) { if (minLens[i] == 0 || word.length !in minLens[i] .. command.length) continue if (command.startsWith(word, true)) { results.add(command.toUpperCase()) matchFound = true break } } if (!matchFound) results.add("*error*") } return results } fun main(args: Array<String>) { val commands = table.trimEnd().split(r) val minLens = MutableList(commands.size) { commands[it].count { c -> c.isUpperCase() } } val sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin" val words = sentence.trim().split(r) val results = validate(commands, minLens, words) print("user words: ") for (j in 0 until words.size) print("${words[j].padEnd(results[j].length)} ") print("\nfull words: ") for (j in 0 until results.size) print("${results[j]} ") println() }
Abbreviations, simple
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
import java.util.Locale private const val 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 " private data class Command(val name: String, val minLen: Int) private fun parse(commandList: String): List<Command> { val commands = mutableListOf<Command>() val fields = commandList.trim().split(" ") var i = 0 while (i < fields.size) { val name = fields[i++] var minLen = name.length if (i < fields.size) { val num = fields[i].toIntOrNull() if (num != null && num in 1..minLen) { minLen = num i++ } } commands.add(Command(name, minLen)) } return commands } private fun get(commands: List<Command>, word: String): String? { for ((name, minLen) in commands) { if (word.length in minLen..name.length && name.startsWith(word, true)) { return name.toUpperCase(Locale.ROOT) } } return null } fun main(args: Array<String>) { val commands = parse(table) val sentence = "riG rePEAT copies put mo rest types fup. 6 poweRin" val words = sentence.trim().split(" ") val results = words.map { word -> get(commands, word) ?: "*error*" } val paddedUserWords = words.mapIndexed { i, word -> word.padEnd(results[i].length) } println("user words: ${paddedUserWords.joinToString(" ")}") println("full words: ${results.joinToString(" ")}") }
Abundant odd numbers
Kotlin from D
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)
fun divisors(n: Int): List<Int> { val divs = mutableListOf(1) val divs2 = mutableListOf<Int>() var i = 2 while (i * i <= n) { if (n % i == 0) { val j = n / i divs.add(i) if (i != j) { divs2.add(j) } } i++ } divs.addAll(divs2.reversed()) return divs } fun abundantOdd(searchFrom: Int, countFrom: Int, countTo: Int, printOne: Boolean): Int { var count = countFrom var n = searchFrom while (count < countTo) { val divs = divisors(n) val tot = divs.sum() if (tot > n) { count++ if (!printOne || count >= countTo) { val s = divs.joinToString(" + ") if (printOne) { println("$n < $s = $tot") } else { println("%2d. %5d < %s = %d".format(count, n, s, tot)) } } } n += 2 } return n } fun main() { val max = 25 println("The first $max abundant odd numbers are:") val n = abundantOdd(1, 0, 25, false) println("\nThe one thousandth abundant odd number is:") abundantOdd(n, 25, 1000, true) println("\nThe first abundant odd number above one billion is:") abundantOdd((1e9 + 1).toInt(), 0, 1, true) }
Accumulator factory
Kotlin
{{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.
// version 1.1 fun foo(n: Double): (d: Double) -> Double { var nn = n return { nn += it; nn } } fun foo(n: Int): (i: Int) -> Int { var nn = n return { nn += it; nn } } fun main(args: Array<String>) { val x = foo(1.0) // calls 'Double' overload x(5.0) foo(3.0) println(x(2.3)) val y = foo(1) // calls 'Int' overload y(5) foo(5) println(y(2)) }
Aliquot sequence classifications
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]]
// version 1.1.3 data class Classification(val sequence: List<Long>, val aliquot: String) const val THRESHOLD = 1L shl 47 fun sumProperDivisors(n: Long): Long { if (n < 2L) return 0L val sqrt = Math.sqrt(n.toDouble()).toLong() var sum = 1L + (2L..sqrt) .filter { n % it == 0L } .map { it + n / it } .sum() if (sqrt * sqrt == n) sum -= sqrt return sum } fun classifySequence(k: Long): Classification { require(k > 0) var last = k val seq = mutableListOf(k) while (true) { last = sumProperDivisors(last) seq.add(last) val n = seq.size val aliquot = when { last == 0L -> "Terminating" n == 2 && last == k -> "Perfect" n == 3 && last == k -> "Amicable" n >= 4 && last == k -> "Sociable[${n - 1}]" last == seq[n - 2] -> "Aspiring" last in seq.slice(1..n - 3) -> "Cyclic[${n - 1 - seq.indexOf(last)}]" n == 16 || last > THRESHOLD -> "Non-Terminating" else -> "" } if (aliquot != "") return Classification(seq, aliquot) } } fun main(args: Array<String>) { println("Aliqot classifications - periods for Sociable/Cyclic in square brackets:\n") for (k in 1L..10) { val (seq, aliquot) = classifySequence(k) println("${"%2d".format(k)}: ${aliquot.padEnd(15)} $seq") } val la = longArrayOf( 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488 ) println() for (k in la) { val (seq, aliquot) = classifySequence(k) println("${"%7d".format(k)}: ${aliquot.padEnd(15)} $seq") } println() val k = 15355717786080L val (seq, aliquot) = classifySequence(k) println("$k: ${aliquot.padEnd(15)} $seq") }
Amb
Kotlin
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.
// version 1.2.41 import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* fun main(args: Array<String>) = amb { val a = amb("the", "that", "a") val b = amb("frog", "elephant", "thing") val c = amb("walked", "treaded", "grows") val d = amb("slowly", "quickly") if (a[a.lastIndex] != b[0]) amb() if (b[b.lastIndex] != c[0]) amb() if (c[c.lastIndex] != d[0]) amb() println(listOf(a, b, c, d)) val x = amb(1, 2, 3) val y = amb(7, 6, 4, 5) if (x * y != 8) amb() println(listOf(x, y)) } class AmbException(): Exception("Refusing to execute") data class AmbPair<T>(val cont: Continuation<T>, val valuesLeft: MutableList<T>) @RestrictsSuspension class AmbEnvironment { val ambList = mutableListOf<AmbPair<*>>() suspend fun <T> amb(value: T, vararg rest: T): T = suspendCoroutineOrReturn { cont -> if (rest.size > 0) { ambList.add(AmbPair(clone(cont), mutableListOf(*rest))) } value } suspend fun amb(): Nothing = suspendCoroutine<Nothing> { } } @Suppress("UNCHECKED_CAST") fun <R> amb(block: suspend AmbEnvironment.() -> R): R { var result: R? = null var toThrow: Throwable? = null val dist = AmbEnvironment() block.startCoroutine(receiver = dist, completion = object : Continuation<R> { override val context: CoroutineContext get() = EmptyCoroutineContext override fun resume(value: R) { result = value } override fun resumeWithException(exception: Throwable) { toThrow = exception } }) while (result == null && toThrow == null && !dist.ambList.isEmpty()) { val last = dist.ambList.run { this[lastIndex] } if (last.valuesLeft.size == 1) { dist.ambList.removeAt(dist.ambList.lastIndex) last.apply { (cont as Continuation<Any?>).resume(valuesLeft[0]) } } else { val value = last.valuesLeft.removeAt(last.valuesLeft.lastIndex) (clone(last.cont) as Continuation<Any?>).resume(value) } } if (toThrow != null) { throw toThrow!! } else if (result != null) { return result!! } else { throw AmbException() } } val UNSAFE = Class.forName("sun.misc.Unsafe") .getDeclaredField("theUnsafe") .apply { isAccessible = true } .get(null) as sun.misc.Unsafe @Suppress("UNCHECKED_CAST") fun <T: Any> clone(obj: T): T { val clazz = obj::class.java val copy = UNSAFE.allocateInstance(clazz) as T copyDeclaredFields(obj, copy, clazz) return copy } tailrec fun <T> copyDeclaredFields(obj: T, copy: T, clazz: Class<out T>) { for (field in clazz.declaredFields) { field.isAccessible = true val v = field.get(obj) field.set(copy, if (v === obj) copy else v) } val superclass = clazz.superclass if (superclass != null) copyDeclaredFields(obj, copy, superclass) }
Anagrams/Deranged anagrams
Kotlin
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}}
// version 1.0.6 import java.io.BufferedReader import java.io.InputStreamReader import java.net.URL fun isDeranged(s1: String, s2: String): Boolean { return (0 until s1.length).none { s1[it] == s2[it] } } fun main(args: Array<String>) { val url = URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt") val isr = InputStreamReader(url.openStream()) val reader = BufferedReader(isr) val anagrams = mutableMapOf<String, MutableList<String>>() var count = 0 var word = reader.readLine() while (word != null) { val chars = word.toCharArray() chars.sort() val key = chars.joinToString("") if (!anagrams.containsKey(key)) { anagrams.put(key, mutableListOf<String>()) anagrams[key]!!.add(word) } else { val deranged = anagrams[key]!!.any { isDeranged(it, word) } if (deranged) { anagrams[key]!!.add(word) count = Math.max(count, word.length) } } word = reader.readLine() } reader.close() anagrams.values .filter { it.size > 1 && it[0].length == count } .forEach { println(it) } }
Angle difference between two bearings
Kotlin
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
// version 1.1.2 class Angle(d: Double) { val value = when { d in -180.0 .. 180.0 -> d d > 180.0 -> (d - 180.0) % 360.0 - 180.0 else -> (d + 180.0) % 360.0 + 180.0 } operator fun minus(other: Angle) = Angle(this.value - other.value) } fun main(args: Array<String>) { val anglePairs = arrayOf( 20.0 to 45.0, -45.0 to 45.0, -85.0 to 90.0, -95.0 to 90.0, -45.0 to 125.0, -45.0 to 145.0, 29.4803 to -88.6381, -78.3251 to -159.036, -70099.74233810938 to 29840.67437876723, -165313.6666297357 to 33693.9894517456, 1174.8380510598456 to -154146.66490124757, 60175.77306795546 to 42213.07192354373 ) println(" b1 b2 diff") val f = "% 12.4f % 12.4f % 12.4f" for (ap in anglePairs) { val diff = Angle(ap.second) - Angle(ap.first) println(f.format(ap.first, ap.second, diff.value)) } }
Anti-primes
Kotlin from 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]]
// Version 1.3.10 fun countDivisors(n: Int): Int { if (n < 2) return 1; var count = 2 // 1 and n for (i in 2..n / 2) { if (n % i == 0) count++ } return count; } fun main(args: Array<String>) { println("The first 20 anti-primes are:") var maxDiv = 0 var count = 0 var n = 1 while (count < 20) { val d = countDivisors(n) if (d > maxDiv) { print("$n ") maxDiv = d count++ } n++ } println() }
Apply a digital filter (direct form II transposed)
Kotlin from C++
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]
// version 1.1.3 fun filter(a: DoubleArray, b: DoubleArray, signal: DoubleArray): DoubleArray { val result = DoubleArray(signal.size) for (i in 0 until signal.size) { var tmp = 0.0 for (j in 0 until b.size) { if (i - j < 0) continue tmp += b[j] * signal[i - j] } for (j in 1 until a.size) { if (i - j < 0) continue tmp -= a[j] * result[i - j] } tmp /= a[0] result[i] = tmp } return result } fun main(args: Array<String>) { val a = doubleArrayOf(1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17) val b = doubleArrayOf(0.16666667, 0.5, 0.5, 0.16666667) val signal = doubleArrayOf( -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 ) val result = filter(a, b, signal) for (i in 0 until result.size) { print("% .8f".format(result[i])) print(if ((i + 1) % 5 != 0) ", " else "\n") } }
Approximate equality
Kotlin from C#
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__
import kotlin.math.abs import kotlin.math.sqrt fun approxEquals(value: Double, other: Double, epsilon: Double): Boolean { return abs(value - other) < epsilon } fun test(a: Double, b: Double) { val epsilon = 1e-18 println("$a, $b => ${approxEquals(a, b, epsilon)}") } fun main() { test(100000000000000.01, 100000000000000.011) test(100.01, 100.011) test(10000000000000.001 / 10000.0, 1000000000.0000001000) test(0.001, 0.0010000001) test(0.000000000000000000000101, 0.0) test(sqrt(2.0) * sqrt(2.0), 2.0) test(-sqrt(2.0) * sqrt(2.0), -2.0) test(3.14159265358979323846, 3.14159265358979324) }
Archimedean spiral
Kotlin from Java
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: :\, r=a+b\theta with real numbers ''a'' and ''b''. ;Task Draw an Archimedean spiral.
// version 1.1.0 import java.awt.* import javax.swing.* class ArchimedeanSpiral : JPanel() { init { preferredSize = Dimension(640, 640) background = Color.white } private fun drawGrid(g: Graphics2D) { g.color = Color(0xEEEEEE) g.stroke = BasicStroke(2f) val angle = Math.toRadians(45.0) val w = width val center = w / 2 val margin = 10 val numRings = 8 val spacing = (w - 2 * margin) / (numRings * 2) for (i in 0 until numRings) { val pos = margin + i * spacing val size = w - (2 * margin + i * 2 * spacing) g.drawOval(pos, pos, size, size) val ia = i * angle val x2 = center + (Math.cos(ia) * (w - 2 * margin) / 2).toInt() val y2 = center - (Math.sin(ia) * (w - 2 * margin) / 2).toInt() g.drawLine(center, center, x2, y2) } } private fun drawSpiral(g: Graphics2D) { g.stroke = BasicStroke(2f) g.color = Color.magenta val degrees = Math.toRadians(0.1) val center = width / 2 val end = 360 * 2 * 10 * degrees val a = 0.0 val b = 20.0 val c = 1.0 var theta = 0.0 while (theta < end) { val r = a + b * Math.pow(theta, 1.0 / c) val x = r * Math.cos(theta) val y = r * Math.sin(theta) plot(g, (center + x).toInt(), (center - y).toInt()) theta += degrees } } private fun plot(g: Graphics2D, x: Int, y: Int) { g.drawOval(x, y, 1, 1) } override fun paintComponent(gg: Graphics) { super.paintComponent(gg) val g = gg as Graphics2D g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) drawGrid(g) drawSpiral(g) } } fun main(args: Array<String>) { SwingUtilities.invokeLater { val f = JFrame() f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE f.title = "Archimedean Spiral" f.isResizable = false f.add(ArchimedeanSpiral(), BorderLayout.CENTER) f.pack() f.setLocationRelativeTo(null) f.isVisible = true } }
Arena storage pool
Kotlin
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.
// Kotlin Native v0.5 import kotlinx.cinterop.* fun main(args: Array<String>) { memScoped { val intVar1 = alloc<IntVar>() intVar1.value = 1 val intVar2 = alloc<IntVar>() intVar2.value = 2 println("${intVar1.value} + ${intVar2.value} = ${intVar1.value + intVar2.value}") } // native memory used by intVar1 & intVar2 is automatically freed when memScoped block ends }
Arithmetic-geometric mean
Kotlin
{{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
// version 1.0.5-2 fun agm(a: Double, g: Double): Double { var aa = a // mutable 'a' var gg = g // mutable 'g' var ta: Double // temporary variable to hold next iteration of 'aa' val epsilon = 1.0e-16 // tolerance for checking if limit has been reached while (true) { ta = (aa + gg) / 2.0 if (Math.abs(aa - ta) <= epsilon) return ta gg = Math.sqrt(aa * gg) aa = ta } } fun main(args: Array<String>) { println(agm(1.0, 1.0 / Math.sqrt(2.0))) }
Arithmetic-geometric mean/Calculate Pi
Kotlin
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.
import java.math.BigDecimal import java.math.MathContext val con1024 = MathContext(1024) val bigTwo = BigDecimal(2) val bigFour = bigTwo * bigTwo fun bigSqrt(bd: BigDecimal, con: MathContext): BigDecimal { var x0 = BigDecimal.ZERO var x1 = BigDecimal.valueOf(Math.sqrt(bd.toDouble())) while (x0 != x1) { x0 = x1 x1 = bd.divide(x0, con).add(x0).divide(bigTwo, con) } return x1 } fun main(args: Array<String>) { var a = BigDecimal.ONE var g = a.divide(bigSqrt(bigTwo, con1024), con1024) var t : BigDecimal var sum = BigDecimal.ZERO var pow = bigTwo while (a != g) { t = (a + g).divide(bigTwo, con1024) g = bigSqrt(a * g, con1024) a = t pow *= bigTwo sum += (a * a - g * g) * pow } val pi = (bigFour * a * a).divide(BigDecimal.ONE - sum, con1024) println(pi) }
Arithmetic evaluation
Kotlin from JavaScript
Create a program which parses and evaluates arithmetic expressions. ;Requirements: * An abstract-syntax tree (AST) for the expression must be created from parsing the input. * The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) * The expression will be a string or list of symbols like "(1+3)*7". * The four symbols + - * / must be supported as binary operators with conventional precedence rules. * Precedence-control parentheses must also be supported. ;Note: For those who don't remember, mathematical precedence is as follows: * Parentheses * Multiplication/Division (left to right) * Addition/Subtraction (left to right) ;C.f: * [[24 game Player]]. * [[Parsing/RPN calculator algorithm]]. * [[Parsing/RPN to infix conversion]].
// version 1.2.10 /* if string is empty, returns zero */ fun String.toDoubleOrZero() = this.toDoubleOrNull() ?: 0.0 fun multiply(s: String): String { val b = s.split('*').map { it.toDoubleOrZero() } return (b[0] * b[1]).toString() } fun divide(s: String): String { val b = s.split('/').map { it.toDoubleOrZero() } return (b[0] / b[1]).toString() } fun add(s: String): String { var t = s.replace(Regex("""^\+"""), "").replace(Regex("""\++"""), "+") val b = t.split('+').map { it.toDoubleOrZero() } return (b[0] + b[1]).toString() } fun subtract(s: String): String { var t = s.replace(Regex("""(\+-|-\+)"""), "-") if ("--" in t) return add(t.replace("--", "+")) val b = t.split('-').map { it.toDoubleOrZero() } return (if (b.size == 3) -b[1] - b[2] else b[0] - b[1]).toString() } fun evalExp(s: String): String { var t = s.replace(Regex("""[()]"""), "") val reMD = Regex("""\d+\.?\d*\s*[*/]\s*[+-]?\d+\.?\d*""") val reM = Regex( """\*""") val reAS = Regex("""-?\d+\.?\d*\s*[+-]\s*[+-]?\d+\.?\d*""") val reA = Regex("""\d\+""") while (true) { val match = reMD.find(t) if (match == null) break val exp = match.value val match2 = reM.find(exp) t = if (match2 != null) t.replace(exp, multiply(exp)) else t.replace(exp, divide(exp)) } while (true) { val match = reAS.find(t) if (match == null) break val exp = match.value val match2 = reA.find(exp) t = if (match2 != null) t.replace(exp, add(exp)) else t.replace(exp, subtract(exp)) } return t } fun evalArithmeticExp(s: String): Double { var t = s.replace(Regex("""\s"""), "").replace("""^\+""", "") val rePara = Regex("""\([^()]*\)""") while(true) { val match = rePara.find(t) if (match == null) break val exp = match.value t = t.replace(exp, evalExp(exp)) } return evalExp(t).toDoubleOrZero() } fun main(arsg: Array<String>) { listOf( "2+3", "2+3/4", "2*3-4", "2*(3+4)+5/6", "2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10", "2*-3--4+-0.25", "-4 - 3", "((((2))))+ 3 * 5", "1 + 2 * (3 + (4 * 5 + 6 * 7 * 8) - 9) / 10", "1 + 2*(3 - 2*(3 - 2)*((2 - 4)*5 - 22/(7 + 2*(3 - 1)) - 1)) + 1" ).forEach { println("$it = ${evalArithmeticExp(it)}") } }
Array length
Kotlin
Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'.
fun main(args: Array<String>) { println(arrayOf("apple", "orange").size) }
Associative array/Merging
Kotlin
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 |}
fun main() { val base = HashMap<String,String>() val update = HashMap<String,String>() base["name"] = "Rocket Skates" base["price"] = "12.75" base["color"] = "yellow" update["price"] = "15.25" update["color"] = "red" update["year"] = "1974" val merged = HashMap(base) merged.putAll(update) println("base: $base") println("update: $update") println("merged: $merged") }
Attractive numbers
Kotlin from 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.
// Version 1.3.21 const val MAX = 120 fun isPrime(n: Int) : Boolean { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 var d : Int = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false d += 4 } return true } fun countPrimeFactors(n: Int) = when { n == 1 -> 0 isPrime(n) -> 1 else -> { var nn = n var count = 0 var f = 2 while (true) { if (nn % f == 0) { count++ nn /= f if (nn == 1) break if (isPrime(nn)) f = nn } else if (f >= 3) { f += 2 } else { f = 3 } } count } } fun main() { println("The attractive numbers up to and including $MAX are:") var count = 0 for (i in 1..MAX) { val n = countPrimeFactors(i) if (isPrime(n)) { System.out.printf("%4d", i) if (++count % 20 == 0) println() } } println() }
Average loop length
Kotlin from 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%)
const val NMAX = 20 const val TESTS = 1000000 val rand = java.util.Random() fun avg(n: Int): Double { var sum = 0 for (t in 0 until TESTS) { val v = BooleanArray(NMAX) var x = 0 while (!v[x]) { v[x] = true sum++ x = rand.nextInt(n) } } return sum.toDouble() / TESTS } fun ana(n: Int): Double { val nn = n.toDouble() var term = 1.0 var sum = 1.0 for (i in n - 1 downTo 1) { term *= i / nn sum += term } return sum } fun main(args: Array<String>) { println(" N average analytical (error)") println("=== ========= ============ =========") for (n in 1..NMAX) { val a = avg(n) val b = ana(n) println(String.format("%3d %6.4f %10.4f (%4.2f%%)", n, a, b, Math.abs(a - b) / b * 100.0)) } }
Averages/Mean angle
Kotlin
{{Related tasks/Statistical measures}}
// version 1.0.5-2 fun meanAngle(angles: DoubleArray): Double { val sinSum = angles.sumByDouble { Math.sin(it * Math.PI / 180.0) } val cosSum = angles.sumByDouble { Math.cos(it * Math.PI / 180.0) } return Math.atan2(sinSum / angles.size, cosSum / angles.size) * 180.0 / Math.PI } fun main(args: Array<String>) { val angles1 = doubleArrayOf(350.0, 10.0) val angles2 = doubleArrayOf(90.0, 180.0, 270.0, 360.0) val angles3 = doubleArrayOf(10.0, 20.0, 30.0) val fmt = "%.2f degrees" // format results to 2 decimal places println("Mean for angles 1 is ${fmt.format(meanAngle(angles1))}") println("Mean for angles 2 is ${fmt.format(meanAngle(angles2))}") println("Mean for angles 3 is ${fmt.format(meanAngle(angles3))}") }
Averages/Pythagorean means
Kotlin
{{Related tasks/Statistical measures}}
import kotlin.math.round import kotlin.math.pow fun Collection<Double>.geometricMean() = if (isEmpty()) Double.NaN else (reduce { n1, n2 -> n1 * n2 }).pow(1.0 / size) fun Collection<Double>.harmonicMean() = if (isEmpty() || contains(0.0)) Double.NaN else size / fold(0.0) { n1, n2 -> n1 + 1.0 / n2 } fun Double.toFixed(len: Int = 6) = round(this * 10.0.pow(len)) / 10.0.pow(len) fun main() { val list = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) val a = list.average() // arithmetic mean val g = list.geometricMean() val h = list.harmonicMean() println("A = $a G = ${g.toFixed()} H = ${h.toFixed()}") println("A >= G is ${a >= g}, G >= H is ${g >= h}") require(g in h..a) }
Averages/Root mean square
Kotlin
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}}
// version 1.0.5-2 fun quadraticMean(vector: Array<Double>) : Double { val sum = vector.sumByDouble { it * it } return Math.sqrt(sum / vector.size) } fun main(args: Array<String>) { val vector = Array(10, { (it + 1).toDouble() }) print("Quadratic mean of numbers 1 to 10 is ${quadraticMean(vector)}") }
Babbage problem
Kotlin
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.
fun main(args: Array<String>) { var number = 520L var square = 520 * 520L while (true) { val last6 = square.toString().takeLast(6) if (last6 == "269696") { println("The smallest number is $number whose square is $square") return } number += 2 square = number * number } }
Balanced brackets
Kotlin from FreeBASIC
'''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
import java.util.Random fun isBalanced(s: String): Boolean { if (s.isEmpty()) return true var countLeft = 0 // number of left brackets so far unmatched for (c in s) { if (c == '[') countLeft++ else if (countLeft > 0) countLeft-- else return false } return countLeft == 0 } fun main(args: Array<String>) { println("Checking examples in task description:") val brackets = arrayOf("", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]") for (b in brackets) { print(if (b != "") b else "(empty)") println("\t " + if (isBalanced(b)) "OK" else "NOT OK") } println() println("Checking 7 random strings of brackets of length 8:") val r = Random() (1..7).forEach { var s = "" for (j in 1..8) { s += if (r.nextInt(2) == 0) '[' else ']' } println("$s " + if (isBalanced(s)) "OK" else "NOT OK") } }
Balanced ternary
Kotlin
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.
// version 1.1.3 import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigThree = BigInteger.valueOf(3L) data class BTernary(private var value: String) : Comparable<BTernary> { init { require(value.all { it in "0+-" }) value = value.trimStart('0') } constructor(v: Int) : this(BigInteger.valueOf(v.toLong())) constructor(v: BigInteger) : this("") { value = toBT(v) } private fun toBT(v: BigInteger): String { if (v < bigZero) return flip(toBT(-v)) if (v == bigZero) return "" val rem = mod3(v) return when (rem) { bigZero -> toBT(v / bigThree) + "0" bigOne -> toBT(v / bigThree) + "+" else -> toBT((v + bigOne) / bigThree) + "-" } } private fun flip(s: String): String { val sb = StringBuilder() for (c in s) { sb.append(when (c) { '+' -> "-" '-' -> "+" else -> "0" }) } return sb.toString() } private fun mod3(v: BigInteger): BigInteger { if (v > bigZero) return v % bigThree return ((v % bigThree) + bigThree) % bigThree } fun toBigInteger(): BigInteger { val len = value.length var sum = bigZero var pow = bigOne for (i in 0 until len) { val c = value[len - i - 1] val dig = when (c) { '+' -> bigOne '-' -> -bigOne else -> bigZero } if (dig != bigZero) sum += dig * pow pow *= bigThree } return sum } private fun addDigits(a: Char, b: Char, carry: Char): String { val sum1 = addDigits(a, b) val sum2 = addDigits(sum1.last(), carry) return when { sum1.length == 1 -> sum2 sum2.length == 1 -> sum1.take(1) + sum2 else -> sum1.take(1) } } private fun addDigits(a: Char, b: Char): String = when { a == '0' -> b.toString() b == '0' -> a.toString() a == '+' -> if (b == '+') "+-" else "0" else -> if (b == '+') "0" else "-+" } operator fun plus(other: BTernary): BTernary { var a = this.value var b = other.value val longer = if (a.length > b.length) a else b var shorter = if (a.length > b.length) b else a while (shorter.length < longer.length) shorter = "0" + shorter a = longer b = shorter var carry = '0' var sum = "" for (i in 0 until a.length) { val place = a.length - i - 1 val digisum = addDigits(a[place], b[place], carry) carry = if (digisum.length != 1) digisum[0] else '0' sum = digisum.takeLast(1) + sum } sum = carry.toString() + sum return BTernary(sum) } operator fun unaryMinus() = BTernary(flip(this.value)) operator fun minus(other: BTernary) = this + (-other) operator fun times(other: BTernary): BTernary { var that = other val one = BTernary(1) val zero = BTernary(0) var mul = zero var flipFlag = false if (that < zero) { that = -that flipFlag = true } var i = one while (i <= that) { mul += this i += one } if (flipFlag) mul = -mul return mul } override operator fun compareTo(other: BTernary) = this.toBigInteger().compareTo(other.toBigInteger()) override fun toString() = value } fun main(args: Array<String>) { val a = BTernary("+-0++0+") val b = BTernary(-436) val c = BTernary("+-++-") println("a = ${a.toBigInteger()}") println("b = ${b.toBigInteger()}") println("c = ${c.toBigInteger()}") val bResult = a * (b - c) val iResult = bResult.toBigInteger() println("a * (b - c) = $bResult = $iResult") }
Barnsley fern
Kotlin from Java
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
// version 1.1.0 import java.awt.* import java.awt.image.BufferedImage import javax.swing.* class BarnsleyFern(private val dim: Int) : JPanel() { private val img: BufferedImage init { preferredSize = Dimension(dim, dim) background = Color.black img = BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB) createFern(dim, dim) } private fun createFern(w: Int, h: Int) { var x = 0.0 var y = 0.0 for (i in 0 until 200_000) { var tmpx: Double var tmpy: Double val r = Math.random() if (r <= 0.01) { tmpx = 0.0 tmpy = 0.16 * y } else if (r <= 0.86) { tmpx = 0.85 * x + 0.04 * y tmpy = -0.04 * x + 0.85 * y + 1.6 } else if (r <= 0.93) { tmpx = 0.2 * x - 0.26 * y tmpy = 0.23 * x + 0.22 * y + 1.6 } else { tmpx = -0.15 * x + 0.28 * y tmpy = 0.26 * x + 0.24 * y + 0.44 } x = tmpx y = tmpy img.setRGB(Math.round(w / 2.0 + x * w / 11.0).toInt(), Math.round(h - y * h / 11.0).toInt(), 0xFF32CD32.toInt()) } } override protected fun paintComponent(gg: Graphics) { super.paintComponent(gg) val g = gg as Graphics2D g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.drawImage(img, 0, 0, null) } } fun main(args: Array<String>) { SwingUtilities.invokeLater { val f = JFrame() f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE f.title = "Barnsley Fern" f.setResizable(false) f.add(BarnsleyFern(640), BorderLayout.CENTER) f.pack() f.setLocationRelativeTo(null) f.setVisible(true) } }
Base64 decode data
Kotlin from D
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.
import java.util.Base64 fun main() { val data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=" val decoder = Base64.getDecoder() val decoded = decoder.decode(data) val decodedStr = String(decoded, Charsets.UTF_8) println(decodedStr) }
Bell numbers
Kotlin from C
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'''
class BellTriangle(n: Int) { private val arr: Array<Int> init { val length = n * (n + 1) / 2 arr = Array(length) { 0 } set(1, 0, 1) for (i in 2..n) { set(i, 0, get(i - 1, i - 2)) for (j in 1 until i) { val value = get(i, j - 1) + get(i - 1, j - 1) set(i, j, value) } } } private fun index(row: Int, col: Int): Int { require(row > 0) require(col >= 0) require(col < row) return row * (row - 1) / 2 + col } operator fun get(row: Int, col: Int): Int { val i = index(row, col) return arr[i] } private operator fun set(row: Int, col: Int, value: Int) { val i = index(row, col) arr[i] = value } } fun main() { val rows = 15 val bt = BellTriangle(rows) println("First fifteen Bell numbers:") for (i in 1..rows) { println("%2d: %d".format(i, bt[i, 0])) } for (i in 1..10) { print("${bt[i, 0]}") for (j in 1 until i) { print(", ${bt[i, j]}") } println() } }
Benford's law
Kotlin
{{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}}.
import java.math.BigInteger interface NumberGenerator { val numbers: Array<BigInteger> } class Benford(ng: NumberGenerator) { override fun toString() = str private val firstDigits = IntArray(9) private val count = ng.numbers.size.toDouble() private val str: String init { for (n in ng.numbers) { firstDigits[n.toString().substring(0, 1).toInt() - 1]++ } str = with(StringBuilder()) { for (i in firstDigits.indices) { append(i + 1).append('\t').append(firstDigits[i] / count) append('\t').append(Math.log10(1 + 1.0 / (i + 1))).append('\n') } toString() } } } object FibonacciGenerator : NumberGenerator { override val numbers: Array<BigInteger> by lazy { val fib = Array<BigInteger>(1000, { BigInteger.ONE }) for (i in 2 until fib.size) fib[i] = fib[i - 2].add(fib[i - 1]) fib } } fun main(a: Array<String>) = println(Benford(FibonacciGenerator))
Best shuffle
Kotlin from Java
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]]
import java.util.Random object BestShuffle { operator fun invoke(s1: String) : String { val s2 = s1.toCharArray() s2.shuffle() for (i in s2.indices) if (s2[i] == s1[i]) for (j in s2.indices) if (s2[i] != s2[j] && s2[i] != s1[j] && s2[j] != s1[i]) { val tmp = s2[i] s2[i] = s2[j] s2[j] = tmp break } return s1 + ' ' + String(s2) + " (" + s2.count(s1) + ')' } private fun CharArray.shuffle() { val rand = Random() for (i in size - 1 downTo 1) { val r = rand.nextInt(i + 1) val tmp = this[i] this[i] = this[r] this[r] = tmp } } private fun CharArray.count(s1: String) : Int { var count = 0 for (i in indices) if (s1[i] == this[i]) count++ return count } } fun main(words: Array<String>) = words.forEach { println(BestShuffle(it)) }
Bioinformatics/base count
Kotlin
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.
fun printSequence(sequence: String, width: Int = 50) { fun <K, V> printWithLabel(k: K, v: V) { val label = k.toString().padStart(5) println("$label: $v") } println("SEQUENCE:") sequence.chunked(width).withIndex().forEach { (i, line) -> printWithLabel(i*width + line.length, line) } println("BASE:") sequence.groupingBy { it }.eachCount().forEach { (k, v) -> printWithLabel(k, v) } printWithLabel("TOTALS", sequence.length) } const val BASE_SEQUENCE = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" fun main() { printSequence(BASE_SEQUENCE) }
Bitcoin/address validation
Kotlin from Java
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.
import java.security.MessageDigest object Bitcoin { private const val ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" private fun ByteArray.contentEquals(other: ByteArray): Boolean { if (this.size != other.size) return false return (0 until this.size).none { this[it] != other[it] } } private fun decodeBase58(input: String): ByteArray? { val output = ByteArray(25) for (c in input) { var p = ALPHABET.indexOf(c) if (p == -1) return null for (j in 24 downTo 1) { p += 58 * (output[j].toInt() and 0xff) output[j] = (p % 256).toByte() p = p shr 8 } if (p != 0) return null } return output } private fun sha256(data: ByteArray, start: Int, len: Int, recursion: Int): ByteArray { if (recursion == 0) return data val md = MessageDigest.getInstance("SHA-256") md.update(data.sliceArray(start until start + len)) return sha256(md.digest(), 0, 32, recursion - 1) } fun validateAddress(address: String): Boolean { if (address.length !in 26..35) return false val decoded = decodeBase58(address) if (decoded == null) return false val hash = sha256(decoded, 0, 21, 2) return hash.sliceArray(0..3).contentEquals(decoded.sliceArray(21..24)) } } fun main(args: Array<String>) { val addresses = arrayOf( "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j", "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9", "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X", "1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", "1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", "BZbvjr", "i55j", "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!", "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz", "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz", "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9", "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I" ) for (address in addresses) println("${address.padEnd(36)} -> ${if (Bitcoin.validateAddress(address)) "valid" else "invalid"}") }
Bitwise IO
Kotlin from C
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
// version 1.2.31 import java.io.File class BitFilter(val f: File, var accu: Int = 0, var bits: Int = 0) { private val bw = f.bufferedWriter() private val br = f.bufferedReader() fun write(buf: ByteArray, start: Int, _nBits: Int, _shift: Int) { var nBits = _nBits var index = start + _shift / 8 var shift = _shift % 8 while (nBits != 0 || bits >= 8) { while (bits >= 8) { bits -= 8 bw.write(accu ushr bits) accu = accu and ((1 shl bits) - 1) } while (bits < 8 && nBits != 0) { val b = buf[index].toInt() accu = (accu shl 1) or (((128 ushr shift) and b) ushr (7 - shift)) nBits-- bits++ if (++shift == 8) { shift = 0; index++ } } } } fun read(buf: ByteArray, start: Int, _nBits: Int, _shift: Int) { var nBits = _nBits var index = start + _shift / 8 var shift = _shift % 8 while (nBits != 0) { while (bits != 0 && nBits != 0) { val mask = 128 ushr shift if ((accu and (1 shl (bits - 1))) != 0) buf[index] = (buf[index].toInt() or mask).toByte() else buf[index] = (buf[index].toInt() and mask.inv()).toByte() nBits-- bits-- if (++shift >= 8) { shift = 0; index++ } } if (nBits == 0) break accu = (accu shl 8) or br.read() bits += 8 } } fun closeWriter() { if (bits != 0) { accu = (accu shl (8 - bits)) bw.write(accu) } bw.close() accu = 0 bits = 0 } fun closeReader() { br.close() accu = 0 bits = 0 } } fun main(args: Array<String>) { val s = "abcdefghijk".toByteArray(Charsets.UTF_8) val f = File("test.bin") val bf = BitFilter(f) /* for each byte in s, write 7 bits skipping 1 */ for (i in 0 until s.size) bf.write(s, i, 7, 1) bf.closeWriter() /* read 7 bits and expand to each byte of s2 skipping 1 bit */ val s2 = ByteArray(s.size) for (i in 0 until s2.size) bf.read(s2, i, 7, 1) bf.closeReader() println(String(s2, Charsets.UTF_8)) }
Box the compass
Kotlin
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)..
// version 1.1.2 fun expand(cp: String): String { val sb = StringBuilder() for (c in cp) { sb.append(when (c) { 'N' -> "north" 'E' -> "east" 'S' -> "south" 'W' -> "west" 'b' -> " by " else -> "-" }) } return sb.toString().capitalize() } fun main(args: Array<String>) { val cp = arrayOf( "N", "NbE", "N-NE", "NEbN", "NE", "NEbE", "E-NE", "EbN", "E", "EbS", "E-SE", "SEbE", "SE", "SEbS", "S-SE", "SbE", "S", "SbW", "S-SW", "SWbS", "SW", "SWbW", "W-SW", "WbS", "W", "WbN", "W-NW", "NWbW", "NW", "NWbN", "N-NW", "NbW" ) println("Index Degrees Compass point") println("----- ------- -------------") val f = "%2d %6.2f %s" for (i in 0..32) { val index = i % 32 var heading = i * 11.25 when (i % 3) { 1 -> heading += 5.62 2 -> heading -= 5.62 } println(f.format(index + 1, heading, expand(cp[index]))) } }
Brazilian numbers
Kotlin from C#
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'''
fun sameDigits(n: Int, b: Int): Boolean { var n2 = n val f = n % b while (true) { n2 /= b if (n2 > 0) { if (n2 % b != f) { return false } } else { break } } return true } fun isBrazilian(n: Int): Boolean { if (n < 7) return false if (n % 2 == 0) return true for (b in 2 until n - 1) { if (sameDigits(n, b)) { return true } } return false } fun isPrime(n: Int): Boolean { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 var d = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false d += 4 } return true } fun main() { val bigLim = 99999 val limit = 20 for (kind in ",odd ,prime".split(',')) { var quiet = false println("First $limit ${kind}Brazilian numbers:") var c = 0 var n = 7 while (c < bigLim) { if (isBrazilian(n)) { if (!quiet) print("%,d ".format(n)) if (++c == limit) { print("\n\n") quiet = true } } if (quiet && kind != "") continue when (kind) { "" -> n++ "odd " -> n += 2 "prime" -> { while (true) { n += 2 if (isPrime(n)) break } } } } if (kind == "") println("The %,dth Brazilian number is: %,d".format(bigLim + 1, n)) } }
Break OO privacy
Kotlin
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.
import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.jvm.isAccessible class ToBeBroken { @Suppress("unused") private val secret: Int = 42 } fun main(args: Array<String>) { val tbb = ToBeBroken() val props = ToBeBroken::class.declaredMemberProperties for (prop in props) { prop.isAccessible = true // make private properties accessible println("${prop.name} -> ${prop.get(tbb)}") } }
Burrows–Wheeler transform
Kotlin 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
// Version 1.2.60 const val STX = "\u0002" const val ETX = "\u0003" fun bwt(s: String): String { if (s.contains(STX) || s.contains(ETX)) { throw RuntimeException("String can't contain STX or ETX") } val ss = STX + s + ETX val table = Array<String>(ss.length) { ss.substring(it) + ss.substring(0, it) } table.sort() return String(table.map { it[it.lastIndex] }.toCharArray()) } fun ibwt(r: String): String { val len = r.length val table = Array<String>(len) { "" } repeat(len) { for (i in 0 until len) { table[i] = r[i].toString() + table[i] } table.sort() } for (row in table) { if (row.endsWith(ETX)) { return row.substring(1, len - 1) } } return "" } fun makePrintable(s: String): String { // substitute ^ for STX and | for ETX to print results return s.replace(STX, "^").replace(ETX, "|") } fun main(args: Array<String>) { val tests = listOf( "banana", "appellee", "dogwood", "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", "\u0002ABC\u0003" ) for (test in tests) { println(makePrintable(test)) print(" --> ") var t = "" try { t = bwt(test) println(makePrintable(t)) } catch (ex: RuntimeException) { println("ERROR: " + ex.message) } val r = ibwt(t) println(" --> $r\n") } }
CSV data manipulation
Kotlin
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.
// version 1.1.3 import java.io.File fun main(args: Array<String>) { val lines = File("example.csv").readLines().toMutableList() lines[0] += ",SUM" for (i in 1 until lines.size) { lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } } val text = lines.joinToString("\n") File("example2.csv").writeText(text) // write to new file println(text) // print to console }
CSV to HTML translation
Kotlin
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).
// version 1.1.3 val csv = "Character,Speech\n" + "The multitude,The messiah! Show us the messiah!\n" + "Brians mother,<angry>Now you listen here! He's not the messiah; " + "he's a very naughty boy! Now go away!</angry>\n" + "The multitude,Who are you?\n" + "Brians mother,I'm his mother; that's who!\n" + "The multitude,Behold his mother! Behold his mother!" fun main(args: Array<String>) { val i = " " // indent val sb = StringBuilder("<table>\n$i<tr>\n$i$i<td>") for (c in csv) { sb.append( when (c) { '\n' -> "</td>\n$i</tr>\n$i<tr>\n$i$i<td>" ',' -> "</td>\n$i$i<td>" '&' -> "&amp;" '\'' -> "&apos;" '<' -> "&lt;" '>' -> "&gt;" else -> c.toString() }) } sb.append("</td>\n$i</tr>\n</table>") println(sb.toString()) println() // now using first row as a table header sb.setLength(0) sb.append("<table>\n$i<thead>\n$i$i<tr>\n$i$i$i<td>") val hLength = csv.indexOf('\n') + 1 // find length of first row including CR for (c in csv.take(hLength)) { sb.append( when (c) { '\n' -> "</td>\n$i$i</tr>\n$i</thead>\n$i<tbody>\n$i$i<tr>\n$i$i$i<td>" ',' -> "</td>\n$i$i$i<td>" else -> c.toString() }) } for (c in csv.drop(hLength)) { sb.append( when (c) { '\n' -> "</td>\n$i$i</tr>\n$i$i<tr>\n$i$i$i<td>" ',' -> "</td>\n$i$i$i<td>" '&' -> "&amp;" '\'' -> "&apos;" '<' -> "&lt;" '>' -> "&gt;" else -> c.toString() }) } sb.append("</td>\n$i$i</tr>\n$i</tbody>\n</table>") println(sb.toString()) }
Calculating the value of e
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
// Version 1.2.40 import kotlin.math.abs const val EPSILON = 1.0e-15 fun main(args: Array<String>) { var fact = 1L var e = 2.0 var n = 2 do { val e0 = e fact *= n++ e += 1.0 / fact } while (abs(e - e0) >= EPSILON) println("e = %.15f".format(e)) }
Call a function
Kotlin
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.
fun fun1() = println("No arguments") fun fun2(i: Int) = println("One argument = $i") fun fun3(i: Int, j: Int = 0) = println("One required argument = $i, one optional argument = $j") fun fun4(vararg v: Int) = println("Variable number of arguments = ${v.asList()}") fun fun5(i: Int) = i * i fun fun6(i: Int, f: (Int) -> Int) = f(i) fun fun7(i: Int): Double = i / 2.0 fun fun8(x: String) = { y: String -> x + " " + y } fun main() { fun1() // no arguments fun2(2) // fixed number of arguments, one here fun3(3) // optional argument, default value used here fun4(4, 5, 6) // variable number of arguments fun3(j = 8, i = 7) // using named arguments, order unimportant val b = false if (b) fun1() else fun2(9) // statement context println(1 + fun6(4, ::fun5) + 3) // first class context within an expression println(fun5(5)) // obtaining return value println(kotlin.math.round(2.5)) // no distinction between built-in and user-defined functions, though former usually have a receiver fun1() // calling sub-routine which has a Unit return type by default println(fun7(11)) // calling function with a return type of Double (here explicit but can be implicit) println(fun8("Hello")("world")) // partial application isn't supported though you can do this }
Cantor set
Kotlin
Draw a Cantor set. See details at this Wikipedia webpage: Cantor set
// Version 1.2.31 const val WIDTH = 81 const val HEIGHT = 5 val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } } fun cantor(start: Int, len: Int, index: Int) { val seg = len / 3 if (seg == 0) return for (i in index until HEIGHT) { for (j in start + seg until start + seg * 2) lines[i][j] = ' ' } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) } fun main(args: Array<String>) { cantor(0, WIDTH, 1) lines.forEach { println(it) } }
Cartesian product of two or more lists
Kotlin
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}
// version 1.1.2 fun flattenList(nestList: List<Any>): List<Any> { val flatList = mutableListOf<Any>() fun flatten(list: List<Any>) { for (e in list) { if (e !is List<*>) flatList.add(e) else @Suppress("UNCHECKED_CAST") flatten(e as List<Any>) } } flatten(nestList) return flatList } operator fun List<Any>.times(other: List<Any>): List<List<Any>> { val prod = mutableListOf<List<Any>>() for (e in this) { for (f in other) { prod.add(listOf(e, f)) } } return prod } fun nAryCartesianProduct(lists: List<List<Any>>): List<List<Any>> { require(lists.size >= 2) return lists.drop(2).fold(lists[0] * lists[1]) { cp, ls -> cp * ls }.map { flattenList(it) } } fun printNAryProduct(lists: List<List<Any>>) { println("${lists.joinToString(" x ")} = ") println("[") println(nAryCartesianProduct(lists).joinToString("\n ", " ")) println("]\n") } fun main(args: Array<String>) { println("[1, 2] x [3, 4] = ${listOf(1, 2) * listOf(3, 4)}") println("[3, 4] x [1, 2] = ${listOf(3, 4) * listOf(1, 2)}") println("[1, 2] x [] = ${listOf(1, 2) * listOf()}") println("[] x [1, 2] = ${listOf<Any>() * listOf(1, 2)}") println("[1, a] x [2, b] = ${listOf(1, 'a') * listOf(2, 'b')}") println() printNAryProduct(listOf(listOf(1776, 1789), listOf(7, 12), listOf(4, 14, 23), listOf(0, 1))) printNAryProduct(listOf(listOf(1, 2, 3), listOf(30), listOf(500, 100))) printNAryProduct(listOf(listOf(1, 2, 3), listOf<Int>(), listOf(500, 100))) printNAryProduct(listOf(listOf(1, 2, 3), listOf(30), listOf('a', 'b'))) }
Casting out nines
Kotlin from D
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]]
// version 1.1.3 fun castOut(base: Int, start: Int, end: Int): List<Int> { val b = base - 1 val ran = (0 until b).filter { it % b == (it * it) % b } var x = start / b val result = mutableListOf<Int>() while (true) { for (n in ran) { val k = b * x + n if (k < start) continue if (k > end) return result result.add(k) } x++ } } fun main(args: Array<String>) { println(castOut(16, 1, 255)) println() println(castOut(10, 1, 99)) println() println(castOut(17, 1, 288)) }
Catalan numbers/Pascal's triangle
Kotlin
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]]
// version 1.1.2 import java.math.BigInteger val ONE = BigInteger.ONE fun pascal(n: Int, k: Int): BigInteger { if (n == 0 || k == 0) return ONE val num = (k + 1..n).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) } val den = (2..n - k).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) } return num / den } fun catalanFromPascal(n: Int) { for (i in 1 until n step 2) { val mi = i / 2 + 1 val catalan = pascal(i, mi) - pascal(i, mi - 2) println("${"%2d".format(mi)} : $catalan") } } fun main(args: Array<String>) { val n = 15 catalanFromPascal(n * 2) }
Catamorphism
Kotlin
''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
fun main(args: Array<String>) { val a = intArrayOf(1, 2, 3, 4, 5) println("Array : ${a.joinToString(", ")}") println("Sum : ${a.reduce { x, y -> x + y }}") println("Difference : ${a.reduce { x, y -> x - y }}") println("Product : ${a.reduce { x, y -> x * y }}") println("Minimum : ${a.reduce { x, y -> if (x < y) x else y }}") println("Maximum : ${a.reduce { x, y -> if (x > y) x else y }}") }
Chaocipher
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.
// Version 1.2.40 enum class Mode { ENCRYPT, DECRYPT } object Chao { private val lAlphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" private val rAlphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC" fun exec(text: String, mode: Mode, showSteps: Boolean = false): String { var left = lAlphabet var right = rAlphabet val eText = CharArray(text.length) val temp = CharArray(26) for (i in 0 until text.length) { if (showSteps) println("$left $right") var index: Int if (mode == Mode.ENCRYPT) { index = right.indexOf(text[i]) eText[i] = left[index] } else { index = left.indexOf(text[i]) eText[i] = right[index] } if (i == text.length - 1) break // permute left for (j in index..25) temp[j - index] = left[j] for (j in 0 until index) temp[26 - index + j] = left[j] var store = temp[1] for (j in 2..13) temp[j - 1] = temp[j] temp[13] = store left = String(temp) // permute right for (j in index..25) temp[j - index] = right[j] for (j in 0 until index) temp[26 - index + j] = right[j] store = temp[0] for (j in 1..25) temp[j - 1] = temp[j] temp[25] = store store = temp[2] for (j in 3..13) temp[j - 1] = temp[j] temp[13] = store right = String(temp) } return String(eText) } } fun main(args: Array<String>) { val plainText = "WELLDONEISBETTERTHANWELLSAID" println("The original plaintext is : $plainText") println("\nThe left and right alphabets after each permutation" + " during encryption are :\n") val cipherText = Chao.exec(plainText, Mode.ENCRYPT, true) println("\nThe ciphertext is : $cipherText") val plainText2 = Chao.exec(cipherText, Mode.DECRYPT) println("\nThe recovered plaintext is : $plainText2") }
Chaos game
Kotlin from Java
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
//Version 1.1.51 import java.awt.* import java.util.Stack import java.util.Random import javax.swing.JPanel import javax.swing.JFrame import javax.swing.Timer import javax.swing.SwingUtilities class ChaosGame : JPanel() { class ColoredPoint(x: Int, y: Int, val colorIndex: Int) : Point(x, y) val stack = Stack<ColoredPoint>() val points: List<Point> val colors = listOf(Color.red, Color.green, Color.blue) val r = Random() init { val dim = Dimension(640, 640) preferredSize = dim background = Color.white val margin = 60 val size = dim.width - 2 * margin points = listOf( Point(dim.width / 2, margin), Point(margin, size), Point(margin + size, size) ) stack.push(ColoredPoint(-1, -1, 0)) Timer(10) { if (stack.size < 50_000) { for (i in 0 until 1000) addPoint() repaint() } }.start() } private fun addPoint() { val colorIndex = r.nextInt(3) val p1 = stack.peek() val p2 = points[colorIndex] stack.add(halfwayPoint(p1, p2, colorIndex)) } fun drawPoints(g: Graphics2D) { for (cp in stack) { g.color = colors[cp.colorIndex] g.fillOval(cp.x, cp.y, 1, 1) } } fun halfwayPoint(a: Point, b: Point, idx: Int) = ColoredPoint((a.x + b.x) / 2, (a.y + b.y) / 2, idx) override fun paintComponent(gg: Graphics) { super.paintComponent(gg) val g = gg as Graphics2D g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) drawPoints(g) } } fun main(args: Array<String>) { SwingUtilities.invokeLater { val f = JFrame() with (f) { defaultCloseOperation = JFrame.EXIT_ON_CLOSE title = "Chaos Game" isResizable = false add(ChaosGame(), BorderLayout.CENTER) pack() setLocationRelativeTo(null) isVisible = true } } }
Check Machin-like formulas
Kotlin
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.
// version 1.1.3 import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE class BigRational : Comparable<BigRational> { val num: BigInteger val denom: BigInteger constructor(n: BigInteger, d: BigInteger) { require(d != bigZero) var nn = n var dd = d if (nn == bigZero) { dd = bigOne } else if (dd < bigZero) { nn = -nn dd = -dd } val g = nn.gcd(dd) if (g > bigOne) { nn /= g dd /= g } num = nn denom = dd } constructor(n: Long, d: Long) : this(BigInteger.valueOf(n), BigInteger.valueOf(d)) operator fun plus(other: BigRational) = BigRational(num * other.denom + denom * other.num, other.denom * denom) operator fun unaryMinus() = BigRational(-num, denom) operator fun minus(other: BigRational) = this + (-other) operator fun times(other: BigRational) = BigRational(this.num * other.num, this.denom * other.denom) fun inverse(): BigRational { require(num != bigZero) return BigRational(denom, num) } operator fun div(other: BigRational) = this * other.inverse() override fun compareTo(other: BigRational): Int { val diff = this - other return when { diff.num < bigZero -> -1 diff.num > bigZero -> +1 else -> 0 } } override fun equals(other: Any?): Boolean { if (other == null || other !is BigRational) return false return this.compareTo(other) == 0 } override fun toString() = if (denom == bigOne) "$num" else "$num/$denom" companion object { val ZERO = BigRational(bigZero, bigOne) val ONE = BigRational(bigOne, bigOne) } } /** represents a term of the form: c * atan(n / d) */ class Term(val c: Long, val n: Long, val d: Long) { override fun toString() = when { c == 1L -> " + " c == -1L -> " - " c < 0L -> " - ${-c}*" else -> " + $c*" } + "atan($n/$d)" } val one = BigRational.ONE fun tanSum(terms: List<Term>): BigRational { if (terms.size == 1) return tanEval(terms[0].c, BigRational(terms[0].n, terms[0].d)) val half = terms.size / 2 val a = tanSum(terms.take(half)) val b = tanSum(terms.drop(half)) return (a + b) / (one - (a * b)) } fun tanEval(c: Long, f: BigRational): BigRational { if (c == 1L) return f if (c < 0L) return -tanEval(-c, f) val ca = c / 2 val cb = c - ca val a = tanEval(ca, f) val b = tanEval(cb, f) return (a + b) / (one - (a * b)) } fun main(args: Array<String>) { val termsList = listOf( listOf(Term(1, 1, 2), Term(1, 1, 3)), listOf(Term(2, 1, 3), Term(1, 1, 7)), listOf(Term(4, 1, 5), Term(-1, 1, 239)), listOf(Term(5, 1, 7), Term(2, 3, 79)), listOf(Term(5, 29, 278), Term(7, 3, 79)), listOf(Term(1, 1, 2), Term(1, 1, 5), Term(1, 1, 8)), listOf(Term(4, 1, 5), Term(-1, 1, 70), Term(1, 1, 99)), listOf(Term(5, 1, 7), Term(4, 1, 53), Term(2, 1, 4443)), listOf(Term(6, 1, 8), Term(2, 1, 57), Term(1, 1, 239)), listOf(Term(8, 1, 10), Term(-1, 1, 239), Term(-4, 1, 515)), listOf(Term(12, 1, 18), Term(8, 1, 57), Term(-5, 1, 239)), listOf(Term(16, 1, 21), Term(3, 1, 239), Term(4, 3, 1042)), listOf(Term(22, 1, 28), Term(2, 1, 443), Term(-5, 1, 1393), Term(-10, 1, 11018)), listOf(Term(22, 1, 38), Term(17, 7, 601), Term(10, 7, 8149)), listOf(Term(44, 1, 57), Term(7, 1, 239), Term(-12, 1, 682), Term(24, 1, 12943)), listOf(Term(88, 1, 172), Term(51, 1, 239), Term(32, 1, 682), Term(44, 1, 5357), Term(68, 1, 12943)), listOf(Term(88, 1, 172), Term(51, 1, 239), Term(32, 1, 682), Term(44, 1, 5357), Term(68, 1, 12944)) ) for (terms in termsList) { val f = String.format("%-5s << 1 == tan(", tanSum(terms) == one) print(f) print(terms[0].toString().drop(3)) for (i in 1 until terms.size) print(terms[i]) println(")") } }
Cheryl's birthday
Kotlin from 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
// Version 1.2.71 val months = listOf( "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ) class Birthday(val month: Int, val day: Int) { public override fun toString() = "${months[month - 1]} $day" public fun monthUniqueIn(bds: List<Birthday>): Boolean { return bds.count { this.month == it.month } == 1 } public fun dayUniqueIn(bds: List<Birthday>): Boolean { return bds.count { this.day == it.day } == 1 } public fun monthWithUniqueDayIn(bds: List<Birthday>): Boolean { return bds.any { (this.month == it.month) && it.dayUniqueIn(bds) } } } fun main(args: Array<String>) { val choices = listOf( Birthday(5, 15), Birthday(5, 16), Birthday(5, 19), Birthday(6, 17), Birthday(6, 18), Birthday(7, 14), Birthday(7, 16), Birthday(8, 14), Birthday(8, 15), Birthday(8, 17) ) // Albert knows the month but doesn't know the day. // So the month can't be unique within the choices. var filtered = choices.filterNot { it.monthUniqueIn(choices) } // Albert also knows that Bernard doesn't know the answer. // So the month can't have a unique day. filtered = filtered.filterNot { it.monthWithUniqueDayIn(filtered) } // Bernard now knows the answer. // So the day must be unique within the remaining choices. filtered = filtered.filter { it.dayUniqueIn(filtered) } // Albert now knows the answer too. // So the month must be unique within the remaining choices. filtered = filtered.filter { it.monthUniqueIn(filtered) } if (filtered.size == 1) println("Cheryl's birthday is ${filtered[0]}") else println("Something went wrong!") }
Chinese remainder theorem
Kotlin from C
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}.
// version 1.1.2 /* returns x where (a * x) % b == 1 */ fun multInv(a: Int, b: Int): Int { if (b == 1) return 1 var aa = a var bb = b var x0 = 0 var x1 = 1 while (aa > 1) { val q = aa / bb var t = bb bb = aa % bb aa = t t = x0 x0 = x1 - q * x0 x1 = t } if (x1 < 0) x1 += b return x1 } fun chineseRemainder(n: IntArray, a: IntArray): Int { val prod = n.fold(1) { acc, i -> acc * i } var sum = 0 for (i in 0 until n.size) { val p = prod / n[i] sum += a[i] * multInv(p, n[i]) * p } return sum % prod } fun main(args: Array<String>) { val n = intArrayOf(3, 5, 7) val a = intArrayOf(2, 3, 2) println(chineseRemainder(n, a)) }
Chinese zodiac
Kotlin
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).
// version 1.1.2 class ChineseZodiac(val year: Int) { val stem : Char val branch : Char val sName : String val bName : String val element: String val animal : String val aspect : String val cycle : Int private companion object { val animals = listOf("Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig") val aspects = listOf("Yang","Yin") val elements = listOf("Wood", "Fire", "Earth", "Metal", "Water") val stems = listOf('甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸') val branches = listOf('子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥') val sNames = listOf("jiă", "yĭ", "bĭng", "dīng", "wù", "jĭ", "gēng", "xīn", "rén", "gŭi") val bNames = listOf("zĭ", "chŏu", "yín", "măo", "chén", "sì", "wŭ", "wèi", "shēn", "yŏu", "xū", "hài") val fmt = "%d %c%c %-9s %-7s %-7s %-6s %02d/60" } init { val y = year - 4 val s = y % 10 val b = y % 12 stem = stems[s] branch = branches[b] sName = sNames[s] bName = bNames[b] element = elements[s / 2] animal = animals[b] aspect = aspects[s % 2] cycle = y % 60 + 1 } override fun toString() = fmt.format(year, stem, branch, sName + "-" + bName, element, animal, aspect, cycle) } fun main(args: Array<String>) { val years = intArrayOf(1935, 1938, 1968, 1972, 1976, 1984, 2017) println("Year Chinese Pinyin Element Animal Aspect Cycle") println("---- ------- --------- ------- ------- ------ -----") for (year in years) println(ChineseZodiac(year)) }
Circles of given radius through two points
Kotlin
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
// version 1.1.51 typealias IAE = IllegalArgumentException class Point(val x: Double, val y: Double) { fun distanceFrom(other: Point): Double { val dx = x - other.x val dy = y - other.y return Math.sqrt(dx * dx + dy * dy ) } override fun equals(other: Any?): Boolean { if (other == null || other !is Point) return false return (x == other.x && y == other.y) } override fun toString() = "(%.4f, %.4f)".format(x, y) } fun findCircles(p1: Point, p2: Point, r: Double): Pair<Point, Point> { if (r < 0.0) throw IAE("the radius can't be negative") if (r == 0.0 && p1 != p2) throw IAE("no circles can ever be drawn") if (r == 0.0) return p1 to p1 if (p1 == p2) throw IAE("an infinite number of circles can be drawn") val distance = p1.distanceFrom(p2) val diameter = 2.0 * r if (distance > diameter) throw IAE("the points are too far apart to draw a circle") val center = Point((p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0) if (distance == diameter) return center to center val mirrorDistance = Math.sqrt(r * r - distance * distance / 4.0) val dx = (p2.x - p1.x) * mirrorDistance / distance val dy = (p2.y - p1.y) * mirrorDistance / distance return Point(center.x - dy, center.y + dx) to Point(center.x + dy, center.y - dx) } fun main(args: Array<String>) { val p = arrayOf( Point(0.1234, 0.9876), Point(0.8765, 0.2345), Point(0.0000, 2.0000), Point(0.0000, 0.0000) ) val points = arrayOf( p[0] to p[1], p[2] to p[3], p[0] to p[0], p[0] to p[1], p[0] to p[0] ) val radii = doubleArrayOf(2.0, 1.0, 2.0, 0.5, 0.0) for (i in 0..4) { try { val (p1, p2) = points[i] val r = radii[i] println("For points $p1 and $p2 with radius $r") val (c1, c2) = findCircles(p1, p2, r) if (c1 == c2) println("there is just one circle with center at $c1") else println("there are two circles with centers at $c1 and $c2") } catch(ex: IllegalArgumentException) { println(ex.message) } println() } }
Cistercian numerals
Kotlin from C++
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'''
import java.io.StringWriter class Cistercian() { constructor(number: Int) : this() { draw(number) } private val size = 15 private var canvas = Array(size) { Array(size) { ' ' } } init { initN() } private fun initN() { for (row in canvas) { row.fill(' ') row[5] = 'x' } } private fun horizontal(c1: Int, c2: Int, r: Int) { for (c in c1..c2) { canvas[r][c] = 'x' } } private fun vertical(r1: Int, r2: Int, c: Int) { for (r in r1..r2) { canvas[r][c] = 'x' } } private fun diagd(c1: Int, c2: Int, r: Int) { for (c in c1..c2) { canvas[r + c - c1][c] = 'x' } } private fun diagu(c1: Int, c2: Int, r: Int) { for (c in c1..c2) { canvas[r - c + c1][c] = 'x' } } private fun drawPart(v: Int) { when (v) { 1 -> { horizontal(6, 10, 0) } 2 -> { horizontal(6, 10, 4) } 3 -> { diagd(6, 10, 0) } 4 -> { diagu(6, 10, 4) } 5 -> { drawPart(1) drawPart(4) } 6 -> { vertical(0, 4, 10) } 7 -> { drawPart(1) drawPart(6) } 8 -> { drawPart(2) drawPart(6) } 9 -> { drawPart(1) drawPart(8) } 10 -> { horizontal(0, 4, 0) } 20 -> { horizontal(0, 4, 4) } 30 -> { diagu(0, 4, 4) } 40 -> { diagd(0, 4, 0) } 50 -> { drawPart(10) drawPart(40) } 60 -> { vertical(0, 4, 0) } 70 -> { drawPart(10) drawPart(60) } 80 -> { drawPart(20) drawPart(60) } 90 -> { drawPart(10) drawPart(80) } 100 -> { horizontal(6, 10, 14) } 200 -> { horizontal(6, 10, 10) } 300 -> { diagu(6, 10, 14) } 400 -> { diagd(6, 10, 10) } 500 -> { drawPart(100) drawPart(400) } 600 -> { vertical(10, 14, 10) } 700 -> { drawPart(100) drawPart(600) } 800 -> { drawPart(200) drawPart(600) } 900 -> { drawPart(100) drawPart(800) } 1000 -> { horizontal(0, 4, 14) } 2000 -> { horizontal(0, 4, 10) } 3000 -> { diagd(0, 4, 10) } 4000 -> { diagu(0, 4, 14) } 5000 -> { drawPart(1000) drawPart(4000) } 6000 -> { vertical(10, 14, 0) } 7000 -> { drawPart(1000) drawPart(6000) } 8000 -> { drawPart(2000) drawPart(6000) } 9000 -> { drawPart(1000) drawPart(8000) } } } private fun draw(v: Int) { var v2 = v val thousands = v2 / 1000 v2 %= 1000 val hundreds = v2 / 100 v2 %= 100 val tens = v2 / 10 val ones = v % 10 if (thousands > 0) { drawPart(1000 * thousands) } if (hundreds > 0) { drawPart(100 * hundreds) } if (tens > 0) { drawPart(10 * tens) } if (ones > 0) { drawPart(ones) } } override fun toString(): String { val sw = StringWriter() for (row in canvas) { for (cell in row) { sw.append(cell) } sw.appendLine() } return sw.toString() } } fun main() { for (number in arrayOf(0, 1, 20, 300, 4000, 5555, 6789, 9999)) { println("$number:") val c = Cistercian(number) println(c) } }
Closures/Value capture
Kotlin
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]]
// version 1.0.6 fun main(args: Array<String>) { // create an array of 10 anonymous functions which return the square of their index val funcs = Array(10){ fun(): Int = it * it } // call all but the last (0 .. 8).forEach { println(funcs[it]()) } }
Colour bars/Display
Kotlin from Java
Display a series of vertical color bars across the width of the display. The color bars should either use: :::* the system palette, or :::* the sequence of colors: ::::::* black ::::::* red ::::::* green ::::::* blue ::::::* magenta ::::::* cyan ::::::* yellow ::::::* white
import java.awt.Color import java.awt.Graphics import javax.swing.JFrame class ColorFrame(width: Int, height: Int): JFrame() { init { defaultCloseOperation = EXIT_ON_CLOSE setSize(width, height) isVisible = true } override fun paint(g: Graphics) { val colors = listOf(Color.black, Color.red, Color.green, Color.blue, Color.pink, Color.cyan, Color.yellow, Color.white) val size = colors.size for (i in 0 until size) { g.color = colors[i] g.fillRect(width / size * i, 0, width / size, height) } } } fun main(args: Array<String>) { ColorFrame(400, 400) }
Comma quibbling
Kotlin
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.
// version 1.0.6 fun commaQuibble(s: String): String { val t = s.trim('[', ']').replace(" ", "").replace("\"", "") val words = t.split(',') val sb = StringBuilder("{") for (i in 0 until words.size) { sb.append(when (i) { 0 -> "" words.lastIndex -> " and " else -> ", " }) sb.append(words[i]) } return sb.append("}").toString() } fun main(args: Array<String>) { val inputs = arrayOf( """[]""", """["ABC"]""", """["ABC", "DEF"]""", """["ABC", "DEF", "G", "H"]""" ) for (input in inputs) println("${input.padEnd(24)} -> ${commaQuibble(input)}") }
Command-line arguments
Kotlin from Java
{{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"
fun main(args: Array<String>) { println("There are " + args.size + " arguments given.") args.forEachIndexed { i, a -> println("The argument #${i+1} is $a and is at index $i") } }
Compare a list of strings
Kotlin
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.
// version 1.0.6 fun areEqual(strings: Array<String>): Boolean { if (strings.size < 2) return true return (1 until strings.size).all { strings[it] == strings[it - 1] } } fun areAscending(strings: Array<String>): Boolean { if (strings.size < 2) return true return (1 until strings.size).all { strings[it] > strings[it - 1] } } // The strings are given in the command line arguments fun main(args: Array<String>) { println("The strings are : ${args.joinToString()}") if (areEqual(args)) println("They are all equal") else if (areAscending(args)) println("They are in strictly ascending order") else println("They are neither equal nor in ascending order") }
Compile-time calculation
Kotlin
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.
// version 1.0.6 const val TEN_FACTORIAL = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 fun main(args: Array<String>) { println("10! = $TEN_FACTORIAL") }
Compiler/lexical analyzer
kotlin from Java
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
// Input: command line argument of file to process or console input. A two or // three character console input of digits followed by a new line will be // checked for an integer between zero and twenty-five to select a fixed test // case to run. Any other console input will be parsed. // Code based on the Java version found here: // https://rosettacode.org/mw/index.php?title=Compiler/lexical_analyzer&action=edit&section=22 // Class to halt the parsing with an exception. class ParsingFailed(message: String): Exception(message) // Enumerate class of tokens supported by this scanner. enum class TokenType { Tk_End_of_input, Op_multiply, Op_divide, Op_mod, Op_add, Op_subtract, Op_negate, Op_not, Op_less, Op_lessequal, Op_greater, Op_greaterequal, Op_equal, Op_notequal, Op_assign, Op_and, Op_or, Kw_if, Kw_else, Kw_while, Kw_print, Kw_putc, Sy_LeftParen, Sy_RightParen, Sy_LeftBrace, Sy_RightBrace, Sy_Semicolon, Sy_Comma, Tk_Identifier, Tk_Integer, Tk_String; override fun toString() = listOf("End_of_input", "Op_multiply", "Op_divide", "Op_mod", "Op_add", "Op_subtract", "Op_negate", "Op_not", "Op_less", "Op_lessequal", "Op_greater", "Op_greaterequal", "Op_equal", "Op_notequal", "Op_assign", "Op_and", "Op_or", "Keyword_if", "Keyword_else", "Keyword_while", "Keyword_print", "Keyword_putc", "LeftParen", "RightParen", "LeftBrace", "RightBrace", "Semicolon", "Comma", "Identifier", "Integer", "String")[this.ordinal] } // TokenType // Data class of tokens returned by the scanner. data class Token(val token: TokenType, val value: String, val line: Int, val pos: Int) { // Overridden method to display the token. override fun toString() = "%5d %5d %-15s %s".format(line, pos, this.token, when (this.token) { TokenType.Tk_Integer, TokenType.Tk_Identifier -> " %s".format(this.value) TokenType.Tk_String -> this.value.toList().joinToString("", " \"", "\"") { when (it) { '\t' -> "\\t" '\n' -> "\\n" '\u000b' -> "\\v" '\u000c' -> "\\f" '\r' -> "\\r" '"' -> "\\\"" '\\' -> "\\" in ' '..'~' -> "$it" else -> "\\u%04x".format(it.code) } } else -> "" } ) } // Token // Function to display an error message and halt the scanner. fun error(line: Int, pos: Int, msg: String): Nothing = throw ParsingFailed("(%d, %d) %s\n".format(line, pos, msg)) // Class to process the source into tokens with properties of the // source string, the line number, the column position, the index // within the source string, the current character being processed, // and map of the keyword strings to the corresponding token type. class Lexer(private val s: String) { private var line = 1 private var pos = 1 private var position = 0 private var chr = if (s.isEmpty()) ' ' else s[0] private val keywords = mapOf<String, TokenType>( "if" to TokenType.Kw_if, "else" to TokenType.Kw_else, "print" to TokenType.Kw_print, "putc" to TokenType.Kw_putc, "while" to TokenType.Kw_while) // Method to retrive the next character from the source. Use null after // the end of our source. private fun getNextChar() = if (++this.position >= this.s.length) { this.pos++ this.chr = '\u0000' this.chr } else { this.pos++ this.chr = this.s[this.position] when (this.chr) { '\n' -> { this.line++ this.pos = 0 } // line '\t' -> while (this.pos%8 != 1) this.pos++ } // when this.chr } // if // Method to return the division token, skip the comment, or handle the // error. private fun div_or_comment(line: Int, pos: Int): Token = if (getNextChar() != '*') Token(TokenType.Op_divide, "", line, pos); else { getNextChar() // Skip comment start outer@ while (true) when (this.chr) { '\u0000' -> error(line, pos, "Lexer: EOF in comment"); '*' -> if (getNextChar() == '/') { getNextChar() // Skip comment end break@outer } // if else -> getNextChar() } // when getToken() } // if // Method to verify a character literal. Return the token or handle the // error. private fun char_lit(line: Int, pos: Int): Token { var c = getNextChar() // skip opening quote when (c) { '\'' -> error(line, pos, "Lexer: Empty character constant"); '\\' -> c = when (getNextChar()) { 'n' -> 10.toChar() '\\' -> '\\' '\'' -> '\'' else -> error(line, pos, "Lexer: Unknown escape sequence '\\%c'". format(this.chr)) } } // when if (getNextChar() != '\'') error(line, pos, "Lexer: Multi-character constant") getNextChar() // Skip closing quote return Token(TokenType.Tk_Integer, c.code.toString(), line, pos) } // char_lit // Method to check next character to see whether it belongs to the token // we might be in the middle of. Return the correct token or handle the // error. private fun follow(expect: Char, ifyes: TokenType, ifno: TokenType, line: Int, pos: Int): Token = when { getNextChar() == expect -> { getNextChar() Token(ifyes, "", line, pos) } // matches ifno == TokenType.Tk_End_of_input -> error(line, pos, "Lexer: %c expected: (%d) '%c'".format(expect, this.chr.code, this.chr)) else -> Token(ifno, "", line, pos) } // when // Method to verify a character string. Return the token or handle the // error. private fun string_lit(start: Char, line: Int, pos: Int): Token { var result = "" while (getNextChar() != start) when (this.chr) { '\u0000' -> error(line, pos, "Lexer: EOF while scanning string literal") '\n' -> error(line, pos, "Lexer: EOL while scanning string literal") '\\' -> when (getNextChar()) { '\\' -> result += '\\' 'n' -> result += '\n' '"' -> result += '"' else -> error(line, pos, "Lexer: Escape sequence unknown '\\%c'". format(this.chr)) } // when else -> result += this.chr } // when getNextChar() // Toss closing quote return Token(TokenType.Tk_String, result, line, pos) } // string_lit // Method to retrive an identifier or integer. Return the keyword // token, if the string matches one. Return the integer token, // if the string is all digits. Return the identifer token, if the // string is valid. Otherwise, handle the error. private fun identifier_or_integer(line: Int, pos: Int): Token { var is_number = true var text = "" while (this.chr in listOf('_')+('0'..'9')+('a'..'z')+('A'..'Z')) { text += this.chr is_number = is_number && this.chr in '0'..'9' getNextChar() } // while if (text.isEmpty()) error(line, pos, "Lexer: Unrecognized character: (%d) %c". format(this.chr.code, this.chr)) return when { text[0] in '0'..'9' -> if (!is_number) error(line, pos, "Lexer: Invalid number: %s". format(text)) else { val max = Int.MAX_VALUE.toString() if (text.length > max.length || (text.length == max.length && max < text)) error(line, pos, "Lexer: Number exceeds maximum value %s". format(text)) Token(TokenType.Tk_Integer, text, line, pos) } // if this.keywords.containsKey(text) -> Token(this.keywords[text]!!, "", line, pos) else -> Token(TokenType.Tk_Identifier, text, line, pos) } } // identifier_or_integer // Method to skip whitespace both C's and Unicode ones and retrive the next // token. private fun getToken(): Token { while (this.chr in listOf('\t', '\n', '\u000b', '\u000c', '\r', ' ') || this.chr.isWhitespace()) getNextChar() val line = this.line val pos = this.pos return when (this.chr) { '\u0000' -> Token(TokenType.Tk_End_of_input, "", line, pos) '/' -> div_or_comment(line, pos) '\'' -> char_lit(line, pos) '<' -> follow('=', TokenType.Op_lessequal, TokenType.Op_less, line, pos) '>' -> follow('=', TokenType.Op_greaterequal, TokenType.Op_greater, line, pos) '=' -> follow('=', TokenType.Op_equal, TokenType.Op_assign, line, pos) '!' -> follow('=', TokenType.Op_notequal, TokenType.Op_not, line, pos) '&' -> follow('&', TokenType.Op_and, TokenType.Tk_End_of_input, line, pos) '|' -> follow('|', TokenType.Op_or, TokenType.Tk_End_of_input, line, pos) '"' -> string_lit(this.chr, line, pos) '{' -> { getNextChar() Token(TokenType.Sy_LeftBrace, "", line, pos) } // open brace '}' -> { getNextChar() Token(TokenType.Sy_RightBrace, "", line, pos) } // close brace '(' -> { getNextChar() Token(TokenType.Sy_LeftParen, "", line, pos) } // open paren ')' -> { getNextChar() Token(TokenType.Sy_RightParen, "", line, pos) } // close paren '+' -> { getNextChar() Token(TokenType.Op_add, "", line, pos) } // plus '-' -> { getNextChar() Token(TokenType.Op_subtract, "", line, pos) } // dash '*' -> { getNextChar() Token(TokenType.Op_multiply, "", line, pos) } // asterisk '%' -> { getNextChar() Token(TokenType.Op_mod, "", line, pos) } // percent ';' -> { getNextChar() Token(TokenType.Sy_Semicolon, "", line, pos) } // semicolon ',' -> { getNextChar() Token(TokenType.Sy_Comma, "", line, pos) } // comma else -> identifier_or_integer(line, pos) } } // getToken // Method to parse and display tokens. fun printTokens() { do { val t: Token = getToken() println(t) } while (t.token != TokenType.Tk_End_of_input) } // printTokens } // Lexer // Function to test all good tests from the website and produce all of the // error messages this program supports. fun tests(number: Int) { // Function to generate test case 0 source: Hello World/Text. fun hello() { Lexer( """/* Hello world */ print("Hello, World!\n"); """).printTokens() } // hello // Function to generate test case 1 source: Phoenix Number. fun phoenix() { Lexer( """/* Show Ident and Integers */ phoenix_number = 142857; print(phoenix_number, "\n");""").printTokens() } // phoenix // Function to generate test case 2 source: All Symbols. fun symbols() { Lexer( """/* All lexical tokens - not syntactically correct, but that will have to wait until syntax analysis */ /* Print */ print /* Sub */ - /* Putc */ putc /* Lss */ < /* If */ if /* Gtr */ > /* Else */ else /* Leq */ <= /* While */ while /* Geq */ >= /* Lbrace */ { /* Eq */ == /* Rbrace */ } /* Neq */ != /* Lparen */ ( /* And */ && /* Rparen */ ) /* Or */ || /* Uminus */ - /* Semi */ ; /* Not */ ! /* Comma */ , /* Mul */ * /* Assign */ = /* Div */ / /* Integer */ 42 /* Mod */ % /* String */ "String literal" /* Add */ + /* Ident */ variable_name /* character literal */ '\n' /* character literal */ '\\' /* character literal */ ' '""").printTokens() } // symbols // Function to generate test case 3 source: Test Case 4. fun four() { Lexer( """/*** test printing, embedded \n and comments with lots of '*' ***/ print(42); print("\nHello World\nGood Bye\nok\n"); print("Print a slash n - \\n.\n");""").printTokens() } // four // Function to generate test case 4 source: Count. fun count() { Lexer( """count = 1; while (count < 10) { print("count is: ", count, "\n"); count = count + 1; }""").printTokens() } // count // Function to generate test case 5 source: 100 Doors. fun doors() { Lexer( """/* 100 Doors */ i = 1; while (i * i <= 100) { print("door ", i * i, " is open\n"); i = i + 1; }""").printTokens() } // doors // Function to generate test case 6 source: Negative Tests. fun negative() { Lexer( """a = (-1 * ((-1 * (5 * 15)) / 10)); print(a, "\n"); b = -a; print(b, "\n"); print(-b, "\n"); print(-(1), "\n");""").printTokens() } // negative // Function to generate test case 7 source: Deep. fun deep() { Lexer( """print(---------------------------------+++5, "\n"); print(((((((((3 + 2) * ((((((2))))))))))))), "\n");   if (1) { if (1) { if (1) { if (1) { if (1) { print(15, "\n"); } } } } }""").printTokens() } // deep // Function to generate test case 8 source: Greatest Common Divisor. fun gcd() { Lexer( """/* Compute the gcd of 1071, 1029: 21 */   a = 1071; b = 1029;   while (b != 0) { new_a = b; b = a % b; a = new_a; } print(a);""").printTokens() } // gcd // Function to generate test case 9 source: Factorial. fun factorial() { Lexer( """/* 12 factorial is 479001600 */   n = 12; result = 1; i = 1; while (i <= n) { result = result * i; i = i + 1; } print(result);""").printTokens() } // factorial // Function to generate test case 10 source: Fibonacci Sequence. fun fibonacci() { Lexer( """/* fibonacci of 44 is 701408733 */   n = 44; i = 1; a = 0; b = 1; while (i < n) { w = a + b; a = b; b = w; i = i + 1; } print(w, "\n");""").printTokens() } // fibonacci // Function to generate test case 11 source: FizzBuzz. fun fizzbuzz() { Lexer( """/* FizzBuzz */ i = 1; while (i <= 100) { if (!(i % 15)) print("FizzBuzz"); else if (!(i % 3)) print("Fizz"); else if (!(i % 5)) print("Buzz"); else print(i);   print("\n"); i = i + 1; }""").printTokens() } // fizzbuzz // Function to generate test case 12 source: 99 Bottles of Beer. fun bottles() { Lexer( """/* 99 bottles */ bottles = 99; while (bottles > 0) { print(bottles, " bottles of beer on the wall\n"); print(bottles, " bottles of beer\n"); print("Take one down, pass it around\n"); bottles = bottles - 1; print(bottles, " bottles of beer on the wall\n\n"); }""").printTokens() } // bottles // Function to generate test case 13 source: Primes. fun primes() { Lexer( """/* Simple prime number generator */ count = 1; n = 1; limit = 100; while (n < limit) { k=3; p=1; n=n+2; while ((k*k<=n) && (p)) { p=n/k*k!=n; k=k+2; } if (p) { print(n, " is prime\n"); count = count + 1; } } print("Total primes found: ", count, "\n");""").printTokens() } // primes // Function to generate test case 14 source: Ascii Mandelbrot. fun ascii() { Lexer( """{ /* This is an integer ascii Mandelbrot generator */ left_edge = -420; right_edge = 300; top_edge = 300; bottom_edge = -300; x_step = 7; y_step = 15; max_iter = 200; y0 = top_edge; while (y0 > bottom_edge) { x0 = left_edge; while (x0 < right_edge) { y = 0; x = 0; the_char = ' '; i = 0; while (i < max_iter) { x_x = (x * x) / 200; y_y = (y * y) / 200; if (x_x + y_y > 800 ) { the_char = '0' + i; if (i > 9) { the_char = '@'; } i = max_iter; } y = x * y / 100 + y0; x = x_x - y_y + x0; i = i + 1; } putc(the_char); x0 = x0 + x_step; } putc('\n'); y0 = y0 - y_step; } } """).printTokens() } // ascii when (number) { 0 -> hello() 1 -> phoenix() 2 -> symbols() 3 -> four() 4 -> count() 5 -> doors() 6 -> negative() 7 -> deep() 8 -> gcd() 9 -> factorial() 10 -> fibonacci() 11 -> fizzbuzz() 12 -> bottles() 13 -> primes() 14 -> ascii() 15 -> // Lexer: Empty character constant Lexer("''").printTokens() 16 -> // Lexer: Unknown escape sequence Lexer("'\\x").printTokens() 17 -> // Lexer: Multi-character constant Lexer("' ").printTokens() 18 -> // Lexer: EOF in comment Lexer("/*").printTokens() 19 -> // Lexer: EOL in string Lexer("\"\n").printTokens() 20 -> // Lexer: EOF in string Lexer("\"").printTokens() 21 -> // Lexer: Escape sequence unknown Lexer("\"\\x").printTokens() 22 -> // Lexer: Unrecognized character Lexer("~").printTokens() 23 -> // Lexer: invalid number Lexer("9a9").printTokens() 24 -> // Lexer: Number exceeds maximum value Lexer("2147483648\n9223372036854775808").printTokens() 25 -> // Lexer: Operator expected Lexer("|.").printTokens() else -> println("Invalid test number %d!".format(number)) } // when } // tests // Main function to check our source and read its data before parsing it. // With no source specified, run the test of all symbols. fun main(args: Array<String>) { try { val s = if (args.size > 0 && args[0].isNotEmpty()) // file on command line java.util.Scanner(java.io.File(args[0])) else // use the console java.util.Scanner(System.`in`) var source = "" while (s.hasNext()) source += s.nextLine()+ if (s.hasNext()) "\n" else "" if (args.size > 0 && args[0].isNotEmpty()) // file on command line Lexer(source).printTokens() else { val digits = source.filter { it in '0'..'9' } when { source.isEmpty() -> // nothing given tests(2) source.length in 1..2 && digits.length == source.length && digits.toInt() in 0..25 -> tests(digits.toInt()) else -> Lexer(source).printTokens() } // when } // if } catch(e: Throwable) { println(e.message) System.exit(1) } // try } // main
Conjugate transpose
Kotlin
Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M. ::: (M^H)_{ji} = \overline{M_{ij}} This means that row j, column i of the conjugate transpose equals the complex conjugate of row i, column j of the original matrix. In the next list, M must also be a square matrix. * A Hermitian matrix equals its own conjugate transpose: M^H = M. * A multiplication with its conjugate transpose: M^HM = MM^H. * A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix. ;Task: Given some matrix of complex numbers, find its conjugate transpose. Also determine if the matrix is a: ::* Hermitian matrix, ::* normal matrix, or ::* unitary matrix. ;See also: * MathWorld entry: conjugate transpose * MathWorld entry: Hermitian matrix * MathWorld entry: normal matrix * MathWorld entry: unitary matrix
// version 1.1.3 typealias C = Complex typealias Vector = Array<C> typealias Matrix = Array<Vector> class Complex(val real: Double, val imag: Double) { operator fun plus(other: Complex) = Complex(this.real + other.real, this.imag + other.imag) operator fun times(other: Complex) = Complex(this.real * other.real - this.imag * other.imag, this.real * other.imag + this.imag * other.real) fun conj() = Complex(this.real, -this.imag) /* tolerable equality allowing for rounding of Doubles */ infix fun teq(other: Complex) = Math.abs(this.real - other.real) <= 1e-14 && Math.abs(this.imag - other.imag) <= 1e-14 override fun toString() = "${"%.3f".format(real)} " + when { imag > 0.0 -> "+ ${"%.3f".format(imag)}i" imag == 0.0 -> "+ 0.000i" else -> "- ${"%.3f".format(-imag)}i" } } fun Matrix.conjTranspose(): Matrix { val rows = this.size val cols = this[0].size return Matrix(cols) { i -> Vector(rows) { j -> this[j][i].conj() } } } operator fun Matrix.times(other: Matrix): Matrix { val rows1 = this.size val cols1 = this[0].size val rows2 = other.size val cols2 = other[0].size require(cols1 == rows2) val result = Matrix(rows1) { Vector(cols2) { C(0.0, 0.0) } } for (i in 0 until rows1) { for (j in 0 until cols2) { for (k in 0 until rows2) { result[i][j] += this[i][k] * other[k][j] } } } return result } /* tolerable matrix equality using the same concept as for complex numbers */ infix fun Matrix.teq(other: Matrix): Boolean { if (this.size != other.size || this[0].size != other[0].size) return false for (i in 0 until this.size) { for (j in 0 until this[0].size) if (!(this[i][j] teq other[i][j])) return false } return true } fun Matrix.isHermitian() = this teq this.conjTranspose() fun Matrix.isNormal(): Boolean { val ct = this.conjTranspose() return (this * ct) teq (ct * this) } fun Matrix.isUnitary(): Boolean { val ct = this.conjTranspose() val prod = this * ct val ident = identityMatrix(prod.size) val prod2 = ct * this return (prod teq ident) && (prod2 teq ident) } fun Matrix.print() { val rows = this.size val cols = this[0].size for (i in 0 until rows) { for (j in 0 until cols) { print(this[i][j]) print(if(j < cols - 1) ", " else "\n") } } println() } fun identityMatrix(n: Int): Matrix { require(n >= 1) val ident = Matrix(n) { Vector(n) { C(0.0, 0.0) } } for (i in 0 until n) ident[i][i] = C(1.0, 0.0) return ident } fun main(args: Array<String>) { val x = Math.sqrt(2.0) / 2.0 val matrices = arrayOf( arrayOf( arrayOf(C(3.0, 0.0), C(2.0, 1.0)), arrayOf(C(2.0, -1.0), C(1.0, 0.0)) ), arrayOf( arrayOf(C(1.0, 0.0), C(1.0, 0.0), C(0.0, 0.0)), arrayOf(C(0.0, 0.0), C(1.0, 0.0), C(1.0, 0.0)), arrayOf(C(1.0, 0.0), C(0.0, 0.0), C(1.0, 0.0)) ), arrayOf( arrayOf(C(x, 0.0), C(x, 0.0), C(0.0, 0.0)), arrayOf(C(0.0, -x), C(0.0, x), C(0.0, 0.0)), arrayOf(C(0.0, 0.0), C(0.0, 0.0), C(0.0, 1.0)) ) ) for (m in matrices) { println("Matrix:") m.print() val mct = m.conjTranspose() println("Conjugate transpose:") mct.print() println("Hermitian? ${mct.isHermitian()}") println("Normal? ${mct.isNormal()}") println("Unitary? ${mct.isUnitary()}\n") } }
Continued fraction
Kotlin from D
A number may be represented as a continued fraction (see Mathworld for more information) as follows: :a_0 + \cfrac{b_1}{a_1 + \cfrac{b_2}{a_2 + \cfrac{b_3}{a_3 + \ddots}}} The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients: For the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1. :\sqrt{2} = 1 + \cfrac{1}{2 + \cfrac{1}{2 + \cfrac{1}{2 + \ddots}}} For Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1. :e = 2 + \cfrac{1}{1 + \cfrac{1}{2 + \cfrac{2}{3 + \cfrac{3}{4 + \ddots}}}} For Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2. :\pi = 3 + \cfrac{1}{6 + \cfrac{9}{6 + \cfrac{25}{6 + \ddots}}} ;See also: :* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.
// version 1.1.2 typealias Func = (Int) -> IntArray fun calc(f: Func, n: Int): Double { var temp = 0.0 for (i in n downTo 1) { val p = f(i) temp = p[1] / (p[0] + temp) } return f(0)[0] + temp } fun main(args: Array<String>) { val pList = listOf<Pair<String, Func>>( "sqrt(2)" to { n -> intArrayOf(if (n > 0) 2 else 1, 1) }, "e " to { n -> intArrayOf(if (n > 0) n else 2, if (n > 1) n - 1 else 1) }, "pi " to { n -> intArrayOf(if (n > 0) 6 else 3, (2 * n - 1) * (2 * n - 1)) } ) for (pair in pList) println("${pair.first} = ${calc(pair.second, 200)}") }