task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
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
| #Jsish | Jsish | #!/usr/bin/env jsish
/* Top rank per group, in Jsish */
function top_rank(n) {
var by_dept = group_by_dept(data);
for (var dept in by_dept) {
puts(dept);
for (var i = 0; i < n && i < by_dept[dept].length; i++) {
var emp = by_dept[dept][i];
puts(emp.name + ", id=" + emp.id + ", salary=" + emp.salary);
}
puts("");
}
}
// 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 ( !by_dept.hasOwnProperty(dept)) {
by_dept[dept] = new Array();
}
by_dept[dept].push(data[idx]);
}
for (var dept in by_dept) {
by_dept[dept].sort(function (a,b) { return b.salary - a.salary; });
}
return by_dept;
}
if (Interp.conf('unitTest')) {
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"}
];
top_rank(3);
}
/*
=!EXPECTSTART!=
D050
John Rappl, id=E21437, salary=47000
Nathan Adams, id=E41298, salary=21900
D101
George Woltman, id=E00127, salary=53500
David McClellan, id=E04242, salary=41500
Tyler Bennett, id=E10297, salary=32000
D190
Kim Arlich, id=E10001, salary=57000
Timothy Grove, id=E16398, salary=29900
D202
Rich Holcomb, id=E01234, salary=49500
Claire Buckman, id=E39876, salary=27800
David Motsinger, id=E27002, salary=19250
=!EXPECTEND!=
*/ |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #JavaScript | JavaScript |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>TicTacToe</title>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
//All helper functions
isBetween = (num, a, b) => {
return num >= a && num <= b;
}
randInt = (low, high) => {
return Math.floor(Math.random() * (high - low + 1)) + low;
}
choice = arr => {
return arr[randInt(0, arr.length - 1)];
}
//Checks if every value in an array equals an item
equals = (arr, item) => {
return arr.filter(a => {
return a === item;
}).length === arr.length;
}
//Returns number of items in array that equal an item
equallen = (arr, item) => {
return arr.filter(a => {
return a === item;
}).length
}
//Checks if any value in the array equals an item
equalanyof = (arr, item) => {
return equallen(arr, item) > 0;
}
//Should be scalable, but it uses default elements for calculations and tracking
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
const width = canvas.width;
const blockSize = canvas.width / 3;
const lineSize = blockSize / 5;
//Draws background
ctx.fillStyle = "rgb(225, 225, 225)";
ctx.fillRect(0, 0, 400, 400);
//Title page
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.font = width / (250 / 17) + "px Arial"; //34
ctx.textAlign = "center";
ctx.fillText("Tic Tac Toe", width / 2, width / (2 + 2 / 3)); //200, 150
//Button for starting
ctx.fillStyle = "rgb(200, 200, 200)";
ctx.fillRect(width / 3.2, width / 2, width / (2 + 2 / 3), width / 8); //125, 200, 150, 50
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.font = width / (200 / 9) + "px Arial"; //18
ctx.fillText("Start", width / 2, width / (40 / 23)); //200, 230
//Uses an array so a forEach loop can scan it for the correct tile
let tileArray = []; //Contains all tiles
let available = []; //Contains only available tiles
class Tile {
constructor(x, y) {
this.x = x * blockSize;
this.y = y * blockSize;
this.state = "none";
tileArray.push(this);
available.push(this);
}
draw() {
ctx.strokeStyle = "rgb(175, 175, 175)";
ctx.lineWidth = blockSize / 10;
if (this.state === "X") {
ctx.beginPath();
ctx.moveTo(this.x + blockSize / 4, this.y + blockSize / 4);
ctx.lineTo(this.x + blockSize / (4 / 3), this.y + blockSize / (4 / 3));
ctx.moveTo(this.x + blockSize / 4, this.y + blockSize / (4 / 3));
ctx.lineTo(this.x + blockSize / (4 / 3), this.y + blockSize / 4);
ctx.stroke();
} else if (this.state === "O") {
ctx.beginPath();
ctx.arc(this.x + blockSize / 2, this.y + blockSize / 2, blockSize / 4, 0, 2 * Math.PI);
ctx.stroke();
}
//Removes this from the available array
const ind = available.indexOf(this);
available = available.slice(0, ind).concat(available.slice(ind + 1, available.length));
}
}
//Defines the game
let game = {
state: "start",
turn: "Player",
player: "X",
opp: "O"
}
//Generates tiles
for (let x = 0; x < 3; x++) {
for (let y = 0; y < 3; y++) {
new Tile(x, y);
}
}
//Gets the mouse position
getMousePos = evt => {
let rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
}
}
//Checks for win conditions
checkCondition = () => {
//Local variables are created to make access easier
let as = tileArray[0].state;
let bs = tileArray[1].state;
let cs = tileArray[2].state;
let ds = tileArray[3].state;
let es = tileArray[4].state;
let fs = tileArray[5].state;
let gs = tileArray[6].state;
let hs = tileArray[7].state;
let is = tileArray[8].state;
//Equals function checks if each value in the array has a state of X or O
if (equals([as, bs, cs], "X") || equals([ds, es, fs], "X") || equals([gs, hs, is], "X") ||
equals([as, ds, gs], "X") || equals([bs, es, hs], "X") || equals([cs, fs, is], "X") ||
equals([as, es, is], "X") || equals([cs, es, gs], "X")) {
alert("Player wins!");
game.state = "over";
} else if (equals([as, bs, cs], "O") || equals([ds, es, fs], "O") || equals([gs, hs, is], "O") ||
equals([as, ds, gs], "O") || equals([bs, es, hs], "O") || equals([cs, fs, is], "O") ||
equals([as, es, is], "O") || equals([cs, es, gs], "O")) {
alert("Opponent wins!");
game.state = "over";
//It is a tie if none of the above conditions are fulfilled and there are no available tiles
} else if (available.length === 0) {
alert("It's a tie!");
game.state = "over";
}
}
//Controls the opponent. Uses many nested switches/if-else for efficiency
oppTurn = () => {
if (game.state === "game") {
let tile = 0;
//Similar local variables as the win checker
let at = tileArray[0].state;
let bt = tileArray[1].state;
let ct = tileArray[2].state;
let dt = tileArray[3].state;
let et = tileArray[4].state;
let ft = tileArray[5].state;
let gt = tileArray[6].state;
let ht = tileArray[7].state;
let it = tileArray[8].state;
let all = [at, bt, ct, dt, et, ft, gt, ht, it];
/*The AI will automatically win if possible
I considered using a filter based system, but it was ugly and
inelegant, and also redundant
I used a nested if-else instead
Equallen checks how many values in the array equal the given value*/
if (equallen(all, "O") >= 2) {
if (equallen([at, bt, ct], "O") === 2 && equallen([at, bt, ct], "X") === 0) {
if (at === "none") {
tile = tileArray[0];
} else if (bt === "none") {
tile = tileArray[1];
} else if (ct === "none") {
tile = tileArray[2];
}
} else if (equallen([dt, et, ft], "O") === 2 && equallen([dt, et, ft], "X") === 0) {
if (dt === "none") {
tile = tileArray[3];
} else if (et === "none") {
tile = tileArray[4];
} else if (ft === "none") {
tile = tileArray[5];
}
} else if (equallen([gt, ht, it], "O") === 2 && equallen([gt, ht, it], "X") === 0) {
if (gt === "none") {
tile = tileArray[6];
} else if (ht === "none") {
tile = tileArray[7];
} else if (it === "none") {
tile = tileArray[8];
}
} else if (equallen([at, dt, gt], "O") === 2 && equallen([at, dt, gt], "X") === 0) {
if (at === "none") {
tile = tileArray[0];
} else if (dt === "none") {
tile = tileArray[3];
} else if (gt === "none") {
tile = tileArray[6];
}
} else if (equallen([bt, et, ht], "O") === 2 && equallen([bt, et, ht], "X") === 0) {
if (bt === "none") {
tile = tileArray[1];
} else if (et === "none") {
tile = tileArray[4];
} else if (ht === "none") {
tile = tileArray[7];
}
} else if (equallen([ct, ft, it], "O") === 2 && equallen([ct, ft, it], "X") === 0) {
if (ct === "none") {
tile = tileArray[2];
} else if (ft === "none") {
tile = tileArray[5];
} else if (it === "none") {
tile = tileArray[8];
}
} else if (equallen([at, et, it], "O") === 2 && equallen([at, et, it], "X") === 0) {
if (at === "none") {
tile = tileArray[0];
} else if (et === "none") {
tile = tileArray[4];
} else if (it === "none") {
tile = tileArray[8];
}
} else if (equallen([ct, et, gt], "O") === 2 && equallen([ct, et, gt], "X") === 0) {
if (ct === "none") {
tile = tileArray[2];
} else if (et === "none") {
tile = tileArray[4];
} else if (gt === "none") {
tile = tileArray[6];
}
}
}
//Stops player from winning if possible
if (equallen(all, "X") >= 2 && tile === 0) {
if (equallen([at, bt, ct], "X") === 2 && equallen([at, bt, ct], "O") === 0) {
if (at === "none") {
tile = tileArray[0];
} else if (bt === "none") {
tile = tileArray[1];
} else if (ct === "none") {
tile = tileArray[2];
}
} else if (equallen([dt, et, ft], "X") === 2 && equallen([dt, et, ft], "O") === 0) {
if (dt === "none") {
tile = tileArray[3];
} else if (et === "none") {
tile = tileArray[4];
} else if (ft === "none") {
tile = tileArray[5];
}
} else if (equallen([gt, ht, it], "X") === 2 && equallen([gt, ht, it], "O") === 0) {
if (gt === "none") {
tile = tileArray[6];
} else if (ht === "none") {
tile = tileArray[7];
} else if (it === "none") {
tile = tileArray[8];
}
} else if (equallen([at, dt, gt], "X") === 2 && equallen([at, dt, gt], "O") === 0) {
if (at === "none") {
tile = tileArray[0];
} else if (dt === "none") {
tile = tileArray[3];
} else if (gt === "none") {
tile = tileArray[6];
}
} else if (equallen([bt, et, ht], "X") === 2 && equallen([bt, et, ht], "O") === 0) {
if (bt === "none") {
tile = tileArray[1];
} else if (et === "none") {
tile = tileArray[4];
} else if (ht === "none") {
tile = tileArray[7];
}
} else if (equallen([ct, ft, it], "X") === 2 && equallen([ct, ft, it], "O") === 0) {
if (ct === "none") {
tile = tileArray[2];
} else if (ft === "none") {
tile = tileArray[5];
} else if (it === "none") {
tile = tileArray[8];
}
} else if (equallen([at, et, it], "X") === 2 && equallen([at, et, it], "O") === 0) {
if (at === "none") {
tile = tileArray[0];
} else if (et === "none") {
tile = tileArray[4];
} else if (it === "none") {
tile = tileArray[8];
}
} else if (equallen([ct, et, gt], "X") === 2 && equallen([ct, et, gt], "O") === 0) {
if (ct === "none") {
tile = tileArray[2];
} else if (et === "none") {
tile = tileArray[4];
} else if (gt === "none") {
tile = tileArray[6];
}
}
}
//Other options in case the above are not fulfilled
//Controls the course of play over the game
if (tile === 0) {
switch (9 - available.length) {
case 1:
//If the center is taken, it plays randomly in the corner
//Otherwise, it takes the center
if (et === "X") {
tile = tileArray[choice([0, 2, 6, 8])];
} else {
tile = tileArray[4];
}
break;
case 3:
if (et === "X" && (equalanyof([at, ct, gt, it], "O"))) {
/*To counter the strategy of
O - -
- X -
X - -
O - -
- X -
- - X
and related strategies*/
if (at === "X") {
if (it === "none") {
tile = tileArray[8];
} else {
tile = tileArray[choice([2, 6])];
}
} else if (ct === "X") {
if (gt === "none") {
tile = tileArray[6];
} else {
tile = tileArray[choice([0, 8])];
}
} else if (gt === "X") {
if (ct === "none") {
tile = tileArray[2];
} else {
tile = tileArray[choice([0, 8])];
}
} else if (it === "X") {
if (at === "none") {
tile = tileArray[0];
} else {
tile = tileArray[choice([2, 6])];
}
}
} else {
tile = choice(tileArray);
}
break;
}
}
//Generates a random number if it could cause an error
if (tile.state != "none") {
tile = choice(available);
}
//Draws the selection
tile.state = game.opp;
tile.draw();
checkCondition();
game.turn = "Player";
}
}
//Click handler
document.onclick = event => {
let pos = getMousePos(event);
switch (game.state) {
case "start":
//Checks if the button was clicked
if (isBetween(pos.x, width / 3.2, width / (16 / 11)) && isBetween(pos.y, width / 2, width / 1.6)) {
game.state = "game"
//Draws the setup for the game
ctx.fillStyle = "rgb(225, 225, 225)";
ctx.fillRect(0, 0, 400, 400);
//Draws the lines
ctx.fillStyle = "rgb(200, 200, 200)";
ctx.fillRect(blockSize - lineSize / 2, 0, lineSize, width);
ctx.fillRect(blockSize * 2 - lineSize / 2, 0, lineSize, width);
ctx.fillRect(0, blockSize - lineSize / 2, width, lineSize);
ctx.fillRect(0, blockSize * 2 - lineSize / 2, width, lineSize);
}
break;
case "game":
if (game.turn === "Player") {
//Goes through the tile array, checking if the click occurred there
tileArray.forEach(tile => {
if (isBetween(pos.x, tile.x, tile.x + blockSize) && isBetween(pos.y, tile.y, tile.y + blockSize)) {
if (available.indexOf(tile) != -1) {
tile.state = game.player;
tile.draw();
checkCondition();
game.turn = "Opponent";
oppTurn();
}
}
});
}
break;
}
}
</script>
</body>
</html>
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #EDSAC_order_code | EDSAC order code |
[Towers of Hanoi task for Rosetta Code.]
[EDSAC program, Initial Orders 2.]
T100K [load program at location 100 (arbitrary)]
GK
[Number of discs, in the address field]
[0] P3F [<--- edit here, value 1..9]
[Letters to represent the rods]
[1] LF [left]
[2] CF [centre]
[3] RF [right]
[Main routine. Enter with acc = 0]
[4] T1F [1F := 0]
[5] A5@ [initialize recursive subroutine]
G104@
A@ [number of discs]
T1F [pass to subroutines]
A1@ [source rod]
T4F [pass to subroutines]
A3@ [target rod]
T5F [pass to subroutines]
[13] A13@ [call subroutine to write header ]
G18@
[15] A15@ [call recursive subroutine to write moves ]
G104@
ZF [stop]
[Subroutine to write a header]
[Input: 1F = number of discs (in the address field)]
[4F = letter for starting rod]
[5F = letter for ending rod]
[Output: None. 1F, 4F, 5F must be preserved.]
[18] A3F [plant return link as usual]
T35@
A1F [number of discs]
L512F [shift 11 left to make output char]
T39@ [plant in message]
A4F [starting rod]
T53@ [plant in message]
A5F [ending rod]
T58@ [plant in message]
A36@ [O order for first char of message]
E30@ [skip next order (code for 'O' is positive)]
[29] A37@ [restore acc after test below]
[30] U31@ [plant order to write next character]
[31] OF [(planted) write next character]
A2F [inc address in previous order]
S37@ [finished yet?]
G29@ [if not, loop back]
[35] ZF [(planted) exit with acc = 0]
[36] O38@ [O order for start of message]
[37] O61@ [O order for exclusive end of message]
[38] #F
[39] PFK2048F!FDFIFSFCFSF!FFFRFOFMF!F
[53] PF!FTFOF!F
[58] PF@F&F
[61]
[Subroutine to write a move of one disc.]
[Input: 1F = disc number 1..9 (in the address field)]
[4F = letter for source rod]
[5F = letter for target rod]
[Output: None. 1F, 4F, 5F must be preserved.]
[Condensed to save space; very similar to previous subroutine.]
[61] A3FT78@A1FL512FT88@ A4FT96@A5FT101@A79@E73@
[72] A80@
[73] U74@
[74] OFA2FS80@G72@
[78] ZF [(planted) exit with acc = 0]
[79] O81@
[80] O104@
[81] K2048FMFOFVFEF!F#F
[88] PFK2048F!FFFRFOFMF!F
[96] PF!FTFOF!F
[101] PF@F&F
[104]
[Recursive subroutine to move discs 1..n, where 1 <= n <= 9.]
[Call with n = 0 to initialize.]
[Input: 1F = n (in the address field)]
[4F = letter for source rod]
[5F = letter for target rod]
[Output: None. 1F, 4F, 5F must be preserved.]
[104] A3F [plant link as usual ]
T167@
[The link will be saved in a stack if recursive calls are required.]
S1F [load -n]
G115@ [jump if n > 0]
[Here if n = 0. Initialize; no recursive calls.]
A169@ [initialize push order to start of stack]
T122@
A1@ [find total of the codes for the rod letters]
A2@
A3@
T168@ [store for future use]
E167@ [jump to link]
[Here with acc = -n in address field]
[115] A2F [add 1]
G120@ [jump if n > 1]
[Here if n = 1. Just write the move; no recursive calls.]
[117] A117@ [call write subroutine]
G61@
E167@ [jump to link]
[Here if n > 1. Recursive calls are required.]
[120] TF [clear acc]
A167@ [load link order]
[122] TF [(planted) push link order onto stack]
A122@ [inc address in previous order]
A2F
T122@
[First recursive call. Modify parameters 1F and 5F; 4F stays the same]
A1F [load n]
S2F [make n - 1]
T1F [pass as parameter]
A168@ [get 3rd rod, neither source nor target]
S4F
S5F
T5F
[133] A133@ [recursive call]
G104@
[Returned, restore parameters]
A1F
A2F
T1F
A168@
S4F
S5F
T5F
[Write move of largest disc]
[142] A142@
G61@
[Second recursive call. Modify parameters 1F and 4F; 5F stays the same]
[Condensed to save space; very similar to first recursice call.]
A1FS2FT1FA168@S4FS5FT4F
[151] A151@G104@A1FA2FT1FA168@S4FS5FT4F
[Pop return link off stack]
A122@ [dec address in push order]
S2F
U122@
A170@ [make A order with same address]
T165@ [plant in code]
[165] AF [(planted) pop return link from stack]
T167@ [plant in code]
[167] ZF [(planted) return to caller]
[Constants]
[168] PF [(planted) sum of letters for rods]
[169] T171@ [T order for start of stack]
[170] MF [add to T order to make A order, same address]
[Stack: placed at end of program, grows into free space.]
[171]
E4Z [define entry point]
PF [acc = 0 on entry]
[end]
|
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #PowerShell | PowerShell | #Input Data
$a=@"
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
"@
#Convert to Object[]
$c = switch ( $a.split([char] 10) ) {
$_ {
$b=$_.split(' ')
New-Object PSObject -Property @{
Library = $b[0]
"Library Dependencies" = @( $( $b[1..($b.length-1)] | Where-Object { $_ -match '\w' } ) )
}
}
}
#Add pure dependencies
$c | ForEach-Object {
$_."Library Dependencies" | Where-Object {
$d=$_
$(:andl foreach($i in $c) {
if($d -match $i.Library) {
$false
break andl
}
}) -eq $null
} | ForEach-Object {
$c+=New-Object PSObject -Property @{
Library=$_
"Library Dependencies"=@()
}
}
}
#Associate with a dependency value
##Initial Dependency Value
$d = $c | Sort Library | Select-Object Library,"Library Dependencies",@{
Name="Dep Value"
Expression={
1
}
}
##Modify Dependency Value, perform check for incorrect dependency
##Dep Value is determined by a parent child relationship, if a library is a parent, all libraries dependant on it are children
for( $i=0; $i -lt $d.count; $i++ ) {
$errmsg=""
foreach( $j in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $i } ) ) {
#Foreach other Child Library where this is a dependency, increase the Dep Value of the Child
if( $( :orl foreach( $k in $d[$j]."Library Dependencies" ) {
if( $k -match $d[$i].Library ) {
foreach( $n in $d[$i]."Library Dependencies" ) {
if( $n -match $d[$j].Library ) {
$errmsg="Error Cyclic Dependency {0}<->{1}" -f $d[$i].Library, $d[$j].Library
break
}
}
$true
break orl
}
} ) ) {
#If the child has already been processed, increase the Dep Value of its children
if( $j -lt $i ) {
foreach( $l in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $j } ) ) {
if( $( :orl2 foreach( $m in $d[$l]."Library Dependencies" ) {
if( $m -match $d[$j].Library ) {
$true
break orl2
}
} ) ) {
$d[$l]."Dep Value"+=$d[$i]."Dep Value"
}
}
}
$d[$j]."Dep Value"+=$d[$i]."Dep Value"
}
if( $errmsg -ne "" ) {
$errmsg
$d=$null
break
}
}
}
#Sort and Display
if( $d ) {
$d | Sort "Dep Value",Library | ForEach-Object {
"{0,-14} LIBRARY DEPENDENCIES`n{1,-14} ====================" -f "LIBRARY", "======="
} {
"{0,-14} $($_."Library Dependencies")" -f $_.Library
}
} |
http://rosettacode.org/wiki/Universal_Turing_machine | Universal Turing machine | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936–1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
Task
Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.
Of course, you will not have an infinite tape,
but you should emulate this as much as is possible.
The three permissible actions on the tape are "left", "right" and "stay".
To test your universal Turing machine (and prove your programming language
is Turing complete!), you should execute the following two Turing machines
based on the following definitions.
Simple incrementer
States: q0, qf
Initial state: q0
Terminating states: qf
Permissible symbols: B, 1
Blank symbol: B
Rules:
(q0, 1, 1, right, q0)
(q0, B, 1, stay, qf)
The input for this machine should be a tape of 1 1 1
Three-state busy beaver
States: a, b, c, halt
Initial state: a
Terminating states: halt
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(a, 0, 1, right, b)
(a, 1, 1, left, c)
(b, 0, 1, left, a)
(b, 1, 1, right, b)
(c, 0, 1, left, b)
(c, 1, 1, stay, halt)
The input for this machine should be an empty tape.
Bonus:
5-state, 2-symbol probable Busy Beaver machine from Wikipedia
States: A, B, C, D, E, H
Initial state: A
Terminating states: H
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(A, 0, 1, right, B)
(A, 1, 1, left, C)
(B, 0, 1, right, C)
(B, 1, 1, right, B)
(C, 0, 1, right, D)
(C, 1, 0, left, E)
(D, 0, 1, left, A)
(D, 1, 1, left, D)
(E, 0, 1, stay, H)
(E, 1, 0, left, A)
The input for this machine should be an empty tape.
This machine runs for more than 47 millions steps.
| #Wren | Wren | import "/dynamic" for Enum, Tuple, Struct
import "/fmt" for Fmt
var Dir = Enum.create("Dir", ["LEFT", "RIGHT", "STAY"])
var Rule = Tuple.create("Rule", ["state1", "symbol1", "symbol2", "dir", "state2"])
var Tape = Struct.create("Tape", ["symbol", "left", "right"])
class Turing {
construct new(states, finalStates, symbols, blank, state, tapeInput, rules) {
_states = states
_finalStates = finalStates
_symbols = symbols
_blank = blank
_state = state
_tape = null
_transitions = List.filled(_states.count, null)
for (i in 0..._states.count) _transitions[i] = List.filled(_symbols.count, null)
for (i in 0...tapeInput.count) {
move_(Dir.RIGHT)
_tape.symbol = tapeInput[i]
}
if (tapeInput.count == 0) move_(Dir.RIGHT)
while (_tape.left) _tape = _tape.left
for (i in 0...rules.count) {
var rule = rules[i]
_transitions[stateIndex_(rule.state1)][symbolIndex_(rule.symbol1)] = rule
}
}
stateIndex_(state) {
var i = _states.indexOf(state)
return (i >= 0) ? i : 0
}
symbolIndex_(symbol) {
var i = _symbols.indexOf(symbol)
return (i >= 0) ? i : 0
}
move_(dir) {
var orig = _tape
if (dir == Dir.RIGHT) {
if (orig && orig.right) {
_tape = orig.right
} else {
_tape = Tape.new(_blank, null, null)
if (orig) {
_tape.left = orig
orig.right = _tape
}
}
} else if (dir == Dir.LEFT) {
if (orig && orig.left) {
_tape = orig.left
} else {
_tape = Tape.new(_blank, null, null)
if (orig) {
_tape.right = orig
orig.left = _tape
}
}
} else if (dir == Dir.STAY) {}
}
printState() {
Fmt.write("$-10s ", _state)
var t = _tape
while (t.left) t = t.left
while (t) {
if (t == _tape) {
System.write("[%(t.symbol)]")
} else {
System.write(" %(t.symbol) ")
}
t = t.right
}
System.print()
}
run(maxLines) {
var lines = 0
while (true) {
printState()
for (finalState in _finalStates) {
if (finalState == _state) return
}
lines = lines + 1
if (lines == maxLines) {
System.print("(Only the first %(maxLines) lines displayed)")
return
}
var rule = _transitions[stateIndex_(_state)][symbolIndex_(_tape.symbol)]
_tape.symbol = rule.symbol2
move_(rule.dir)
_state = rule.state2
}
}
}
System.print("Simple incrementer")
Turing.new(
["q0", "qf"], // states
["qf"], // finalStates
["B", "1"], // symbols
"B", // blank
"q0", // state
["1", "1", "1"], // tapeInput
[ // rules
Rule.new("q0", "1", "1", Dir.RIGHT, "q0"),
Rule.new("q0", "B", "1", Dir.STAY, "qf")
]
).run(20)
System.print("\nThree-state busy beaver")
Turing.new(
["a", "b", "c", "halt"], // states
["halt"], // finalStates
["0", "1"], // symbols
"0", // blank
"a", // state
[], // tapeInput
[ // rules
Rule.new("a", "0", "1", Dir.RIGHT, "b"),
Rule.new("a", "1", "1", Dir.LEFT, "c"),
Rule.new("b", "0", "1", Dir.LEFT, "a"),
Rule.new("b", "1", "1", Dir.RIGHT, "b"),
Rule.new("c", "0", "1", Dir.LEFT, "b"),
Rule.new("c", "1", "1", Dir.STAY, "halt")
]
).run(20)
System.print("\nFive-state two-symbol probable busy beaver")
Turing.new(
["A", "B", "C", "D", "E", "H"], // states
["H"], // finalStates
["0", "1"], // symbols
"0", // blank
"A", // state
[], // tapeInput
[ // rules
Rule.new("A", "0", "1", Dir.RIGHT, "B"),
Rule.new("A", "1", "1", Dir.LEFT, "C"),
Rule.new("B", "0", "1", Dir.RIGHT, "C"),
Rule.new("B", "1", "1", Dir.RIGHT, "B"),
Rule.new("C", "0", "1", Dir.RIGHT, "D"),
Rule.new("C", "1", "0", Dir.LEFT, "E"),
Rule.new("D", "0", "1", Dir.LEFT, "A"),
Rule.new("D", "1", "1", Dir.LEFT, "D"),
Rule.new("E", "0", "1", Dir.STAY, "H"),
Rule.new("E", "1", "0", Dir.LEFT, "A")
]
).run(20) |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #Maxima | Maxima | a: %pi / 3;
[sin(a), cos(a), tan(a), sec(a), csc(a), cot(a)];
b: 1 / 2;
[asin(b), acos(b), atan(b), asec(1 / b), acsc(1 / b), acot(b)];
/* Hyperbolic functions are also available */
a: 1 / 2;
[sinh(a), cosh(a), tanh(a), sech(a), csch(a), coth(a)], numer;
[asinh(a), acosh(1 / a), atanh(a), asech(a), acsch(a), acoth(1 / a)], numer; |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #Java | Java | import java.util.*;
public class TreeTraversal {
static class Node<T> {
T value;
Node<T> left;
Node<T> right;
Node(T value) {
this.value = value;
}
void visit() {
System.out.print(this.value + " ");
}
}
static enum ORDER {
PREORDER, INORDER, POSTORDER, LEVEL
}
static <T> void traverse(Node<T> node, ORDER order) {
if (node == null) {
return;
}
switch (order) {
case PREORDER:
node.visit();
traverse(node.left, order);
traverse(node.right, order);
break;
case INORDER:
traverse(node.left, order);
node.visit();
traverse(node.right, order);
break;
case POSTORDER:
traverse(node.left, order);
traverse(node.right, order);
node.visit();
break;
case LEVEL:
Queue<Node<T>> queue = new LinkedList<>();
queue.add(node);
while(!queue.isEmpty()){
Node<T> next = queue.remove();
next.visit();
if(next.left!=null)
queue.add(next.left);
if(next.right!=null)
queue.add(next.right);
}
}
}
public static void main(String[] args) {
Node<Integer> one = new Node<Integer>(1);
Node<Integer> two = new Node<Integer>(2);
Node<Integer> three = new Node<Integer>(3);
Node<Integer> four = new Node<Integer>(4);
Node<Integer> five = new Node<Integer>(5);
Node<Integer> six = new Node<Integer>(6);
Node<Integer> seven = new Node<Integer>(7);
Node<Integer> eight = new Node<Integer>(8);
Node<Integer> nine = new Node<Integer>(9);
one.left = two;
one.right = three;
two.left = four;
two.right = five;
three.left = six;
four.left = seven;
six.left = eight;
six.right = nine;
traverse(one, ORDER.PREORDER);
System.out.println();
traverse(one, ORDER.INORDER);
System.out.println();
traverse(one, ORDER.POSTORDER);
System.out.println();
traverse(one, ORDER.LEVEL);
}
} |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Julia | Julia |
s = "Hello,How,Are,You,Today"
a = split(s, ",")
t = join(a, ".")
println("The string \"", s, "\"")
println("Splits into ", a)
println("Reconstitutes to \"", t, "\"")
|
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #K | K | words: "," \: "Hello,How,Are,You,Today"
"." /: words |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Perl | Perl | use Benchmark;
use Memoize;
sub fac1 {
my $n = shift;
return $n == 0 ? 1 : $n * fac1($n - 1);
}
sub fac2 {
my $n = shift;
return $n == 0 ? 1 : $n * fac2($n - 1);
}
memoize('fac2');
my $result = timethese(100000, {
'fac1' => sub { fac1(50) },
'fac2' => sub { fac2(50) },
});
Benchmark::cmpthese($result); |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
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
| #Julia | Julia | # v0.6.0
using DataFrames
df = DataFrame(
EmployeeName=["Tyler Bennett", "John Rappl", "George Woltman", "Adam Smith",
"Claire Buckman", "David McClellan", "Rich Holcomb", "Nathan Adams",
"Richard Potter", "David Motsinger", "Tim Sampair", "Kim Arlich", "Timothy Grove"],
EmployeeID = ["E10297", "E21437", "E00127", "E63535", "E39876", "E04242",
"E01234", "E41298", "E43128", "E27002", "E03033", "E10001", "E16398"],
Salary = [32000, 47000, 53500, 18000, 27800, 41500, 49500, 21900, 15900, 19250,
27000, 57000, 29900],
Department = ["D101", "D050", "D101", "D202", "D202", "D101", "D202", "D050",
"D101", "D202", "D101", "D190", "D190"])
# To get only values
function firstnby(n::Int, y::Array, by::Array)
# Check that each value belong to one and one only class
if length(y) != length(by); error("y and by must have the same length"); end
# Initialize resulting dictionary
rst = Dict{eltype(by), Array{eltype(y)}}()
# For each class...
for cl in unique(by)
# ...select the values of that class...
i = find(x -> x == cl, by)
# ...sort them and store them in result...
rst[cl] = sort(y[i]; rev=true)
# ...if length is greater than n select only first n elements
if length(i) > n
rst[cl] = rst[cl][1:n]
end
end
return rst
end
for (cl, val) in firstnby(3, Array(df[:Salary]), Array(df[:Department]))
println("$cl => $val")
end
# To get the full row...
function firstnby(n::Int, df::DataFrame, y::Symbol, by::Symbol)
rst = Dict{eltype(df[by]), DataFrame}()
for cl in unique(df[by])
i = find(x -> x == cl, df[by])
rst[cl] = sort(df[i, :]; cols=order(y; rev=true))
if length(i) > n
rst[cl] = rst[cl][1:n, :]
end
end
return rst
end
for (cl, data) in firstnby(3, df, :Salary, :Department)
println("\n$cl:\n$data")
end
|
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #Julia | Julia | const winningpositions = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7],
[2, 5, 8], [3, 6, 9],[1, 5, 9], [7, 5, 3]]
function haswon(brd, xoro)
marked = findall(x -> x == xoro, brd)
for pos in winningpositions
if length(pos) <= length(marked) && pos == sort(marked)[1:3]
return true
end
end
false
end
function readcharwithprompt(prompt, expected)
ret = '*'
while !(ret in expected)
print("\n", prompt, " -> ")
ret = lowercase(chomp(readline()))[1]
end
ret
end
availablemoves(brd) = findall(x -> x == ' ', brd)
cornersopen(brd) = [x for x in [1, 3, 7, 9] if brd[x] == ' ']
int2char(x) = Char(x + UInt8('0'))
char2int(x) = UInt8(x) - UInt8('0')
getyn(query) = readcharwithprompt(query, ['y', 'n'])
gettheirmove(brd) = char2int(readcharwithprompt("Your move(1-9)", int2char.(availablemoves(brd))))
function findwin(brd, xoro)
tmpbrd = deepcopy(brd)
for mv in availablemoves(tmpbrd)
tmpbrd[mv] = xoro
if haswon(tmpbrd, xoro)
return mv
end
tmpbrd[mv] = ' '
end
return nothing
end
function choosemove(brd, mychar, theirchar)
if all(x -> x == ' ', brd)
brd[rand(cornersopen(brd))] = mychar # corner trap if starting game
elseif availablemoves(brd) == [] # no more moves
println("Game is over. It was a draw.")
exit(0)
elseif (x = findwin(brd, mychar)) != nothing || (x = findwin(brd, theirchar)) != nothing
brd[x] = mychar # win if possible, block their win otherwise if their win is possible
elseif brd[5] == ' '
brd[5] = mychar # take center if open and not doing corner trap
elseif (corners = cornersopen(brd)) != []
brd[rand(corners)] = mychar # choose a corner over a side middle move
else
brd[rand(availablemoves(brd))] = mychar # random otherwise
end
end
function display(brd)
println("+-----------+")
println("| ", brd[1], " | ", brd[2], " | ", brd[3], " |")
println("| ", brd[4], " | ", brd[5], " | ", brd[6], " |")
println("| ", brd[7], " | ", brd[8], " | ", brd[9], " |")
println("+-----------+")
end
function tictactoe()
board = fill(' ', 9)
println("Board move grid:\n 1 2 3\n 4 5 6\n 7 8 9")
yn = getyn("Would you like to move first (y/n)?")
if yn == 'y'
mychar = 'O'
theirchar = 'X'
board[gettheirmove(board)] = theirchar
else
mychar = 'X'
theirchar = 'O'
end
while true
choosemove(board, mychar, theirchar)
println("Computer has moved.")
display(board)
if haswon(board, mychar)
println("Game over. Computer wins!")
exit(0)
elseif availablemoves(board) == []
break
end
board[gettheirmove(board)] = theirchar
println("Player has moved.")
display(board)
if haswon(board, theirchar)
println("Game over. Player wins!")
exit(0)
elseif availablemoves(board) == []
break
end
end
println("Game over. It was a draw.")
end
tictactoe()
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Eiffel | Eiffel | class
APPLICATION
create
make
feature {NONE} -- Initialization
make
do
move (4, "A", "B", "C")
end
feature -- Towers of Hanoi
move (n: INTEGER; frm, to, via: STRING)
require
n > 0
do
if n = 1 then
print ("Move disk from pole " + frm + " to pole " + to + "%N")
else
move (n - 1, frm, via, to)
move (1, frm, to, via)
move (n - 1, via, to, frm)
end
end
end |
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #PureBasic | PureBasic | #EndOfDataMarker$ = "::EndOfData::"
DataSection
;"LIBRARY: [LIBRARY_DEPENDENCY_1 LIBRARY_DEPENDENCY_2 ... LIBRARY_DEPENDENCY_N]
Data.s "des_system_lib: [std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee]"
Data.s "dw01: [ieee dw01 dware gtech]"
;Data.s "dw01: [ieee dw01 dware gtech dw04]" ;comment the previous line and uncomment this one for cyclic dependency
Data.s "dw02: [ieee dw02 dware]"
Data.s "dw03: [std synopsys dware dw03 dw02 dw01 ieee gtech]"
Data.s "dw04: [dw04 ieee dw01 dware gtech]"
Data.s "dw05: [dw05 ieee dware]"
Data.s "dw06: [dw06 ieee dware]"
Data.s "dw07: [ieee dware]"
Data.s "dware: [ieee dware]"
Data.s "gtech: [ieee gtech]"
Data.s "ramlib: [std ieee]"
Data.s "std_cell_lib: [ieee std_cell_lib]"
Data.s "synopsys: nil"
Data.s #EndOfDataMarker$
EndDataSection
Structure DAG_node
Value.s
forRemoval.i ;flag marks elements that should be removed the next time they are accessed
List dependencies.s()
EndStructure
If Not OpenConsole()
MessageRequester("Error","Unable to open console")
End
EndIf
;// initialize Directed Acyclic Graph //
Define i, itemData.s, firstBracketPos
NewList DAG.DAG_node()
Repeat
Read.s itemData
itemData = Trim(itemData)
If itemData <> #EndOfDataMarker$
AddElement(DAG())
;add library
DAG()\Value = Trim(Left(itemData, FindString(itemData, ":", 1) - 1))
;parse library dependencies
firstBracketPos = FindString(itemData, "[", 1)
If firstBracketPos
itemData = Trim(Mid(itemData, firstBracketPos + 1, FindString(itemData, "]", 1) - firstBracketPos - 1))
For i = (CountString(itemData, " ") + 1) To 1 Step -1
AddElement(DAG()\dependencies())
DAG()\dependencies() = StringField(itemData, i, " ")
Next
EndIf
EndIf
Until itemData = #EndOfDataMarker$
;// process DAG //
;create DAG entry for nodes listed in dependencies but without their own entry
NewMap libraries()
ForEach DAG()
ForEach DAG()\dependencies()
libraries(DAG()\dependencies()) = #True
If DAG()\dependencies() = DAG()\Value
DeleteElement(DAG()\dependencies()) ;remove self-dependencies
EndIf
Next
Next
ForEach DAG()
If FindMapElement(libraries(),DAG()\Value)
DeleteMapElement(libraries(),DAG()\Value)
EndIf
Next
ResetList(DAG())
ForEach libraries()
AddElement(DAG())
DAG()\Value = MapKey(libraries())
Next
ClearMap(libraries())
;process DAG() repeatedly until no changes occur
NewList compileOrder.s()
Repeat
noChangesMade = #True
ForEach DAG()
If DAG()\forRemoval
DeleteElement(DAG())
Else
;remove dependencies that have been placed in the compileOrder
ForEach DAG()\dependencies()
If FindMapElement(libraries(),DAG()\dependencies())
DeleteElement(DAG()\dependencies())
EndIf
Next
;add DAG() entry to compileOrder if it has no more dependencies
If ListSize(DAG()\dependencies()) = 0
AddElement(compileOrder())
compileOrder() = DAG()\Value
libraries(DAG()\Value) = #True ;mark the library for removal as a dependency
DAG()\forRemoval = #True
noChangesMade = #False
EndIf
EndIf
Next
Until noChangesMade
If ListSize(DAG())
PrintN("Cyclic dependencies detected in:" + #CRLF$)
ForEach DAG()
PrintN(" " + DAG()\Value)
Next
Else
PrintN("Compile order:" + #CRLF$)
ForEach compileOrder()
PrintN(" " + compileOrder())
Next
EndIf
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole() |
http://rosettacode.org/wiki/Universal_Turing_machine | Universal Turing machine | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936–1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
Task
Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.
Of course, you will not have an infinite tape,
but you should emulate this as much as is possible.
The three permissible actions on the tape are "left", "right" and "stay".
To test your universal Turing machine (and prove your programming language
is Turing complete!), you should execute the following two Turing machines
based on the following definitions.
Simple incrementer
States: q0, qf
Initial state: q0
Terminating states: qf
Permissible symbols: B, 1
Blank symbol: B
Rules:
(q0, 1, 1, right, q0)
(q0, B, 1, stay, qf)
The input for this machine should be a tape of 1 1 1
Three-state busy beaver
States: a, b, c, halt
Initial state: a
Terminating states: halt
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(a, 0, 1, right, b)
(a, 1, 1, left, c)
(b, 0, 1, left, a)
(b, 1, 1, right, b)
(c, 0, 1, left, b)
(c, 1, 1, stay, halt)
The input for this machine should be an empty tape.
Bonus:
5-state, 2-symbol probable Busy Beaver machine from Wikipedia
States: A, B, C, D, E, H
Initial state: A
Terminating states: H
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(A, 0, 1, right, B)
(A, 1, 1, left, C)
(B, 0, 1, right, C)
(B, 1, 1, right, B)
(C, 0, 1, right, D)
(C, 1, 0, left, E)
(D, 0, 1, left, A)
(D, 1, 1, left, D)
(E, 0, 1, stay, H)
(E, 1, 0, left, A)
The input for this machine should be an empty tape.
This machine runs for more than 47 millions steps.
| #Yabasic | Yabasic | // Machine definitions
name = 1 : initState = 2 : endState = 3 : blank = 4 : countOnly = true
incrementer$ = "Simple incrementer,q0,qf,B"
incrementer$ = incrementer$ + ",q0,1,1,right,q0,q0,B,1,stay,qf"
threeStateBB$ = "Three-state busy beaver,a,halt,0"
data "a,0,1,right,b"
data "a,1,1,left,c"
data "b,0,1,left,a"
data "b,1,1,right,b"
data "c,0,1,left,b"
data "c,1,1,stay,halt"
data ""
do
read a$
if a$ = "" break
threeStateBB$ = threeStateBB$ + "," + a$
loop
fiveStateBB$ = "Five-state busy beaver,A,H,0"
data "A,0,1,right,B"
data "A,1,1,left,C"
data "B,0,1,right,C"
data "B,1,1,right,B"
data "C,0,1,right,D"
data "C,1,0,left,E"
data "D,0,1,left,A"
data "D,1,1,left,D"
data "E,0,1,stay,H"
data "E,1,0,left,A"
data ""
do
read a$
if a$ = "" break
fiveStateBB$ = fiveStateBB$ + "," + a$
loop
clear screen
// Display a representation of the tape and machine state on the screen
sub show(state$, headPos, tape$)
local pos
print " ", state$, "\t| ";
for pos = 1 to len(tape$)
if pos = headPos then print "[", mid$(tape$, pos, 1), "] "; else print " ", mid$(tape$, pos, 1), " "; end if
next
print
end sub
sub string.rep$(s$, n)
local i, r$
for i = 1 to n
r$ = r$ + s$
next
return r$
end sub
// Simulate a turing machine
sub UTM(mach$, tape$, countOnly)
local state$, headPos, counter, machine$(1), n, m, rule
m = len(tape$)
n = token(mach$, machine$(), ",")
state$ = machine$(initState)
n = n - blank
headPos = 1
print "\n\n", machine$(name)
print string.rep$("=", len(machine$(name))), "\n"
if not countOnly print " State", "\t| Tape [head]\n----------------------"
repeat
if mid$(tape$, headPos, 1) = " " mid$(tape$, headPos, 1) = machine$(blank)
if not countOnly show(state$, headPos, tape$)
for rule = blank + 1 to n step 5
if machine$(rule) = state$ and machine$(rule + 1) = mid$(tape$, headPos, 1) then
mid$(tape$, headPos, 1) = machine$(rule + 2)
if machine$(rule + 3) = "left" then
headPos = headPos - 1
if headPos < 1 then
headPos = 1
tape$ = " " + tape$
end if
end if
if machine$(rule + 3) = "right" then
headPos = headPos + 1
if headPos > m then
m = m + 1
tape$ = tape$ + " "
end if
end if
state$ = machine$(rule + 4)
break
end if
next
counter = counter + 1
until(state$ = machine$(endState))
if countOnly then print "Steps taken: ", counter else show(state$, headPos, tape$) end if
end sub
// Main procedure
UTM(incrementer$, "111")
UTM(threeStateBB$, " ")
UTM(fiveStateBB$, " ", countOnly) |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #MAXScript | MAXScript | local radians = pi / 4
local degrees = 45.0
--sine
print (sin (radToDeg radians))
print (sin degrees)
--cosine
print (cos (radToDeg radians))
print (cos degrees)
--tangent
print (tan (radToDeg radians))
print (tan degrees)
--arcsine
print (asin (sin (radToDeg radians)))
print (asin (sin degrees))
--arccosine
print (acos (cos (radToDeg radians)))
print (acos (cos degrees))
--arctangent
print (atan (tan (radToDeg radians)))
print (atan (tan degrees)) |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #JavaScript | JavaScript | function BinaryTree(value, left, right) {
this.value = value;
this.left = left;
this.right = right;
}
BinaryTree.prototype.preorder = function(f) {this.walk(f,['this','left','right'])}
BinaryTree.prototype.inorder = function(f) {this.walk(f,['left','this','right'])}
BinaryTree.prototype.postorder = function(f) {this.walk(f,['left','right','this'])}
BinaryTree.prototype.walk = function(func, order) {
for (var i in order)
switch (order[i]) {
case "this": func(this.value); break;
case "left": if (this.left) this.left.walk(func, order); break;
case "right": if (this.right) this.right.walk(func, order); break;
}
}
BinaryTree.prototype.levelorder = function(func) {
var queue = [this];
while (queue.length != 0) {
var node = queue.shift();
func(node.value);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
// convenience function for creating a binary tree
function createBinaryTreeFromArray(ary) {
var left = null, right = null;
if (ary[1]) left = createBinaryTreeFromArray(ary[1]);
if (ary[2]) right = createBinaryTreeFromArray(ary[2]);
return new BinaryTree(ary[0], left, right);
}
var tree = createBinaryTreeFromArray([1, [2, [4, [7]], [5]], [3, [6, [8],[9]]]]);
print("*** preorder ***"); tree.preorder(print);
print("*** inorder ***"); tree.inorder(print);
print("*** postorder ***"); tree.postorder(print);
print("*** levelorder ***"); tree.levelorder(print); |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Klingphix | Klingphix | ( "Hello,How,Are,You,Today" "," ) split len [ get print "." print ] for
nl "End " input |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Kotlin | Kotlin | fun main(args: Array<String>) {
val input = "Hello,How,Are,You,Today"
println(input.split(',').joinToString("."))
} |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Phix | Phix | with javascript_semantics
function identity(integer x)
return x
end function
function total(integer num)
for i=1 to 100_000_000 do
num += odd(i)
end for
return num
end function
procedure time_it(integer fn)
atom t0 = time()
integer res = fn(4)
string funcname = get_routine_info(fn)[4]
printf(1,"%s(4) = %d, taking %s\n",{funcname,res,elapsed(time()-t0)})
end procedure
time_it(identity)
time_it(total)
|
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Phixmonti | Phixmonti | def count
for drop endfor
enddef
1000000 count
msec dup var t0 print " seconds" print nl
10000000 count
msec t0 - print " seconds" print |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
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
| #Kotlin | Kotlin | // version 1.1.2
data class Employee(val name: String, val id: String, val salary: Int, val dept: String)
const val N = 2 //say
fun main(args: Array<String>) {
val employees = listOf(
Employee("Tyler Bennett", "E10297", 32000, "D101"),
Employee("John Rappl", "E21437", 47000, "D050"),
Employee("George Woltman" , "E00127", 53500, "D101"),
Employee("Adam Smith", "E63535", 18000, "D202"),
Employee("Claire Buckman", "E39876", 27800, "D202"),
Employee("David McClellan", "E04242", 41500, "D101"),
Employee("Rich Holcomb", "E01234", 49500, "D202"),
Employee("Nathan Adams", "E41298", 21900, "D050"),
Employee("Richard Potter", "E43128", 15900, "D101"),
Employee("David Motsinger", "E27002", 19250, "D202"),
Employee("Tim Sampair", "E03033", 27000, "D101"),
Employee("Kim Arlich", "E10001", 57000, "D190"),
Employee("Timothy Grove", "E16398", 29900, "D190")
)
val employeesByDept = employees.sortedBy { it.dept }.groupBy { it.dept }
println("Highest $N salaries by department:\n")
for ((key, value) in employeesByDept) {
val topRanked = value.sortedByDescending { it.salary }.take(N)
println("Dept $key => ")
for (i in 0 until N) with (topRanked[i]) { println("${name.padEnd(15)} $id $salary") }
println()
}
} |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #Kotlin | Kotlin | // version 1.1.51
import java.util.Random
val r = Random()
val b = Array(3) { IntArray(3) } // board -> 0: blank; -1: computer; 1: human
var bestI = 0
var bestJ = 0
fun checkWinner(): Int {
for (i in 0..2) {
if (b[i][0] != 0 && b[i][1] == b[i][0] && b[i][2] == b[i][0]) return b[i][0]
if (b[0][i] != 0 && b[1][i] == b[0][i] && b[2][i] == b[0][i]) return b[0][i]
}
if (b[1][1] == 0) return 0
if (b[1][1] == b[0][0] && b[2][2] == b[0][0]) return b[0][0]
if (b[1][1] == b[2][0] && b[0][2] == b[1][1]) return b[1][1]
return 0
}
fun showBoard() {
val t = "X O"
for (i in 0..2) {
for (j in 0..2) print("${t[b[i][j] + 1]} ")
println()
}
println("-----")
}
fun testMove(value: Int, depth: Int): Int {
var best = -1
var changed = 0
var score = checkWinner()
if (score != 0) return if (score == value) 1 else -1
for (i in 0..2) {
for (j in 0..2) {
if (b[i][j] != 0) continue
b[i][j] = value
changed = value
score = -testMove(-value, depth + 1)
b[i][j] = 0
if (score <= best) continue
if (depth == 0) {
bestI = i
bestJ = j
}
best = score
}
}
return if (changed != 0) best else 0
}
fun game(user: Boolean): String {
var u = user
for (i in 0..2) b[i].fill(0)
print("Board postions are numbered so:\n1 2 3\n4 5 6\n7 8 9\n")
print("You have O, I have X.\n\n")
for (k in 0..8) {
while (u) {
var move: Int?
do {
print("Your move: ")
move = readLine()!!.toIntOrNull()
}
while (move != null && move !in 1..9)
move = move!! - 1
val i = move / 3
val j = move % 3
if (b[i][j] != 0) continue
b[i][j] = 1
break
}
if (!u) {
if (k == 0) { // randomize if computer opens, less boring
bestI = r.nextInt(Int.MAX_VALUE) % 3
bestJ = r.nextInt(Int.MAX_VALUE) % 3
}
else testMove(-1, 0)
b[bestI][bestJ] = -1
val myMove = bestI * 3 + bestJ + 1
println("My move: $myMove")
}
showBoard()
val win = checkWinner()
if (win != 0) return (if (win == 1) "You win" else "I win") + ".\n\n"
u = !u
}
return "A draw.\n\n"
}
fun main(args: Array<String>) {
var user = false
while (true) {
user = !user
print(game(user))
var yn: String
do {
print("Play again y/n: ")
yn = readLine()!!.toLowerCase()
}
while (yn != "y" && yn != "n")
if (yn != "y") return
println()
}
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Ela | Ela | open monad io
:::IO
//Functional approach
hanoi 0 _ _ _ = []
hanoi n a b c = hanoi (n - 1) a c b ++ [(a,b)] ++ hanoi (n - 1) c b a
hanoiIO n = mapM_ f $ hanoi n 1 2 3 where
f (x,y) = putStrLn $ "Move " ++ show x ++ " to " ++ show y
//Imperative approach using IO monad
hanoiM n = hanoiM' n 1 2 3 where
hanoiM' 0 _ _ _ = return ()
hanoiM' n a b c = do
hanoiM' (n - 1) a c b
putStrLn $ "Move " ++ show a ++ " to " ++ show b
hanoiM' (n - 1) c b a |
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #Python | Python | try:
from functools import reduce
except:
pass
data = {
'des_system_lib': set('std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee'.split()),
'dw01': set('ieee dw01 dware gtech'.split()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k) # Ignore self dependencies
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, "A cyclic dependency exists amongst %r" % data
print ('\n'.join( toposort2(data) )) |
http://rosettacode.org/wiki/Universal_Turing_machine | Universal Turing machine | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936–1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
Task
Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.
Of course, you will not have an infinite tape,
but you should emulate this as much as is possible.
The three permissible actions on the tape are "left", "right" and "stay".
To test your universal Turing machine (and prove your programming language
is Turing complete!), you should execute the following two Turing machines
based on the following definitions.
Simple incrementer
States: q0, qf
Initial state: q0
Terminating states: qf
Permissible symbols: B, 1
Blank symbol: B
Rules:
(q0, 1, 1, right, q0)
(q0, B, 1, stay, qf)
The input for this machine should be a tape of 1 1 1
Three-state busy beaver
States: a, b, c, halt
Initial state: a
Terminating states: halt
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(a, 0, 1, right, b)
(a, 1, 1, left, c)
(b, 0, 1, left, a)
(b, 1, 1, right, b)
(c, 0, 1, left, b)
(c, 1, 1, stay, halt)
The input for this machine should be an empty tape.
Bonus:
5-state, 2-symbol probable Busy Beaver machine from Wikipedia
States: A, B, C, D, E, H
Initial state: A
Terminating states: H
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(A, 0, 1, right, B)
(A, 1, 1, left, C)
(B, 0, 1, right, C)
(B, 1, 1, right, B)
(C, 0, 1, right, D)
(C, 1, 0, left, E)
(D, 0, 1, left, A)
(D, 1, 1, left, D)
(E, 0, 1, stay, H)
(E, 1, 0, left, A)
The input for this machine should be an empty tape.
This machine runs for more than 47 millions steps.
| #zkl | zkl | var [const] D=Dictionary; // short cut
// blank symbol and terminating state(s) are Void
var Lt=-1, Sy=0, Rt=1; // Left, Stay, Right
fcn printTape(tape,pos){
tape.keys.apply("toInt").sort()
.pump(String,'wrap(i){ ((pos==i) and "(%s)" or " %s ").fmt(tape[i]) })
.println();
}
fcn turing(state,[D]tape,[Int]pos,[D]rules,verbose=True,n=0){
if(not state){
print("%d steps. Length %d. Tape: ".fmt(n,tape.len()));
printTape(tape,Void);
return(tape);
}
r:=rules[state][tape[pos] = tape.find(pos)];
if(verbose) printTape(tape,pos);
tape[pos]=r[0];
return(self.fcn(r[2],tape,pos+r[1],rules,verbose,n+1));
} |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #Metafont | Metafont | Pi := 3.14159;
vardef torad expr x = Pi*x/180 enddef; % conversions
vardef todeg expr x = 180x/Pi enddef;
vardef sin expr x = sind(todeg(x)) enddef; % radians version of sind
vardef cos expr x = cosd(todeg(x)) enddef; % and cosd
vardef sign expr x = if x>=0: 1 else: -1 fi enddef; % commodity
vardef tand expr x = % tan with arg in degree
if cosd(x) = 0:
infinity * sign(sind(x))
else: sind(x)/cosd(x) fi enddef;
vardef tan expr x = tand(todeg(x)) enddef; % arg in rad
% INVERSE
% the arc having x as tanget is that between x-axis and a line
% from the center to the point (1, x); MF angle says this
vardef atand expr x = angle(1,x) enddef;
vardef atan expr x = torad(atand(x)) enddef; % rad version
% known formula to express asin and acos in function of
% atan; a+-+b stays for sqrt(a^2 - b^2) (defined in plain MF)
vardef asin expr x = 2atan(x/(1+(1+-+x))) enddef;
vardef acos expr x = 2atan((1+-+x)/(1+x)) enddef;
vardef asind expr x = todeg(asin(x)) enddef; % degree versions
vardef acosd expr x = todeg(acos(x)) enddef;
% commodity
def outcompare(expr a, b) = message decimal a & " = " & decimal b enddef;
% output tests
outcompare(torad(60), Pi/3);
outcompare(todeg(Pi/6), 30);
outcompare(Pi/3, asin(sind(60)));
outcompare(30, acosd(cos(Pi/6)));
outcompare(45, atand(tand(45)));
outcompare(Pi/4, atan(tand(45)));
outcompare(sin(Pi/3), sind(60));
outcompare(cos(Pi/4), cosd(45));
outcompare(tan(Pi/3), tand(60));
end |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #jq | jq | def preorder:
if length == 0 then empty
else .[0], (.[1]|preorder), (.[2]|preorder)
end;
def inorder:
if length == 0 then empty
else (.[1]|inorder), .[0] , (.[2]|inorder)
end;
def postorder:
if length == 0 then empty
else (.[1] | postorder), (.[2]|postorder), .[0]
end;
# Helper functions for levelorder:
# Produce a stream of the first elements
def heads: map( .[0] | select(. != null)) | .[];
# Produce a stream of the left/right branches:
def tails:
if length == 0 then empty
else [map ( .[1], .[2] ) | .[] | select( . != null)]
end;
def levelorder: [.] | recurse( tails ) | heads;
|
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ksh | Ksh |
#!/bin/ksh
# Tokenize a string
# # Variables:
#
string="Hello,How,Are,You,Today"
inputdelim=\, # a comma
outputdelim=\. # a period
# # Functions:
#
# # Function _tokenize(str, indelim, outdelim)
#
function _tokenize {
typeset _str ; _str="$1"
typeset _ind ; _ind="$2"
typeset _outd ; _outd="$3"
while [[ ${_str} != ${_str/${_ind}/${_outd}} ]]; do
_str=${_str/${_ind}/${_outd}}
done
echo "${_str}"
}
######
# main #
######
_tokenize "${string}" "${inputdelim}" "${outputdelim}" |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #LabVIEW | LabVIEW |
{S.replace , by . in Hello,How,Are,You,Today}.
-> Hello.How.Are.You.Today.
|
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Picat | Picat | import cp.
go =>
println("time/1 for 201 queens:"),
time2(once(queens(201,_Q))),
nl,
% time1b/1 is a used defined function (using statistics/2)
Time = time1b($once(queens(28,Q2))),
println(Q2),
printf("28-queens took %dms\n", Time),
nl.
% N-queens problem.
% N: number of queens to place
% Q: the solution
queens(N, Q) =>
Q=new_list(N),
Q :: 1..N,
all_different(Q),
all_different([$Q[I]-I : I in 1..N]),
all_different([$Q[I]+I : I in 1..N]),
solve([ffd,split],Q).
% time1b/1 is a function that returns the time (ms)
time1b(Goal) = T =>
statistics(runtime, _),
call(Goal),
statistics(runtime, [_,T]). |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #PicoLisp | PicoLisp | : (bench (do 1000000 (* 3 4)))
0.080 sec
-> 12 |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
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
| #Ksh | Ksh |
#!/bin/ksh
exec 2> /tmp/Top_rank_per_group.err
# Top rank per group
# # Variables:
#
integer TOP_NUM=2
typeset -T Empsal_t=(
typeset -h 'Employee Name' ename=''
typeset -h 'Employee ID' eid=''
typeset -i -h 'Employee Salary' esalary
typeset -h 'Emplyee Department' edept=''
function init_employee {
typeset buff ; buff="$1"
typeset oldIFS ; oldIFS="$IFS"
typeset arr ; typeset -a arr
IFS=\,
arr=( ${buff} )
_.ename="${arr[0]}"
_.eid="${arr[1]}"
_.esalary=${arr[2]}
_.edept="${arr[3]}"
IFS="${oldIFS}"
}
)
edata='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'
######
# main #
######
# # Employee data into array of Types
#
typeset -a empsal_t # array of Type variables (objects)
integer j i=0
echo "${edata}" | while read; do
Empsal_t empsal_t[i] # Create Type (object)
empsal_t[i++].init_employee "$REPLY" # Initialize Type (object)
done
# # Sort the array of Type variables
#
set -a -s -A empsal_t -K edept,esalary:n:r,ename
# # BUG work around! duplicate the now sorted Type array and use it for output
#
sorted=$(typeset -p empsal_t) && sorted=${sorted/empsal_t/sorted} && eval ${sorted}
for ((i=0; i<${#sorted[*]}; i++)); do
if [[ ${sorted[i].edept} != ${prevdept} ]] || (( j < TOP_NUM )); then
[[ ${sorted[i].edept} != ${prevdept} ]] && j=0
print "${sorted[i].edept} ${sorted[i].esalary} ${sorted[i].eid} ${sorted[i].ename}"
prevdept=${sorted[i].edept}
(( j++ ))
fi
done |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #Lasso | Lasso | [
session_start('user')
session_addvar('user', 'matrix')
session_addvar('user', 'winrecord')
session_addvar('user', 'turn')
var(matrix)->isNotA(::array) ? var(matrix = array('-','-','-','-','-','-','-','-','-'))
var(winrecord)->isNotA(::array) ? var(winrecord = array)
var(turn)->isNotA(::string) ? var(turn = 'x')
if(web_request->params->asStaticArray >> 'reset') => {
$matrix = array('-','-','-','-','-','-','-','-','-')
$turn = 'x'
}
with i in web_request->params->asStaticArray do => {
if(#i->name->beginswith('p')) => {
local(num = #i->name->asCopy)
#num->removeLeading('p')
#num = integer(#num)
#num > 0 && $matrix->get(#num) == '-' ? $matrix->get(#num) = #i->value
$turn == 'o' ? $turn = 'x' | $turn = 'o'
}
}
local(
istie = false,
winner = 'noone',
clear = false
)
// determine if we have a winner
if($matrix->find('-')->size < 9) => {
local(winners = array('123','456','789','147','258','369','159','357'))
loop(8) => {
local(xscore = 0,oscore = 0,use = #winners->get(loop_count))
with v in #use->values do => {
$matrix->findposition('x') >> integer(#v) ? #xscore++
$matrix->findposition('o') >> integer(#v) ? #oscore++
}
if(#xscore == 3) => {
#winner = 'x'
$winrecord->insert('x')
#clear = true
loop_abort
}
if(#oscore == 3) => {
#winner = 'o'
$winrecord->insert('o')
#clear = true
loop_abort
}
}
}
// determine if tie
if(not $matrix->find('-')->size && #winner == 'noone') => {
#istie = true
#winner = 'tie'
$winrecord->insert('tie')
#clear = true
}
]
<form action="?" method="post">
<table>
<tr>
[loop(3) => {^]<td><button name="p[loop_count]" value="[$turn]"[
$matrix->get(loop_count) != '-' || #winner != 'noone' ? ' disabled="disabled"'
]>[$matrix->get(loop_count) != '-' ? $matrix->get(loop_count) | ' ']</button></td>[^}]
</tr>
<tr>
[loop(-from=4,-to=6) => {^]<td><button name="p[loop_count]" value="[$turn]"[
$matrix->get(loop_count) != '-' || #winner != 'noone' ? ' disabled="disabled"'
]>[$matrix->get(loop_count) != '-' ? $matrix->get(loop_count) | ' ']</button></td>[^}]
</tr>
<tr>
[loop(-from=7,-to=9) => {^]<td><button name="p[loop_count]" value="[$turn]"[
$matrix->get(loop_count) != '-' || #winner != 'noone' ? ' disabled="disabled"'
]>[$matrix->get(loop_count) != '-' ? $matrix->get(loop_count) | ' ']</button></td>[^}]
</tr>
</table>
</form>
[if(#istie && #winner == 'tie')]
<p><b>It's a tie!</b></p>
[else(#winner != 'noone')]
<p>[#winner->uppercase&] won! Congratulations.</p>
[else]<math>Insert formula here</math>
<p>It is now [$turn]'s turn!</p>
[/if]
<p><a href="?reset">Reset</a></p>
[if($winrecord->size)]<p>Win record: [$winrecord->join(', ')]</p>[/if]
[if(#clear == true) => {
$matrix = array('-','-','-','-','-','-','-','-','-')
$turn = 'x'
}] |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Elena | Elena | move = (n,from,to,via)
{
if (n == 1)
{
console.printLine("Move disk from pole ",from," to pole ",to)
}
else
{
move(n-1,from,via,to);
move(1,from,to,via);
move(n-1,via,to,from)
}
}; |
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #R | R |
deps <- list(
"des_system_lib" = c("std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"),
"dw01" = c("ieee", "dw01", "dware", "gtech", "dw04"),
"dw02" = c("ieee", "dw02", "dware"),
"dw03" = c("std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech"),
"dw04" = c("dw04", "ieee", "dw01", "dware", "gtech"),
"dw05" = c("dw05", "ieee", "dware"),
"dw06" = c("dw06", "ieee", "dware"),
"dw07" = c("ieee", "dware"),
"dware" = c("ieee", "dware"),
"gtech" = c("ieee", "gtech"),
"ramlib" = c("std", "ieee"),
"std_cell_lib" = c("ieee", "std_cell_lib"),
"synopsys" = c())
|
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #MiniScript | MiniScript | pi3 = pi/3
degToRad = pi/180
print "sin PI/3 radians = " + sin(pi3)
print "sin 60 degrees = " + sin(60*degToRad)
print "arcsin 0.5 in radians = " + asin(0.5)
print "arcsin 0.5 in degrees = " + asin(0.5)/degToRad
print "cos PI/3 radians = " + cos(pi3)
print "cos 60 degrees = " + cos(60*degToRad)
print "arccos 0.5 in radians = " + acos(0.5)
print "arccos 0.5 in degrees = " + acos(0.5)/degToRad
print "tan PI/3 radians = " + tan(pi3)
print "tan 60 degrees = " + tan(60*degToRad)
print "arctan 0.5 in radians = " + atan(0.5)
print "arctan 0.5 in degrees = " + atan(0.5)/degToRad |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #Julia | Julia | tree = Any[1, Any[2, Any[4, Any[7, Any[],
Any[]],
Any[]],
Any[5, Any[],
Any[]]],
Any[3, Any[6, Any[8, Any[],
Any[]],
Any[9, Any[],
Any[]]],
Any[]]]
preorder(t, f) = if !isempty(t)
f(t[1]); preorder(t[2], f); preorder(t[3], f)
end
inorder(t, f) = if !isempty(t)
inorder(t[2], f); f(t[1]); inorder(t[3], f)
end
postorder(t, f) = if !isempty(t)
postorder(t[2], f); postorder(t[3], f); f(t[1])
end
levelorder(t, f) = while !isempty(t)
t = mapreduce(x -> isa(x, Number) ? (f(x); []) : x, vcat, t)
end
|
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lambdatalk | Lambdatalk |
{S.replace , by . in Hello,How,Are,You,Today}.
-> Hello.How.Are.You.Today.
|
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Pike | Pike |
void get_some_primes()
{
int i;
while(i < 10000)
i = i->next_prime();
}
void main()
{
float time_wasted = gauge( get_some_primes() );
write("Wasted %f CPU seconds calculating primes\n", time_wasted);
}
|
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #PL.2FI | PL/I | declare (start_time, finish_time) float (18);
start_time = secs();
do i = 1 to 10000000;
/* something to be repeated goes here. */
end;
finish_time = secs();
put skip edit ('elapsed time=', finish_time - start_time, ' seconds')
(A, F(10,3), A);
/* gives the result to thousandths of a second. */
/* Note: using the SECS function takes into account the clock */
/* going past midnight. */ |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
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
| #Lua | Lua | N = 2
lst = { { "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" }
}
dep = {}
for i = 1, #lst do
if dep[ lst[i][4] ] == nil then
dep[ lst[i][4] ] = {}
dep[ lst[i][4] ][1] = lst[i]
else
dep[ lst[i][4] ][#dep[lst[i][4]]+1] = lst[i]
end
end
for i, _ in pairs( dep ) do
table.sort( dep[i], function (a,b) return a[3] > b[3] end )
print( "Department:", dep[i][1][4] )
for l = 1, math.min( N, #dep[i] ) do
print( "", dep[i][l][1], dep[i][l][2], dep[i][l][3] )
end
print ""
end |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #Lingo | Lingo | global $ -- object representing simple framework
global gBoard -- current board image
global gBoardTemplate -- empty board image
global gHumanChip -- cross image
global gComputerChip -- circle image
global gM -- 3x3 matrix storing game state: 0=free cell, 1=human cell, -1=computer cell
global gStep -- index of current move (1..9)
global gGameOverFlag -- TRUE if current game is over
----------------------------------------
-- Entry point
----------------------------------------
on startMovie
-- libs
$.import("sprite")
-- window properties
_movie.stage.title = "Tic-Tac-Toe"
_movie.stage.rect = rect(0, 0, 224, 310)
_movie.centerStage = TRUE
-- load images from filesystem
m = new(#bitmap)
m.importFileInto($.@("resources/cross.bmp"), [#trimWhiteSpace:FALSE])
gHumanChip = m.image
m = new(#bitmap)
m.importFileInto($.@("resources/circle.bmp"), [#trimWhiteSpace:FALSE])
gComputerChip = m.image
-- create GUI
m = new(#bitmap)
m.importFileInto($.@("resources/board.bmp"))
m.regpoint = point(0, 0)
s = $.sprite.make(m, [#loc:point(20, 20)], TRUE)
s.addListener(#mouseDown, _movie, #humanMove)
gBoard = m.image
gBoardTemplate = gBoard.duplicate()
m = $.sprite.newMember(#button, [#text:"New Game (Human starts)", #fontstyle:"bold", #rect:rect(0, 0, 180, 0)])
s = $.sprite.make(m, [#loc:point(20, 220)], TRUE)
s.addListener(#mouseDown, _movie, #newGame, 1)
m = $.sprite.newMember(#button, [#text:"New Game (Computer starts)", #fontstyle:"bold", #rect:rect(0, 0, 180, 0)])
s = $.sprite.make(m, [#loc:point(20, 250)], TRUE)
s.addListener(#mouseDown, _movie, #newGame, -1)
m = $.sprite.newMember(#field, [#name:"feedback", #editable:FALSE, #fontstyle:"bold", #alignment:"center",\
#border:0, #color:rgb(255, 0, 0), #rect:rect(0, 0, 180, 0)])
s = $.sprite.make(m, [#loc:point(20, 280)], TRUE)
newGame(1)
-- show the application window
_movie.updateStage()
_movie.stage.visible = TRUE
end
----------------------------------------
-- Starts a new game
----------------------------------------
on newGame (whoStarts)
-- reset board
gBoard.copyPixels(gBoardTemplate, gBoardTemplate.rect, gBoardTemplate.rect)
-- clear feedback
member("feedback").text = ""
-- reset states
gM = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
gStep = 0
gGameOverFlag = FALSE
if whoStarts=-1 then computerMove()
end
----------------------------------------
-- Handles a human move (mouse click)
----------------------------------------
on humanMove ()
if gGameOverFlag then return
-- find cell for mouse position
p = _mouse.clickLoc - sprite(1).loc
if p.locH mod 60<4 or p.locV mod 60<4 then return
p = p / 60
x = p[1] + 1
y = p[2] + 1
if gM[x][y] then return -- ignore illegal moves
gM[x][y] = 1
-- update cell image
p = p * 60
gBoard.copyPixels(gHumanChip, gHumanChip.rect.offset(4+p[1], 4+p[2]), gHumanChip.rect)
-- proceed (unless game over)
gStep = gStep + 1
if not checkHumanMove(x, y) then computerMove()
end
----------------------------------------
-- Checks if human has won or game ended with draw
----------------------------------------
on checkHumanMove (x, y)
if sum([gM[x][1], gM[x][2], gM[x][3]])=3 then return gameOver(1, [[x, 1], [x, 2], [x, 3]])
if sum([gM[1][y], gM[2][y], gM[3][y]])=3 then return gameOver(1, [[1, y], [2, y], [3, y]])
if x=y and sum([gM[1][1], gM[2][2], gM[3][3]])=3 then return gameOver(1, [[1, 1], [2, 2], [3, 3]])
if x+y=4 and sum([gM[1][3], gM[2][2], gM[3][1]])=3 then return gameOver(1, [[1, 3], [2, 2], [3, 1]])
if gStep=9 then return gameOver(0)
return FALSE
end
----------------------------------------
-- Checks if selecting specified empty cell makes computer or human win
----------------------------------------
on checkCellWins (x, y, who)
wins = who*2
if sum([gM[1][y], gM[2][y], gM[3][y]]) = wins then return [[1, y], [2, y], [3, y]]
if sum([gM[x][1], gM[x][2], gM[x][3]]) = wins then return [[x, 1], [x, 2], [x, 3]]
if x=y and sum([gM[1][1], gM[2][2], gM[3][3]]) = wins then return [[1, 1], [2, 2], [3, 3]]
if x+y=4 and sum([gM[1][3], gM[2][2], gM[3][1]]) = wins then return [[1, 3], [2, 2], [3, 1]]
return FALSE
end
----------------------------------------
-- Handles game over
----------------------------------------
on gameOver (winner, cells)
gGameOverFlag = TRUE
if winner = 0 then
member("feedback").text = "It's a draw!"
else
-- hilite winning line with yellow
img = image(56, 56, 32)
img.fill(img.rect, rgb(255, 255, 0))
repeat with c in cells
x = (c[1]-1)*60 + 4
y = (c[2]-1)*60 + 4
gBoard.copyPixels(img, img.rect.offset(x, y), img.rect, [#ink:#darkest])
end repeat
member("feedback").text = ["Human", "Computer"][1+(winner=-1)] & " has won!"
end if
return TRUE
end
----------------------------------------
-- Calculates next computer move
----------------------------------------
on computerMove ()
gStep = gStep + 1
-- move 1: select center
if gStep=1 then return doComputerMove(2, 2)
-- move 2 (human started)
if gStep=2 then
if gM[2][2]=1 then
-- if center, select arbitrary corner
return doComputerMove(1, 1)
else
-- otherwise select center
return doComputerMove(2, 2)
end if
end if
-- move 3 (computer started)
if gStep=3 then
-- if corner, select diagonally opposite corner
if gM[1][1]=1 then return doComputerMove(3, 3)
if gM[3][3]=1 then return doComputerMove(1, 1)
if gM[1][3]=1 then return doComputerMove(3, 1)
return doComputerMove(1, 1) -- top left corner as default
end if
-- get free cells
free = []
repeat with x = 1 to 3
repeat with y = 1 to 3
if gM[x][y]=0 then free.add([x, y])
end repeat
end repeat
-- check if computer can win now
repeat with c in free
res = checkCellWins(c[1], c[2], -1)
if res<>FALSE then
doComputerMove(c[1], c[2])
return gameOver(-1, res)
end if
end repeat
-- check if human could win with next move (if yes, prevent it)
repeat with c in free
res = checkCellWins(c[1], c[2], 1)
if res<>FALSE then return doComputerMove(c[1], c[2], TRUE)
end repeat
-- move 4 (human started): prevent "double mills"
if gStep=4 then
if gM[2][2]=1 and (gM[1][1]=1 or gM[3][3]=1) then return doComputerMove(3, 1)
if gM[2][2]=1 and (gM[1][3]=1 or gM[3][1]=1) then return doComputerMove(1, 1)
if gM[2][3]+gM[3][2]=2 then return doComputerMove(3, 3)
if gM[1][2]+gM[2][3]=2 then return doComputerMove(1, 3)
if gM[1][2]+gM[2][1]=2 then return doComputerMove(1, 1)
if gM[2][1]+gM[3][2]=2 then return doComputerMove(3, 1)
if (gM[1][3]+gM[3][1]=2) or (gM[1][1]+gM[3][3]=2) then return doComputerMove(2, 1)
end if
-- move 5 (computer started): try to create a "double mill"
if gStep=5 then
repeat with x = 1 to 3
col = [gM[x][1], gM[x][2], gM[x][3]]
if not (sum(col)=-1 and max(col)=0) then next repeat
repeat with y = 1 to 3
row = [gM[1][y], gM[2][y], gM[3][y]]
if not (sum(row)=-1 and max(row)=0 and gM[x][y]=0) then next repeat
return doComputerMove(x, y)
end repeat
end repeat
end if
-- otherwise use first free cell
c = free[1]
doComputerMove(c[1], c[2])
end
----------------------------------------
-- Updates state matrix and cell image
----------------------------------------
on doComputerMove (x, y, checkDraw)
gM[x][y] = -1
gBoard.copyPixels(gComputerChip, gComputerChip.rect.offset(4+(x-1)*60, 4+(y-1)*60), gComputerChip.rect)
if checkDraw and gStep=9 then gameOver(0)
end
----------------------------------------
--
----------------------------------------
on sum (aLine)
return aLine[1]+aLine[2]+aLine[3]
end |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Elixir | Elixir | defmodule RC do
def hanoi(n) when 0<n and n<10, do: hanoi(n, 1, 2, 3)
defp hanoi(1, f, _, t), do: move(f, t)
defp hanoi(n, f, u, t) do
hanoi(n-1, f, t, u)
move(f, t)
hanoi(n-1, u, f, t)
end
defp move(f, t), do: IO.puts "Move disk from #{f} to #{t}"
end
RC.hanoi(3) |
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #Racket | Racket |
#lang racket
(define G
(make-hash
'((des_system_lib . (std synopsys std_cell_lib des_system_lib dw02
dw01 ramlib ieee))
(dw01 . (ieee dw01 dware gtech))
(dw02 . (ieee dw02 dware))
(dw03 . (std synopsys dware dw03 dw02 dw01 ieee gtech))
(dw04 . (dw04 ieee dw01 dware gtech))
(dw05 . (dw05 ieee dware))
(dw06 . (dw06 ieee dware))
(dw07 . (ieee dware))
(dware . (ieee dware))
(gtech . (ieee gtech))
(ramlib . (std ieee))
(std_cell_lib . (ieee std_cell_lib))
(synopsys . ()))))
(define (clean G)
(define G* (hash-copy G))
(for ([(from tos) G])
; remove self dependencies
(hash-set! G* from (remove from tos))
; make sure all nodes are present in the ht
(for ([to tos]) (hash-update! G* to (λ(_)_) '())))
G*)
(define (incoming G)
(define in (make-hash))
(for* ([(from tos) G] [to tos])
(hash-update! in to (λ(fs) (cons from fs)) '()))
in)
(define (nodes G) (hash-keys G))
(define (out G n) (hash-ref G n '()))
(define (remove! G n m) (hash-set! G n (remove m (out G n))))
(define (topo-sort G)
(define n (length (nodes G)))
(define in (incoming G))
(define (no-incoming? n) (empty? (hash-ref in n '())))
(let loop ([L '()] [S (list->set (filter no-incoming? (nodes G)))])
(cond [(set-empty? S)
(if (= (length L) n)
L
(error 'topo-sort (~a "cycle detected" G)))]
[else
(define n (set-first S))
(define S\n (set-rest S))
(for ([m (out G n)])
(remove! G n m)
(remove! in m n)
(when (no-incoming? m)
(set! S\n (set-add S\n m))))
(loop (cons n L) S\n)])))
(topo-sort (clean G))
|
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | sin С/П Вx cos С/П Вx tg С/П Вx arcsin
С/П Вx arccos С/П Вx arctg С/П
|
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #Kotlin | Kotlin | data class Node(val v: Int, var left: Node? = null, var right: Node? = null) {
override fun toString() = "$v"
}
fun preOrder(n: Node?) {
n?.let {
print("$n ")
preOrder(n.left)
preOrder(n.right)
}
}
fun inorder(n: Node?) {
n?.let {
inorder(n.left)
print("$n ")
inorder(n.right)
}
}
fun postOrder(n: Node?) {
n?.let {
postOrder(n.left)
postOrder(n.right)
print("$n ")
}
}
fun levelOrder(n: Node?) {
n?.let {
val queue = mutableListOf(n)
while (queue.isNotEmpty()) {
val node = queue.removeAt(0)
print("$node ")
node.left?.let { queue.add(it) }
node.right?.let { queue.add(it) }
}
}
}
inline fun exec(name: String, n: Node?, f: (Node?) -> Unit) {
print(name)
f(n)
println()
}
fun main(args: Array<String>) {
val nodes = Array(10) { Node(it) }
nodes[1].left = nodes[2]
nodes[1].right = nodes[3]
nodes[2].left = nodes[4]
nodes[2].right = nodes[5]
nodes[4].left = nodes[7]
nodes[3].left = nodes[6]
nodes[6].left = nodes[8]
nodes[6].right = nodes[9]
exec(" preOrder: ", nodes[1], ::preOrder)
exec(" inorder: ", nodes[1], ::inorder)
exec(" postOrder: ", nodes[1], ::postOrder)
exec("level-order: ", nodes[1], ::levelOrder)
} |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lang5 | Lang5 | 'Hello,How,Are,You,Today ', split '. join . |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #LDPL | LDPL |
DATA:
explode/words is text vector
explode/index is number
explode/string is text
explode/length is number
explode/stringlength is number
explode/current-token is text
explode/char is text
explode/separator is text
i is number
PROCEDURE:
# Ask for a sentence
display "Enter a sentence: "
accept explode/string
# Declare explode Subprocedure
# Splits a text into a text vector by a certain delimiter
# Input parameters:
# - explode/string: the string to explode (destroyed)
# - explode/separator: the character used to separate the string (preserved)
# Output parameters:
# - explode/words: vector of splitted words
# - explode/length: length of explode/words
sub-procedure explode
join explode/string and explode/separator in explode/string
store length of explode/string in explode/stringlength
store 0 in explode/index
store 0 in explode/length
store "" in explode/current-token
while explode/index is less than explode/stringlength do
get character at explode/index from explode/string in explode/char
if explode/char is equal to explode/separator then
store explode/current-token in explode/words:explode/length
add explode/length and 1 in explode/length
store "" in explode/current-token
else
join explode/current-token and explode/char in explode/current-token
end if
add explode/index and 1 in explode/index
repeat
subtract 1 from explode/length in explode/length
end sub-procedure
# Separate the entered string
store " " in explode/separator
call sub-procedure explode
while i is less than or equal to explode/length do
display explode/words:i crlf
add 1 and i in i
repeat
|
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #PowerShell | PowerShell |
function fun($n){
$res = 0
if($n -gt 0) {
1..$n | foreach{
$a, $b = $_, ($n+$_)
$res += $a + $b
}
}
$res
}
"$((Measure-Command {fun 10000}).TotalSeconds) Seconds"
|
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #PureBasic | PureBasic | Procedure Foo(Limit)
Protected i, palindromic, String$
For i=0 To Limit
String$=Str(i)
If String$=ReverseString(String$)
palindromic+1
EndIf
Next
ProcedureReturn palindromic
EndProcedure
If OpenConsole()
Define Start, Stop, cnt
PrintN("Starting timing of a calculation,")
PrintN("for this we test how many of 0-1000000 are palindromic.")
Start=ElapsedMilliseconds()
cnt=Foo(1000000)
Stop=ElapsedMilliseconds()
PrintN("The function need "+Str(stop-Start)+" msec,")
PrintN("and "+Str(cnt)+" are palindromic.")
Print("Press ENTER to exit."): Input()
EndIf |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
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
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
' erase stack of values, so we can add data
Flush
Input "N=",N
Enum Departments {D050,D101,D190,D202}
\\ Inventory Department need unique keys
Inventory Department
\\ each item in this inventory should be an inventory too
Class Empl {
name$, id$, salary
Class:
Module Empl(.name$, .id$, .salary) {}
}
Data "Tyler Bennett","E10297",32000,D101
Data "John Rappl","E21437",47000,D050
Data "George Woltman","E00127",53500,D101
Data "Adam Smith","E63535",18000,D202
Data "Claire Buckman","E39876",27800,D202
Data "David McClellan","E04242",41500,D101
Data "Rich Holcomb","E01234",49500,D202
Data "Nathan Adams","E41298",21900,D050
Data "Richard Potter","E43128",15900,D101
Data "David Motsinger","E27002",19250,D202
Data "Tim Sampair","E03033",27000,D101
Data "Kim Arlich","E10001",57000,D190
Data "Timothy Grove","E16398",29900,D190
Data ""
Read name$
While name$<>"" {
Read id$, salary, dep
Rem : Print name$, id$, salary, dep
If Exist(Department, dep) Then {
z=Eval(Department) ' get pointer to inventory
AppendOne()
} Else {
z=queue
AppendDep()
AppendOne()
}
Read name$
}
Sort Department as number
i=each(Department)
\\ make depname as type of Departments
depname=D050
Print "Dep. Employee Name Emp. ID Salary"
While i {
\\ when we pass a number to a enum variable
\\ if the number exist, get that enum item else raise error
depname=val(eval$(i, i^))
\\ z is a pointer to inventory
z=Eval(i)
Sort descending z as number
k=each(z,1,N)
While k {
Empl=Eval(k)
For Empl {
\\ eval$(depname) return the name of enum variable (like D050)
Print Format$("{0:6}{1:20}{2:8}{3::-8}",Eval$(depname), .name$, .id$, .salary)
}
}
}
Print "Done"
Sub AppendDep()
Append Department, dep:=z
End Sub
Sub AppendOne()
Append z, salary:=Empl(name$, id$, salary)
End Sub
}
Checkit
|
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #Lua | Lua | #!/usr/bin/env luajit
ffi=require"ffi"
local function printf(fmt,...) io.write(string.format(fmt, ...)) end
local board="123456789" -- board
local pval={1, -1} -- player 1=1 2=-1 for negamax
local pnum={} for k,v in ipairs(pval) do pnum[v]=k end
local symbol={'X','O'} -- default symbols X and O
local isymbol={} for k,v in pairs(symbol) do isymbol[v]=pval[k] end
math.randomseed(os.time()^5*os.clock()) -- time-seed the random gen
local random=math.random
-- usage of ffi variables give 20% speed
ffi.cdef[[
typedef struct{
char value;
char flag;
int depth;
}cData;
]]
-- draw the "board" in the way the numpad is organized
local function draw(board)
for i=7,1,-3 do
print(board:sub(i,i+2))
end
end
-- pattern for win situations
local check={"(.)...%1...%1","..(.).%1.%1..",
"(.)%1%1......","...(.)%1%1...","......(.)%1%1",
"(.)..%1..%1..",".(.)..%1..%1.","..(.)..%1..%1",
}
-- calculate a win situation for which player or draw
local function win(b)
local sub
for i=1,#check do
sub=b:match(check[i])
if sub then break end
end
sub=isymbol[sub]
return sub or 0
end
-- input only validate moves of not yet filled positions
local function input(b,player)
char=symbol[pnum[player]]
local inp
repeat
printf("Player %d (\"%s\") move: ",pnum[player],char)
inp=tonumber(io.read()) or 0
until inp>=1 and inp<=9 and b:find(inp)
b=b:gsub(inp,char)
return b,inp
end
-- ask how many human or AI players
local function playerselect()
local ai={}
local yn
for i=1,2 do
repeat
printf("Player %d human (Y/n)? ", i) yn=io.read():lower()
until yn:match("[yn]") or yn==''
if yn=='n' then
ai[pval[i]]=true
printf("Player %d is AI\n", i)
else
printf("Player %d is human\n", i)
end
end
return ai
end
local function endgame()
repeat
printf("\nEnd game? (y/n)? ", i) yn=io.read():lower()
until yn:match("[yn]")
if yn=='n' then
return false
else
printf("\nGOOD BYE PROFESSOR FALKEN.\n\nA STRANGE GAME.\nTHE ONLY WINNING MOVE IS\nNOT TO PLAY.\n\nHOW ABOUT A NICE GAME OF CHESS?\n")
return true
end
end
-- AI Routine
local function shuffle(t)
for i=#t,1,-1 do
local rnd=random(i)
t[i], t[rnd] = t[rnd], t[i]
end
return t
end
-- move generator
local function genmove(node, color)
return coroutine.wrap(function()
local moves={}
for m in node:gmatch("%d") do
moves[#moves+1]=m
end
shuffle(moves) -- to make it more interesting
for _,m in ipairs(moves) do
local child=node:gsub(m,symbol[pnum[color]])
coroutine.yield(child, m)
end
end)
end
--[[
Negamax with alpha-beta pruning and table caching
]]
local cache={}
local best, aimove, tDepth
local LOWERB,EXACT,UPPERB=-1,0,1 -- has somebody an idea how to make them real constants?
local function negamax(node, depth, color, α, β)
color=color or 1
α=α or -math.huge
β=β or math.huge
-- check for cached node
local αOrg=α
local cData=cache[node]
if cData and cData.depth>=depth and depth~=tDepth then
if cData.flag==EXACT then
return cData.value
elseif cData.flag==LOWERB then
α=math.max(α,cData.value)
elseif cData.flag==UPPERB then
β=math.min(β,cData.value)
end
if α>=β then
return cData.value
end
end
local winner=win(node)
if depth==0 or winner~=0 then
return winner*color
end
local value=-math.huge
for child,move in genmove(node, color) do
value=math.max(value, -negamax(child, depth-1, -color, -β, -α))
if value>α then
α=value
if depth==tDepth then
best=child
aimove=move
end
end
if α>=β then break end
end
-- cache known data
--cData={} -- if you want Lua tables instead of ffi you can switch the two lines here, costs 20% speed
cData=ffi.new("cData")
cData.value=value
if value<=αOrg then
cData.flag=UPPERB
elseif value>=β then
cData.flag=LOWERB
else
cData.flag=EXACT
end
cData.depth=depth
cache[node]=cData
return α
end
-- MAIN
do
local winner,value
local score={[-1]=0, [0]=0, [1]=0}
repeat
print("\n TIC-TAC-TOE\n")
local aiplayer=playerselect()
local player=1
board="123456789"
for i=1,#board do
draw(board)
tDepth=10-i
if aiplayer[player] then
negamax(board, tDepth, player, -math.huge, math.huge)
board=best
printf("AI %d moves %s\n", pnum[player], aimove)
else
board=input(board,player)
end
winner=win(board)
if winner~=0 then break end
player=-player
end
score[winner]=score[winner]+1
if winner and winner~=0 then
printf("*** Player %d (%s) has won\n", pnum[winner], symbol[pnum[winner]])
else
printf("*** No winner\n")
end
printf("Score Player 1: %d Player 2: %d Draw: %d\n",score[1],score[-1],score[0])
draw(board)
until endgame()
end |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Emacs_Lisp | Emacs Lisp | (defun move (n from to via)
(if (= n 1)
(message "Move from %S to %S" from to)
(move (- n 1) from via to)
(message "Move from %S to %S" from to)
(move (- n 1) via to from))) |
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #Raku | Raku | sub print_topo_sort ( %deps ) {
my %ba;
for %deps.kv -> $before, @afters {
for @afters -> $after {
%ba{$before}{$after} = 1 if $before ne $after;
%ba{$after} //= {};
}
}
while %ba.grep( not *.value )».key -> @afters {
say [email protected];
%ba{@afters}:delete;
for %ba.values { .{@afters}:delete }
}
say %ba ?? "Cycle found! {%ba.keys.sort}" !! '---';
}
my %deps =
des_system_lib => < std synopsys std_cell_lib des_system_lib dw02
dw01 ramlib ieee >,
dw01 => < ieee dw01 dware gtech >,
dw02 => < ieee dw02 dware >,
dw03 => < std synopsys dware dw03 dw02 dw01 ieee gtech >,
dw04 => < dw04 ieee dw01 dware gtech >,
dw05 => < dw05 ieee dware >,
dw06 => < dw06 ieee dware >,
dw07 => < ieee dware >,
dware => < ieee dware >,
gtech => < ieee gtech >,
ramlib => < std ieee >,
std_cell_lib => < ieee std_cell_lib >,
synopsys => < >;
print_topo_sort(%deps);
%deps<dw01> = <ieee dw01 dware gtech dw04>; # Add unresolvable dependency
print_topo_sort(%deps); |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #Modula-2 | Modula-2 | MODULE Trig;
FROM RealMath IMPORT pi,sin,cos,tan,arctan,arccos,arcsin;
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE WriteReal(v : REAL);
VAR buf : ARRAY[0..31] OF CHAR;
BEGIN
RealToStr(v, buf);
WriteString(buf)
END WriteReal;
VAR theta : REAL;
BEGIN
theta := pi / 4.0;
WriteString("theta: ");
WriteReal(theta);
WriteLn;
WriteString("sin: ");
WriteReal(sin(theta));
WriteLn;
WriteString("cos: ");
WriteReal(cos(theta));
WriteLn;
WriteString("tan: ");
WriteReal(tan(theta));
WriteLn;
WriteString("arcsin: ");
WriteReal(arcsin(sin(theta)));
WriteLn;
WriteString("arccos: ");
WriteReal(arccos(cos(theta)));
WriteLn;
WriteString("arctan: ");
WriteReal(arctan(tan(theta)));
WriteLn;
ReadChar
END Trig. |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #Lambdatalk | Lambdatalk | - {W.equal? word1 word2} returns true or false
- {S.replace rex by exp1 in exp2}
replaces a regular expression by some expression in another one
- {S.sort comp words} sorts the sequence of words according to comp
- {A.new words} creates a new array from the sequence of words
- {A.get index array} gets the value of array at index
|
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #LFE | LFE |
> (set split (string:tokens "Hello,How,Are,You,Today" ","))
("Hello" "How" "Are" "You" "Today")
> (string:join split ".")
"Hello.How.Are.You.Today"
|
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lingo | Lingo | input = "Hello,How,Are,You,Today"
_player.itemDelimiter = ","
output = ""
repeat with i = 1 to input.item.count
put input.item[i]&"." after output
end repeat
delete the last char of output
put output
-- "Hello.How.Are.You.Today" |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Python | Python | import sys, timeit
def usec(function, arguments):
modname, funcname = __name__, function.__name__
timer = timeit.Timer(stmt='%(funcname)s(*args)' % vars(),
setup='from %(modname)s import %(funcname)s; args=%(arguments)r' % vars())
try:
t, N = 0, 1
while t < 0.2:
t = min(timer.repeat(repeat=3, number=N))
N *= 10
microseconds = round(10000000 * t / N, 1) # per loop
return microseconds
except:
timer.print_exc(file=sys.stderr)
raise
from math import pow
def nothing(): pass
def identity(x): return x |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #R | R | # A task
foo <- function()
{
for(i in 1:10)
{
mat <- matrix(rnorm(1e6), nrow=1e3)
mat^-0.5
}
}
# Time the task
timer <- system.time(foo())
# Extract the processing time
timer["user.self"] |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | InitialList ={{"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"}};
TrimmedList=Map[ If[Length[#]>3,Take[#,3],#]& ,
Map[Reverse[SortBy[#,#[[3]]&]]&,GatherBy[InitialList,Last]]
];
Scan[((Print["Department ",#[[1,4]],"\n","Employee","\t","Id","\t","Salary"]&[#])&[#];
(Scan[Print[#[[1]],"\t",#[[2]],"\t",#[[3]]]&,#] )& [#])&,TrimmedList] |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #M2000_Interpreter | M2000 Interpreter |
Module Tic.Tac.Toe {
Dim Board$(1 to 3, 1 to 3)=" "
WinGame=False
p=Board$()
RandomPosition=lambda -> {
=(random(1,3), random(1,3))
}
BoardItemEmpty=Lambda p (x, y) -> {
=Array$(p, x, y)=" "
}
BoardSetItem=Lambda p (x, y, w$) -> {
link p to a$()
a$(x, y)=w$
}
T=9
R=0
C=0
Repeat {
Print "Computer Move:"
CompMove()
T--
DrawBoard()
CheckWin()
if WinGame Then Print "Computer Win": Exit
if T=0 then exit
Repeat {
GetRowCol("Input Row", &R)
GetRowCol("Input Column", &C)
If BoardItemEmpty(R,C) then call boardsetitem(R,C,"O") : exit
} Always
T--
DrawBoard()
CheckWin()
if WinGame Then Print "You Win": Exit
} until T=0 or WinGame
Sub DrawBoard()
Print "R/C 1 2 3"
Print " 1) "; Board$(1,1);"|";Board$(1,2);"|";Board$(1,3)
Print " -+-+-"
Print " 2) "; Board$(2,1);"|";Board$(2,2);"|";Board$(2,3)
Print " -+-+-"
Print " 3) "; Board$(3,1);"|";Board$(3,2);"|";Board$(3,3)
End Sub
Sub CheckWin()
WinGame=false
local i,j,three$
For i=1 to 3
three$=""
For j=1 to 3 : three$+=Board$(i,j) : Next j
CheckThree()
three$=""
For j=1 to 3 : three$+=Board$(j,i) :Next j
CheckThree()
Next i
three$=""
For i=1 to 3 : three$+=Board$(i,i): Next i
CheckThree()
three$=""
For i=1 to 3:three$+=Board$(i,4-i): Next i
CheckThree()
End Sub
Sub CheckThree()
if instr(three$," ")=0 then WinGame=WinGame or Filter$(three$, left$(three$,1))=""
End Sub
Sub CompMove()
if T<9 and Board$(2,2)=" " then {
call boardsetitem(2,2,"X")
} Else {
local i=3, j=3, found=false
if T<=6 then {
CompThink("X","X")
}
let i=3, j=3
If Not found And T<6 then {
CompThink("O","X")
}
If not found then {
Repeat {
comp=RandomPosition()
If BoardItemEmpty(!comp) then call boardsetitem(!comp, "X") : exit
} Always
}
}
End Sub
Sub CompThink(Bad$, Good$)
While i>0 {
j=3
While j>0 {
if Board$(i,j)=" " then {
Board$(i,j)=Bad$
CheckWin()
if WinGame then {
Board$(i,j)=Good$:i=0:j=0: found=true
} Else Board$(i,j)=" "
}
j--
}
i--
}
End Sub
Sub GetRowCol(What$, &W)
Print What$;":";
Repeat {
W=Val("0"+Key$)
} until W>=1 and W<=3
Print Str$(W,"")
End Sub
}
Tic.Tac.Toe
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Erlang | Erlang | move(1, F, T, _V) ->
io:format("Move from ~p to ~p~n", [F, T]);
move(N, F, T, V) ->
move(N-1, F, V, T),
move(1 , F, T, V),
move(N-1, V, T, F). |
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #REXX | REXX | /*REXX pgm does a topological sort (orders such that no item precedes a dependent item).*/
iDep.= 0; iPos.= 0; iOrd.= 0 /*initialize some stemmed arrays to 0.*/
nL= 15; nd= 44; nc= 69 /* " " "parms" and indices.*/
label= 'DES_SYSTEM_LIB DW01 DW02 DW03 DW04 DW05 DW06 DW07' ,
'DWARE GTECH RAMLIB STD_CELL_LIB SYNOPSYS STD IEEE'
iCode= 1 14 13 12 1 3 2 11 15 0 2 15 2 9 10 0 3 15 3 9 0 4 14 213 9 4 3 2 15 10 0 5 5 15 ,
2 9 10 0 6 6 15 9 0 7 7 15 9 0 8 15 9 0 39 15 9 0 10 15 10 0 11 14 15 0 12 15 12 0 0
j= 0
do i=1
iL= word(iCode, i); if iL==0 then leave
do forever; i= i+1
iR= word(iCode, i); if iR==0 then leave
j= j+1; iDep.j.1= iL
iDep.j.2= iR
end /*forever*/
end /*i*/
call tSort
say '═══compile order═══'
@= 'libraries found.)'
#=0; do o=nO by -1 for nO; #= #+1; say word(label, iOrd.o)
end /*o*/; if #==0 then #= 'no'
say ' ('# @; say
say '═══unordered libraries═══'
#=0; do u=nO+1 to nL; #= #+1; say word(label, iOrd.u)
end /*u*/; if #==0 then #= 'no'
say ' ('# "unordered" @
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
tSort: procedure expose iDep. iOrd. iPos. nd nL nO
do i=1 for nL; iOrd.i= i; iPos.i= i
end /*i*/
k= 1
do until k<=j; j = k; k= nL+1
do i=1 for nd; iL = iDep.i.1; iR= iPos.iL
ipL= iPos.iL; ipR= iPos.iR
if iL==iR | ipL>.k | ipL<j | ipR<j then iterate
k= k-1
_= iOrd.k; iPos._ = ipL
iPos.iL= k
iOrd.ipL= iOrd.k; iOrd.k = iL
end /*i*/
end /*until*/
nO= j-1; return |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary utf8
numeric digits 30
parse 'Radians Degrees angle' RADIANS DEGREES ANGLE .;
parse 'sine cosine tangent arcsine arccosine arctangent' SINE COSINE TANGENT ARCSINE ARCCOSINE ARCTANGENT .
trigVals = ''
trigVals[RADIANS, ANGLE ] = (Rexx Math.PI) / 4 -- Pi/4 == 45 degrees
trigVals[DEGREES, ANGLE ] = 45.0
trigVals[RADIANS, SINE ] = (Rexx Math.sin(trigVals[RADIANS, ANGLE]))
trigVals[DEGREES, SINE ] = (Rexx Math.sin(Math.toRadians(trigVals[DEGREES, ANGLE])))
trigVals[RADIANS, COSINE ] = (Rexx Math.cos(trigVals[RADIANS, ANGLE]))
trigVals[DEGREES, COSINE ] = (Rexx Math.cos(Math.toRadians(trigVals[DEGREES, ANGLE])))
trigVals[RADIANS, TANGENT ] = (Rexx Math.tan(trigVals[RADIANS, ANGLE]))
trigVals[DEGREES, TANGENT ] = (Rexx Math.tan(Math.toRadians(trigVals[DEGREES, ANGLE])))
trigVals[RADIANS, ARCSINE ] = (Rexx Math.asin(trigVals[RADIANS, SINE]))
trigVals[DEGREES, ARCSINE ] = (Rexx Math.toDegrees(Math.acos(trigVals[DEGREES, SINE])))
trigVals[RADIANS, ARCCOSINE ] = (Rexx Math.acos(trigVals[RADIANS, COSINE]))
trigVals[DEGREES, ARCCOSINE ] = (Rexx Math.toDegrees(Math.acos(trigVals[DEGREES, COSINE])))
trigVals[RADIANS, ARCTANGENT] = (Rexx Math.atan(trigVals[RADIANS, TANGENT]))
trigVals[DEGREES, ARCTANGENT] = (Rexx Math.toDegrees(Math.atan(trigVals[DEGREES, TANGENT])))
say ' '.right(12)'|' RADIANS.right(17) '|' DEGREES.right(17) '|'
say ANGLE.right(12)'|' trigVals[RADIANS, ANGLE ].format(4, 12) '|' trigVals[DEGREES, ANGLE ].format(4, 12) '|'
say SINE.right(12)'|' trigVals[RADIANS, SINE ].format(4, 12) '|' trigVals[DEGREES, SINE ].format(4, 12) '|'
say COSINE.right(12)'|' trigVals[RADIANS, COSINE ].format(4, 12) '|' trigVals[DEGREES, COSINE ].format(4, 12) '|'
say TANGENT.right(12)'|' trigVals[RADIANS, TANGENT ].format(4, 12) '|' trigVals[DEGREES, TANGENT ].format(4, 12) '|'
say ARCSINE.right(12)'|' trigVals[RADIANS, ARCSINE ].format(4, 12) '|' trigVals[DEGREES, ARCSINE ].format(4, 12) '|'
say ARCCOSINE.right(12)'|' trigVals[RADIANS, ARCCOSINE ].format(4, 12) '|' trigVals[DEGREES, ARCCOSINE ].format(4, 12) '|'
say ARCTANGENT.right(12)'|' trigVals[RADIANS, ARCTANGENT].format(4, 12) '|' trigVals[DEGREES, ARCTANGENT].format(4, 12) '|'
say
return
|
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #Lingo | Lingo | -- parent script "BinaryTreeNode"
property _val, _left, _right
on new (me, val)
me._val = val
return me
end
on getValue (me)
return me._val
end
on setLeft (me, node)
me._left = node
end
on setRight (me, node)
me._right = node
end
on getLeft (me)
return me._left
end
on getRight (me)
return me._right
end |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Logo | Logo | to split :str :sep
output parse map [ifelse ? = :sep ["| |] [?]] :str
end |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Logtalk | Logtalk |
:- object(spliting).
:- public(convert/2).
:- mode(convert(+atom, -atom), one).
convert(StringIn, StringOut) :-
atom_chars(StringIn, CharactersIn),
phrase(split(',', Tokens), CharactersIn),
phrase(split('.', Tokens), CharactersOut),
atom_chars(StringOut, CharactersOut).
split(Separator, [t([Character| Characters])| Tokens]) -->
[Character], {Character \== Separator}, split(Separator, [t(Characters)| Tokens]).
split(Separator, [t([])| Tokens]) -->
[Separator], split(Separator, Tokens).
split(_, [t([])]) -->
[].
% the look-ahead in the next rule prevents adding a spurious separator at the end
split(_, []), [Character] -->
[Character].
:- end_object.
|
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Racket | Racket |
#lang racket
(define (fact n) (if (zero? n) 1 (* n (fact (sub1 n)))))
(time (fact 5000))
|
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Raku | Raku | my $start = now;
(^100000).pick(1000);
say now - $start; |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
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
| #Nim | Nim | import algorithm
type Record = tuple[name, id: string; salary: int; department: string]
var people = [("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")]
proc pcmp(a, b: Record): int =
result = cmp(a.department, b.department)
if result == 0:
result = cmp(b.salary, a.salary)
proc printTop(people: openArray[Record]; n: Positive) =
var people = sorted(people, pcmp)
var rank = 0
for i, p in people:
if i > 0 and p.department != people[i-1].department:
rank = 0
echo()
if rank < n:
echo p.department, " ", p.salary, " ", p.name
inc rank
people.printTop(2) |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | DynamicModule[{board = ConstantArray[0, {3, 3}], text = "Playing...",
first, rows =
Join[#, Transpose@#, {Diagonal@#, Diagonal@Reverse@#}] &},
Column@{Graphics[{Thickness[.02],
Table[With[{i = i, j = j},
Button[{White, Rectangle[{i, j} - 1, {i, j}], Black,
Dynamic[Switch[board[[i, j]], 0, Black, 1,
Circle[{i, j} - .5, .3], -1,
Line[{{{i, j} - .2, {i, j} - .8}, {{i - .2,
j - .8}, {i - .8, j - .2}}}]]]},
Which[text != "Playing...", board = ConstantArray[0, {3, 3}];
text = "Playing...", board[[i, j]] == 0,
If[board == ConstantArray[0, {3, 3}],
first = {i,
j} /. {{2, 2} -> 1, {1 | 3, 1 | 3} -> 2, _ -> 3}];
board[[i, j]] = 1;
FinishDynamic[];
Which[MemberQ[rows[board], {1, 1, 1}], text = "You win.",
FreeQ[board, 0], text = "Draw.", True,
board[[Sequence @@
SortBy[Select[Tuples[{Range@3, Range@3}],
board[[Sequence @@ #]] ==
0 &], -Total[
Sort /@
rows[ReplacePart[
board, # -> -1]] /. {{-1, -1, -1} ->
512, {-1, 1, 1} -> 64, {-1, -1, 0} ->
8, {0, 1, 1} -> -1, {_, _, _} -> 0}] -
Switch[#, {2, 2}, 1, {1 | 3, 1 | 3},
If[first == 2, -1, 0], _,
If[first == 2, 0, -1]] &][[1]]]] = -1;
Which[MemberQ[rows[board], {-1, -1, -1}],
text = "You lost.", FreeQ[board, 0],
text = "Draw."]]]]], {i, 1, 3}, {j, 1, 3}], Thickness[.01],
Line[{{{1, 0}, {1, 3}}, {{2, 0}, {2, 3}}, {{0, 1}, {3, 1}}, {{0,
2}, {3, 2}}}]}], Dynamic@text}] |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #ERRE | ERRE |
!-----------------------------------------------------------
! HANOI.R : solve tower of Hanoi puzzle using a recursive
! modified algorithm.
!-----------------------------------------------------------
PROGRAM HANOI
!$INTEGER
!VAR I,J,MOSSE,NUMBER
PROCEDURE PRINTMOVE
LOCAL SOURCE$,DEST$
MOSSE=MOSSE+1
CASE I OF
1-> SOURCE$="Left" END ->
2-> SOURCE$="Center" END ->
3-> SOURCE$="Right" END ->
END CASE
CASE J OF
1-> DEST$="Left" END ->
2-> DEST$="Center" END ->
3-> DEST$="Right" END ->
END CASE
PRINT("I move a disk from ";SOURCE$;" to ";DEST$)
END PROCEDURE
PROCEDURE MOVE
IF NUMBER<>0 THEN
NUMBER=NUMBER-1
J=6-I-J
MOVE
J=6-I-J
PRINTMOVE
I=6-I-J
MOVE
I=6-I-J
NUMBER=NUMBER+1
END IF
END PROCEDURE
BEGIN
MAXNUM=12
MOSSE=0
PRINT(CHR$(12);TAB(25);"--- TOWERS OF HANOI ---")
REPEAT
PRINT("Number of disks ";)
INPUT(NUMBER)
UNTIL NUMBER>1 AND NUMBER<=MAXNUM
PRINT
PRINT("For ";NUMBER;"disks the total number of moves is";2^NUMBER-1)
I=1 ! number of source pole
J=3 ! number of destination pole
MOVE
END PROGRAM
|
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #Ruby | Ruby | require 'tsort'
class Hash
include TSort
alias tsort_each_node each_key
def tsort_each_child(node, &block)
fetch(node).each(&block)
end
end
depends = {}
DATA.each do |line|
key, *libs = line.split
depends[key] = libs
libs.each {|lib| depends[lib] ||= []}
end
begin
p depends.tsort
depends["dw01"] << "dw04"
p depends.tsort
rescue TSort::Cyclic => e
puts "\ncycle detected: #{e}"
end
__END__
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #Nim | Nim | import math, strformat
let rad = Pi/4
let deg = 45.0
echo &"Sine: {sin(rad):.10f} {sin(degToRad(deg)):13.10f}"
echo &"Cosine : {cos(rad):.10f} {cos(degToRad(deg)):13.10f}"
echo &"Tangent: {tan(rad):.10f} {tan(degToRad(deg)):13.10f}"
echo &"Arcsine: {arcsin(sin(rad)):.10f} {radToDeg(arcsin(sin(degToRad(deg)))):13.10f}"
echo &"Arccosine: {arccos(cos(rad)):.10f} {radToDeg(arccos(cos(degToRad(deg)))):13.10f}"
echo &"Arctangent: {arctan(tan(rad)):.10f} {radToDeg(arctan(tan(degToRad(deg)))):13.10f}"
|
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #Logo | Logo | ; nodes are [data left right], use "first" to get data
to node.left :node
if empty? butfirst :node [output []]
output first butfirst :node
end
to node.right :node
if empty? butfirst :node [output []]
if empty? butfirst butfirst :node [output []]
output first butfirst butfirst :node
end
to max :a :b
output ifelse :a > :b [:a] [:b]
end
to tree.depth :tree
if empty? :tree [output 0]
output 1 + max tree.depth node.left :tree tree.depth node.right :tree
end
to pre.order :tree :action
if empty? :tree [stop]
invoke :action first :tree
pre.order node.left :tree :action
pre.order node.right :tree :action
end
to in.order :tree :action
if empty? :tree [stop]
in.order node.left :tree :action
invoke :action first :tree
in.order node.right :tree :action
end
to post.order :tree :action
if empty? :tree [stop]
post.order node.left :tree :action
post.order node.right :tree :action
invoke :action first :tree
end
to at.depth :n :tree :action
if empty? :tree [stop]
ifelse :n = 1 [invoke :action first :tree] [
at.depth :n-1 node.left :tree :action
at.depth :n-1 node.right :tree :action
]
end
to level.order :tree :action
for [i 1 [tree.depth :tree]] [at.depth :i :tree :action]
end
make "tree [1 [2 [4 [7]]
[5]]
[3 [6 [8]
[9]]]]
pre.order :tree [(type ? "| |)] (print)
in.order :tree [(type ? "| |)] (print)
post.order :tree [(type ? "| |)] (print)
level.order :tree [(type ? "| |)] (print) |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lua | Lua | function string:split (sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
local str = "Hello,How,Are,You,Today"
print(table.concat(str:split(","), ".")) |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Function Tokenize$(s){
\\ letter$ pop a string from stack of values
\\ shift 2 swap top two values on stack of values
fold1=lambda m=1 ->{
shift 2 :if m=1 then m=0:drop: push letter$ else push letter$+"."+letter$
}
=s#fold$(fold1)
}
Print Tokenize$(piece$("Hello,How,Are,You,Today",",")) ="Hello.How.Are.You.Today" ' true
}
Checkit
|
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Raven | Raven | define doId use $x
$x dup * $x /
define doPower use $v, $p
$v $p pow
define doSort
group
20000 each choose
list sort reverse
define timeFunc use $fName
time as $t1
$fName "" prefer call
time as $t2
$fName $t2 $t1 -"%.4g secs for %s\n" print
"NULL" timeFunc
42 "doId" timeFunc
12 2 "doPower" timeFunc
"doSort" timeFunc |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Retro | Retro | : .runtime ( a- ) time [ do time ] dip - "\n%d\n" puts ;
: test 20000 [ putn space ] iterd ;
&test .runtime |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #REXX | REXX | /*REXX program displays the elapsed time for a REXX function (or subroutine). */
arg reps . /*obtain an optional argument from C.L.*/
if reps=='' then reps=100000 /*Not specified? No, then use default.*/
call time 'Reset' /*only the 1st character is examined. */
junk = silly(reps) /*invoke the SILLY function (below). */
/*───► CALL SILLY REPS also works.*/
/* The E is for elapsed time.*/
/* │ ─ */
/* ┌────◄───┘ */
/* │ */
/* ↓ */
say 'function SILLY took' format(time("E"),,2) 'seconds for' reps "iterations."
/* ↑ */
/* │ */
/* ┌────────►───────┘ */
/* │ */
/* The above 2 for the FORMAT function displays the time with*/
/* two decimal digits (rounded) past the decimal point). Using */
/* a 0 (zero) would round the time to whole seconds. */
exit /*stick a fork in it, we're all done. */
/*────────────────────────────────────────────────────────────────────────────*/
silly: procedure /*chew up some CPU time doing some silly stuff.*/
do j=1 for arg(1) /*wash, apply, lather, rinse, repeat. ··· */
@.j=random() date() time() digits() fuzz() form() xrange() queued()
end /*j*/
return j-1 |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
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
| #OCaml | OCaml | open StdLabels
let to_string (name,_,s,_) = (Printf.sprintf "%s (%d)" name s)
let take n li =
let rec aux i acc = function
| _ when i >= n -> (List.rev acc)
| [] -> (List.rev acc)
| x::xs -> aux (succ i) (x::acc) xs
in
aux 0 [] li ;;
let toprank data n =
let len = List.length data in
let h = Hashtbl.create len in
List.iter data ~f:(fun ((_,_,_,dep) as employee) ->
Hashtbl.add h dep employee);
let deps =
List.fold_left data ~init:[] ~f:
(fun ac (_,_,_,v) -> if List.mem v ac then ac else v::ac) in
let f dep =
Printf.printf "Department: %s\n " dep;
let l = Hashtbl.find_all h dep in
let l2 = List.sort (fun (_,_,v1,_) (_,_,v2,_) -> compare v2 v1) l in
let l3 = (take n l2) in
print_endline(String.concat ", " (List.map to_string l3));
print_newline()
in
List.iter f deps;
;;
let data = [
"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";
]
let () =
toprank data 3;
;; |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #MATLAB | MATLAB | function TicTacToe
% Set up the board (one for each player)
boards = false(3, 3, 2); % Players' pieces
rep = [' 1 | 4 | 7' ; ' 2 | 5 | 8' ; ' 3 | 6 | 9'];
% Prompt user with options
fprintf('Welcome to Tic-Tac-Toe!\n')
nHumans = str2double(input('Enter the number of human players: ', 's'));
if isnan(nHumans) || ceil(nHumans) ~= nHumans || nHumans < 1 || nHumans > 2
nHumans = 0;
pHuman = false(2, 1);
elseif nHumans == 1
humanFirst = input('Would the human like to go first (Y/N)? ', 's');
if length(humanFirst) == 1 && lower(humanFirst) == 'n'
pHuman = [false ; true];
else
pHuman = [true ; false];
end
else
pHuman = true(2, 1);
end
if any('o' == input('Should Player 1 use X or O? ', 's'))
marks = 'OX';
else
marks = 'XO';
end
fprintf('So Player 1 is %shuman and %cs and Player 2 is %shuman and %cs.\n', ...
char('not '.*~pHuman(1)), marks(1), char('not '.*~pHuman(2)), marks(2))
if nHumans > 0
fprintf('Select the space to mark by entering the space number.\n')
fprintf('No entry will quit the game.\n')
end
% Play game
gameOver = false;
turn = 1;
while ~gameOver
fprintf('\n')
disp(rep)
fprintf('\n')
if pHuman(turn)
[move, isValid, isQuit] = GetMoveFromPlayer(turn, boards);
gameOver = isQuit;
else
move = GetMoveFromComputer(turn, boards);
fprintf('Player %d chooses %d\n', turn, move)
isValid = true;
isQuit = false;
end
if isValid && ~isQuit
[r, c] = ind2sub([3 3], move);
boards(r, c, turn) = true;
rep(r, 4*c) = marks(turn);
if CheckWin(boards(:, :, turn))
gameOver = true;
fprintf('\n')
disp(rep)
fprintf('\nPlayer %d wins!\n', turn)
elseif CheckDraw(boards)
gameOver = true;
fprintf('\n')
disp(rep)
fprintf('\nCat''s game!\n')
end
turn = ~(turn-1)+1;
end
end
end
function [move, isValid, isQuit] = GetMoveFromPlayer(pNum, boards)
% move - 1-9 indicating move position, 0 if invalid move
% isValid - logical indicating if move was valid, true if quitting
% isQuit - logical indicating if player wishes to quit game
p1 = boards(:, :, 1);
p2 = boards(:, :, 2);
moveStr = input(sprintf('Player %d: ', pNum), 's');
if isempty(moveStr)
fprintf('Play again soon!\n')
move = 0;
isValid = true;
isQuit = true;
else
move = str2double(moveStr);
isQuit = false;
if isnan(move) || move < 1 || move > 9 || p1(move) || p2(move)
fprintf('%s is an invalid move.\n', moveStr)
isQuit = 0;
isValid = false;
else
isValid = true;
end
end
end
function move = GetMoveFromComputer(pNum, boards)
% pNum - 1-2 player number
% boards - 3x3x2 logical array where pBoards(:,:,1) is player 1's marks
% Assumes that it is possible to make a move
if ~any(boards(:)) % Play in the corner for first move
move = 1;
else % Use Newell and Simon's "rules to win"
pMe = boards(:, :, pNum);
pThem = boards(:, :, ~(pNum-1)+1);
possMoves = find(~(pMe | pThem)).';
% Look for a winning move
move = FindWin(pMe, possMoves);
if move
return
end
% Look to block opponent from winning
move = FindWin(pThem, possMoves);
if move
return
end
% Look to create a fork (two non-blocked lines of two)
for m = possMoves
newPMe = pMe;
newPMe(m) = true;
if CheckFork(newPMe, pThem)
move = m;
return
end
end
% Look to make two in a row so long as it doesn't force opponent to fork
notGoodMoves = false(size(possMoves));
for m = possMoves
newPMe = pMe;
newPMe(m) = true;
if CheckPair(newPMe, pThem)
nextPossMoves = possMoves;
nextPossMoves(nextPossMoves == m) = [];
theirMove = FindWin(newPMe, nextPossMoves);
newPThem = pThem;
newPThem(theirMove) = true;
if ~CheckFork(newPThem, newPMe)
move = m;
return
else
notGoodMoves(possMoves == m) = true;
end
end
end
possMoves(notGoodMoves) = [];
% Play the center if available
if any(possMoves == 5)
move = 5;
return
end
% Play the opposite corner of the opponent's piece if available
corners = [1 3 7 9];
move = intersect(possMoves, ...
corners(~(pMe(corners) | pThem(corners)) & pThem(fliplr(corners))));
if ~isempty(move)
move = move(1);
return
end
% Play an empty corner if available
move = intersect(possMoves, corners);
if move
move = move(1);
return
end
% Play an empty side if available
sides = [2 4 6 8];
move = intersect(possMoves, sides);
if move
move = move(1);
return
end
% No good moves, so move randomly
possMoves = find(~(pMe | pThem));
move = possMoves(randi(length(possMoves)));
end
end
function move = FindWin(board, possMoves)
% board - 3x3 logical representing one player's pieces
% move - integer indicating position to move to win, or 0 if no winning move
for m = possMoves
newPMe = board;
newPMe(m) = true;
if CheckWin(newPMe)
move = m;
return
end
end
move = 0;
end
function win = CheckWin(board)
% board - 3x3 logical representing one player's pieces
% win - logical indicating if that player has a winning board
win = any(all(board)) || any(all(board, 2)) || ...
all(diag(board)) || all(diag(fliplr(board)));
end
function fork = CheckFork(p1, p2)
% fork - logical indicating if player 1 has created a fork unblocked by player 2
fork = sum([sum(p1)-sum(p2) (sum(p1, 2)-sum(p2, 2)).' ...
sum(diag(p1))-sum(diag(p2)) ...
sum(diag(fliplr(p1)))-sum(diag(fliplr(p2)))] == 2) > 1;
end
function pair = CheckPair(p1, p2)
% pair - logical indicating if player 1 has two in a line unblocked by player 2
pair = any([sum(p1)-sum(p2) (sum(p1, 2)-sum(p2, 2)).' ...
sum(diag(p1))-sum(diag(p2)) ...
sum(diag(fliplr(p1)))-sum(diag(fliplr(p2)))] == 2);
end
function draw = CheckDraw(boards)
% boards - 3x3x2 logical representation of all players' pieces
draw = all(all(boards(:, :, 1) | boards(:, :, 2)));
end |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Excel | Excel | SHOWHANOI
=LAMBDA(n,
FILTERP(
LAMBDA(x, "" <> x)
)(
HANOI(n)("left")("right")("mid")
)
)
HANOI
=LAMBDA(n,
LAMBDA(l,
LAMBDA(r,
LAMBDA(m,
IF(0 = n,
"",
LET(
next, n - 1,
APPEND(
APPEND(
HANOI(next)(l)(m)(r)
)(
CONCAT(l, " -> ", r)
)
)(
HANOI(next)(m)(r)(l)
)
)
)
)
)
)
) |
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #Rust | Rust | use std::boxed::Box;
use std::collections::{HashMap, HashSet};
#[derive(Debug, PartialEq, Eq, Hash)]
struct Library<'a> {
name: &'a str,
children: Vec<&'a str>,
num_parents: usize,
}
fn build_libraries(input: Vec<&str>) -> HashMap<&str, Box<Library>> {
let mut libraries: HashMap<&str, Box<Library>> = HashMap::new();
for input_line in input {
let line_split = input_line.split_whitespace().collect::<Vec<&str>>();
let name = line_split.get(0).unwrap();
let mut num_parents: usize = 0;
for parent in line_split.iter().skip(1) {
if parent == name {
continue;
}
if !libraries.contains_key(parent) {
libraries.insert(
parent,
Box::new(Library {
name: parent,
children: vec![name],
num_parents: 0,
}),
);
} else {
libraries.get_mut(parent).unwrap().children.push(name);
}
num_parents += 1;
}
if !libraries.contains_key(name) {
libraries.insert(
name,
Box::new(Library {
name,
children: Vec::new(),
num_parents,
}),
);
} else {
libraries.get_mut(name).unwrap().num_parents = num_parents;
}
}
libraries
}
fn topological_sort<'a>(
mut libraries: HashMap<&'a str, Box<Library<'a>>>,
) -> Result<Vec<&'a str>, String> {
let mut needs_processing = libraries
.iter()
.map(|(k, _v)| k.clone())
.collect::<HashSet<&str>>();
let mut options: Vec<&str> = libraries
.iter()
.filter(|(_k, v)| v.num_parents == 0)
.map(|(k, _v)| *k)
.collect();
let mut sorted: Vec<&str> = Vec::new();
while !options.is_empty() {
let cur = options.pop().unwrap();
for children in libraries
.get_mut(cur)
.unwrap()
.children
.drain(0..)
.collect::<Vec<&str>>()
{
let child = libraries.get_mut(children).unwrap();
child.num_parents -= 1;
if child.num_parents == 0 {
options.push(child.name)
}
}
sorted.push(cur);
needs_processing.remove(cur);
}
match needs_processing.is_empty() {
true => Ok(sorted),
false => Err(format!("Cycle detected among {:?}", needs_processing)),
}
}
fn main() {
let input: Vec<&str> = vec![
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n",
"dw01 ieee dw01 dware gtech dw04\n",
"dw02 ieee dw02 dware\n",
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n",
"dw04 dw04 ieee dw01 dware gtech\n",
"dw05 dw05 ieee dware\n",
"dw06 dw06 ieee dware\n",
"dw07 ieee dware\n",
"dware ieee dware\n",
"gtech ieee gtech\n",
"ramlib std ieee\n",
"std_cell_lib ieee std_cell_lib\n",
"synopsys\n",
];
let libraries = build_libraries(input);
match topological_sort(libraries) {
Ok(sorted) => println!("{:?}", sorted),
Err(msg) => println!("{:?}", msg),
}
}
|
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #OCaml | OCaml | let pi = 4. *. atan 1.
let radians = pi /. 4.
let degrees = 45.;;
Printf.printf "%f %f\n" (sin radians) (sin (degrees *. pi /. 180.));;
Printf.printf "%f %f\n" (cos radians) (cos (degrees *. pi /. 180.));;
Printf.printf "%f %f\n" (tan radians) (tan (degrees *. pi /. 180.));;
let arcsin = asin (sin radians);;
Printf.printf "%f %f\n" arcsin (arcsin *. 180. /. pi);;
let arccos = acos (cos radians);;
Printf.printf "%f %f\n" arccos (arccos *. 180. /. pi);;
let arctan = atan (tan radians);;
Printf.printf "%f %f\n" arctan (arctan *. 180. /. pi);; |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #Logtalk | Logtalk |
:- object(tree_traversal).
:- public(orders/1).
orders(Tree) :-
write('Pre-order: '), pre_order(Tree), nl,
write('In-order: '), in_order(Tree), nl,
write('Post-order: '), post_order(Tree), nl,
write('Level-order: '), level_order(Tree).
:- public(orders/0).
orders :-
tree(Tree),
orders(Tree).
tree(
t(1,
t(2,
t(4,
t(7, t, t),
t
),
t(5, t, t)
),
t(3,
t(6,
t(8, t, t),
t(9, t, t)
),
t
)
)
).
pre_order(t).
pre_order(t(Value, Left, Right)) :-
write(Value), write(' '),
pre_order(Left),
pre_order(Right).
in_order(t).
in_order(t(Value, Left, Right)) :-
in_order(Left),
write(Value), write(' '),
in_order(Right).
post_order(t).
post_order(t(Value, Left, Right)) :-
post_order(Left),
post_order(Right),
write(Value), write(' ').
level_order(t).
level_order(t(Value, Left, Right)) :-
% write tree root value
write(Value), write(' '),
% write rest of the tree
level_order([Left, Right], Tail-Tail).
level_order([], Trees-[]) :-
( Trees \= [] ->
% print next level
level_order(Trees, Tail-Tail)
; % no more levels
true
).
level_order([Tree| Trees], Rest0) :-
( Tree = t(Value, Left, Right) ->
write(Value), write(' '),
% collect the subtrees to print the next level
append(Rest0, [Left, Right| Tail]-Tail, Rest1),
% continue printing the current level
level_order(Trees, Rest1)
; % continue printing the current level
level_order(Trees, Rest0)
).
% use difference-lists for constant time append
append(List1-Tail1, Tail1-Tail2, List1-Tail2).
:- end_object.
|
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #M4 | M4 | define(`s',`Hello,How,Are,You,Today')
define(`set',`define(`$1[$2]',`$3')')
define(`get',`defn($1[$2])')
define(`n',0)
define(`fill',
`set(a,n,$1)`'define(`n',incr(n))`'ifelse(eval($#>1),1,`fill(shift($@))')')
fill(s)
define(`j',0)
define(`show',
`ifelse(eval(j<n),1,`get(a,j).`'define(`j',incr(j))`'show')')
show |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Maple | Maple | StringTools:-Join(StringTools:-Split("Hello,How,Are,You,Today", ","),"."); |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Ring | Ring |
beginTime = TimeList()[13]
for n = 1 to 10000000
n = n + 1
next
endTime = TimeList()[13]
elapsedTime = endTime - beginTime
see "Elapsed time = " + elapsedTime + nl
|
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Ruby | Ruby | require 'benchmark'
Benchmark.bm(8) do |x|
x.report("nothing:") { }
x.report("sum:") { (1..1_000_000).inject(4) {|sum, x| sum + x} }
end |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
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
| #Oforth | Oforth | Object Class new: Employee(name, id, salary, dep)
Employee method: initialize := dep := salary := id := name ;
Employee method: salary @salary ;
Employee method: dep @dep ;
Employee method: << "[" << @dep << "," << @name << "," << @salary << "]" << ;
: topRank(n)
| employees |
ListBuffer new ->employees
Employee new("Tyler Bennett", "E10297", 32000, "D101") employees add
Employee new("John Rappl", "E21437", 47000, "D050") employees add
Employee new("George Woltman", "E00127", 53500, "D101") employees add
Employee new("Adam Smith", "E63535", 18000, "D202") employees add
Employee new("Claire Buckman", "E39876", 27800, "D202") employees add
Employee new("David McClellan", "E04242", 41500, "D101") employees add
Employee new("Rich Holcomb", "E01234", 49500, "D202") employees add
Employee new("Nathan Adams", "E41298", 21900, "D050") employees add
Employee new("Richard Potter", "E43128", 15900, "D101") employees add
Employee new("David Motsinger", "E27002", 19250, "D202") employees add
Employee new("Tim Sampair", "E03033", 27000, "D101") employees add
Employee new("Kim Arlich", "E10001", 57000, "D190") employees add
Employee new("Timothy Grove", "E16398", 29900, "D190") employees add
#dep employees sortBy groupWith( #dep )
map(#[ sortBy(#[ salary neg ]) left(n) ]) apply(#println) ; |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #mIRC_Scripting_Language | mIRC Scripting Language | alias ttt {
if ($2 isin %ttt) || (!%ttt) {
var %ttt~ = $remove($iif(%ttt,%ttt,1 2 3 4 5 6 7 8 9),$2,X,O)
var %ttt~~ = $replace($iif(%ttt,%ttt,1 2 3 4 5 6 7 8 9),$2,X)
set %ttt $replace(%ttt~~,$iif(($regex(%ttt~~,/(?:O . . (?:(?:. O .|O) . . (\d)|(?:. (\d) .|(\d)) . . O)|(\d) . . (?:. O .|O) . . O|. . (?:O . (?:O . (\d)|(\d) . O)|(\d) . O . O) . .)/)) || ($regex(%ttt~~,/^(?:. . . )*(?:O (?:O (\d)|(\d) O)|(\d) O O)(?: . . .)*$/)),$regml(1),$iif(($regex(%ttt~~,/(?:X . . (?:(?:. X .|X) . . (\d)|(?:. (\d) .|(\d)) . . X)|(\d) . . (?:. X .|X) . . X|. . (?:X . (?:X . (\d)|(\d) . X)|(\d) . X . X) . .)/)) || ($regex(%ttt~~,/^(?:. . . )*(?:X (?:X (\d)|(\d) X)|(\d) X X)(?: . . .)*$/)),$regml(1),$iif($remove(%ttt~,2,4,6,8,$chr(32)),$iif((5 isin $remove(%ttt~,2,4,6,8)) && ($rand(0,$numtok($v2,32)) == 0),5,$gettok($remove(%ttt~,2,4,6,8),$rand(1,$numtok($remove(%ttt~,2,4,6,8),32)),32)),$gettok(%ttt~,$rand(1,$numtok(%ttt~,32)),32)))),O)
tokenize 32 %ttt
if ($regex(%ttt,/(?:X . . (?:X|. X .) . . X|. . X . X . X . .)/)) || ($regex(%ttt,/^(?:. . . )*X X X(?: . . .)*$/)) {
echo -ag $me Wins
tokenize 32 %ttt~~
unset %ttt
}
elseif ($regex(%ttt,/(?:O . . (?:O|. O .) . . O|. . O . O . O . .)/)) || ($regex(%ttt,/^(?:. . . )*O O O(?: . . .)*$/)) {
echo -ag $me Loses
unset %ttt
}
elseif (!$regex(%ttt,/\d/)) {
echo -ag Draw
unset %ttt
}
echo -ag � $+ $iif($1 isnum,$chr(32),$1) $+ $chr(124) $+ $iif($2 isnum,$chr(32),$2) $+ $chr(124) $+ $iif($3 isnum, ,$3)
echo -ag � $+ $iif($4 isnum,$chr(32),$4) $+ $chr(124) $+ $iif($5 isnum,$chr(32),$5) $+ $chr(124) $+ $iif($6 isnum, ,$6)
echo -ag � $+ $iif($7 isnum,$chr(32),$7) $+ $chr(124) $+ $iif($8 isnum,$chr(32),$8) $+ $chr(124) $+ $iif($9 isnum, ,$9)
}
else {
echo -ag Place Taken
tokenize 32 %ttt
echo -ag � $+ $iif($1 isnum,$chr(32),$1) $+ $chr(124) $+ $iif($2 isnum,$chr(32),$2) $+ $chr(124) $+ $iif($3 isnum, ,$3)
echo -ag � $+ $iif($4 isnum,$chr(32),$4) $+ $chr(124) $+ $iif($5 isnum,$chr(32),$5) $+ $chr(124) $+ $iif($6 isnum, ,$6)
echo -ag � $+ $iif($7 isnum,$chr(32),$7) $+ $chr(124) $+ $iif($8 isnum,$chr(32),$8) $+ $chr(124) $+ $iif($9 isnum, ,$9)
}
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Ezhil | Ezhil |
# (C) 2013 Ezhil Language Project
# Tower of Hanoi – recursive solution
நிரல்பாகம் ஹோனாய்(வட்டுகள், முதல்அச்சு, இறுதிஅச்சு,வட்டு)
@(வட்டுகள் == 1 ) ஆனால்
பதிப்பி “வட்டு ” + str(வட்டு) + “ஐ \t (” + str(முதல்அச்சு) + “ —> ” + str(இறுதிஅச்சு)+ “) அச்சிற்கு நகர்த்துக.”
இல்லை
@( ["இ", "அ", "ஆ"] இல் அச்சு ) ஒவ்வொன்றாக
@( (முதல்அச்சு != அச்சு) && (இறுதிஅச்சு != அச்சு) ) ஆனால்
நடு = அச்சு
முடி
முடி
# solve problem for n-1 again between src and temp pegs
ஹோனாய்(வட்டுகள்-1, முதல்அச்சு,நடு,வட்டுகள்-1)
# move largest disk from src to destination
ஹோனாய்(1, முதல்அச்சு, இறுதிஅச்சு,வட்டுகள்)
# solve problem for n-1 again between different pegs
ஹோனாய்(வட்டுகள்-1, நடு, இறுதிஅச்சு,வட்டுகள்-1)
முடி
முடி
ஹோனாய்(4,”அ”,”ஆ”,0)
|
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #Scheme | Scheme |
(import (chezscheme))
(import (srfi srfi-1))
(define (remove-self-dependency pair)
(let ((key (car pair))
(value (cdr pair)))
(cons key (remq key value))))w
(define (remove-self-dependencies alist)
(map remove-self-dependency alist))
(define (add-missing-items dependencies)
(let loop ((items (delete-duplicates (append-map cdr dependencies) eq?))
(out dependencies))
(if (null? items)
out
(let ((item (car items)))
(if (assq item out)
(loop (cdr items) out)
(loop (cdr items) (cons (cons item '()) out)))))))
(define (lift dependencies batch)
(let loop ((dependencies dependencies)
(out '()))
(if (null? dependencies)
out
(let ((key (caar dependencies))
(value (cdar dependencies)))
(if (null? value)
(loop (cdr dependencies) out)
(loop (cdr dependencies)
(cons (cons key (lset-difference eq? value batch))
out)))))))
(define (topological-sort dependencies)
(let* ((dependencies (remove-self-dependencies dependencies))
(dependencies (add-missing-items dependencies)))
(let loop ((out '())
(dependencies dependencies))
(if (null? dependencies)
(reverse out)
(let ((batch (map car (filter (lambda (pair) (null? (cdr pair))) dependencies))))
(if (null? batch)
#f
(loop (cons batch out) (lift dependencies batch))))))))
(define example
'((des_system_lib . (std synopsys std_cell_lib des_system_lib dw02
dw01 ramlib ieee))
(dw01 . (ieee dw01 dware gtech))
(dw02 . (ieee dw02 dware))
(dw03 . (std synopsys dware dw03 dw02 dw01 ieee gtech))
(dw04 . (dw04 ieee dw01 dware gtech))
(dw05 . (dw05 ieee dware))
(dw06 . (dw06 ieee dware))
(dw07 . (ieee dware))
(dware . (ieee dware))
(gtech . (ieee gtech))
(ramlib . (std ieee))
(std_cell_lib . (ieee std_cell_lib))
(synopsys . ())))
(write (topological-sort example))
(define unsortable
'((des_system_lib . (std synopsys std_cell_lib des_system_lib dw02
dw01 ramlib ieee))
(dw01 . (ieee dw01 dware gtech dw04))
(dw02 . (ieee dw02 dware))
(dw03 . (std synopsys dware dw03 dw02 dw01 ieee gtech))
(dw04 . (dw04 ieee dw01 dware gtech))
(dw05 . (dw05 ieee dware))
(dw06 . (dw06 ieee dware))
(dw07 . (ieee dware))
(dware . (ieee dware))
(gtech . (ieee gtech))
(ramlib . (std ieee))
(std_cell_lib . (ieee std_cell_lib))
(synopsys . ())))
(newline)
(write (topological-sort unsortable))
|
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #Octave | Octave | function d = degree(rad)
d = 180*rad/pi;
endfunction
r = pi/3;
rd = degree(r);
funcs = { "sin", "cos", "tan", "sec", "cot", "csc" };
ifuncs = { "asin", "acos", "atan", "asec", "acot", "acsc" };
for i = 1 : numel(funcs)
v = arrayfun(funcs{i}, r);
vd = arrayfun(strcat(funcs{i}, "d"), rd);
iv = arrayfun(ifuncs{i}, v);
ivd = arrayfun(strcat(ifuncs{i}, "d"), vd);
printf("%s(%f) = %s(%f) = %f (%f)\n",
funcs{i}, r, strcat(funcs{i}, "d"), rd, v, vd);
printf("%s(%f) = %f\n%s(%f) = %f\n",
ifuncs{i}, v, iv,
strcat(ifuncs{i}, "d"), vd, ivd);
endfor |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #Lua | Lua | -- Utility
local function append(t1, t2)
for _, v in ipairs(t2) do
table.insert(t1, v)
end
end
-- Node class
local Node = {}
Node.__index = Node
function Node:order(order)
local r = {}
append(r, type(self[order[1]]) == "table" and self[order[1]]:order(order) or {self[order[1]]})
append(r, type(self[order[2]]) == "table" and self[order[2]]:order(order) or {self[order[2]]})
append(r, type(self[order[3]]) == "table" and self[order[3]]:order(order) or {self[order[3]]})
return r
end
function Node:levelorder()
local levelorder = {}
local queue = {self}
while next(queue) do
local node = table.remove(queue, 1)
table.insert(levelorder, node[1])
table.insert(queue, node[2])
table.insert(queue, node[3])
end
return levelorder
end
-- Node creator
local function new(value, left, right)
return value and setmetatable({
value,
(type(left) == "table") and new(unpack(left)) or new(left),
(type(right) == "table") and new(unpack(right)) or new(right),
}, Node) or nil
end
-- Example
local tree = new(1, {2, {4, 7}, 5}, {3, {6, 8, 9}})
print("preorder: " .. table.concat(tree:order({1, 2, 3}), " "))
print("inorder: " .. table.concat(tree:order({2, 1, 3}), " "))
print("postorder: " .. table.concat(tree:order({2, 3, 1}), " "))
print("level-order: " .. table.concat(tree:levelorder(), " ")) |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | StringJoin@StringSplit["Hello,How,Are,You,Today", "," -> "."] |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Rust | Rust | // 20210224 Rust programming solution
use rand::Rng;
use std::time::{Instant};
fn custom_function() {
let mut i = 0;
let mut rng = rand::thread_rng();
let n1: f32 = rng.gen();
while i < ( 1000000 + 1000000 * ( n1.log10() as i32 ) ) {
i = i + 1;
}
}
fn main() {
let start = Instant::now();
custom_function();
let duration = start.elapsed();
println!("Time elapsed in the custom_function() is : {:?}", duration);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.