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/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Rot13[s_] := StringReplace[
s,
# -> RotateLeft[#, 13] & @* CharacterRange @@ # &[
{"a", "z"}, {"A", "Z"}
] // Thread
]
Rot13["Hello World!"]
Rot13[%] |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #JavaScript | JavaScript | var roman = {
map: [
1000, 'M', 900, 'CM', 500, 'D', 400, 'CD', 100, 'C', 90, 'XC',
50, 'L', 40, 'XL', 10, 'X', 9, 'IX', 5, 'V', 4, 'IV', 1, 'I',
],
int_to_roman: function(n) {
var value = '';
for (var idx = 0; n > 0 && idx < this.map.length; idx += 2) {
while (n ... |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Lua | Lua | function ToNumeral( roman )
local Num = { ["M"] = 1000, ["D"] = 500, ["C"] = 100, ["L"] = 50, ["X"] = 10, ["V"] = 5, ["I"] = 1 }
local numeral = 0
local i = 1
local strlen = string.len(roman)
while i < strlen do
local z1, z2 = Num[ string.sub(roman,i,i) ], Num[ string.sub(roman,i+1,i+1... |
http://rosettacode.org/wiki/Rock-paper-scissors | Rock-paper-scissors | Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
... | #Swift | Swift | enum Choice: CaseIterable {
case rock
case paper
case scissors
case lizard
case spock
}
extension Choice {
var weaknesses: Set<Choice> {
switch self {
case .rock:
return [.paper, .spock]
case .paper:
return [.scissors, .lizard]
case .scissors:
return [.rock, .... |
http://rosettacode.org/wiki/Rock-paper-scissors | Rock-paper-scissors | Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
... | #Tcl | Tcl | package require Tcl 8.5
### Choices are represented by integers, which are indices into this list:
### Rock, Paper, Scissors
### Normally, idiomatic Tcl code uses names for these sorts of things, but it
### turns out that using integers simplifies the move-comparison logic.
# How to ask for a move from the human... |
http://rosettacode.org/wiki/Retrieve_and_search_chat_history | Retrieve and search chat history | Task
Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library.
Details:
The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r... | #Python | Python | #! /usr/bin/env python3
import datetime
import re
import urllib.request
import sys
def get(url):
with urllib.request.urlopen(url) as response:
html = response.read().decode('utf-8')
if re.match(r'<!Doctype HTML[\s\S]*<Title>URL Not Found</Title>', html):
return None
return html
def main()... |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #Racket | Racket |
#lang racket
(define (encode str)
(regexp-replace* #px"(.)\\1*" str (λ (m c) (~a (string-length m) c))))
(define (decode str)
(regexp-replace* #px"([0-9]+)(.)" str (λ (m n c) (make-string (string->number n) (string-ref c 0)))))
|
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #MATLAB | MATLAB | function r=rot13(s)
if ischar(s)
r=s; % preallocation and copy of non-letters
for i=1:size(s,1)
for j=1:size(s,2)
if isletter(s(i,j))
if s(i,j)>=97 % lower case
base = 97;
else % upper case
... |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #jq | jq | def to_roman_numeral:
def romans:
[100000, "\u2188"],
[90000, "ↂ\u2188"],
[50000, "\u2187"],
[40000, "ↂ\u2187"],
[10000, "ↂ"],
[9000, "Mↂ"],
[5000, "ↁ"],
[4000, "Mↁ"],
[1000, "M"],
[900, "CM"],
[500, "D"],
[400, "CD"],
[100... |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #M2000_Interpreter | M2000 Interpreter |
Module RomanNumbers {
flush ' empty current stack
gosub Initialize
document Doc$
while not empty
read rom$
print rom$;"=";RomanEval$(rom$)
Doc$=rom$+"="+RomanEval$(rom$)+{
}
end while
Clipboard Doc$
end
Initialize:
functi... |
http://rosettacode.org/wiki/Rock-paper-scissors | Rock-paper-scissors | Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
... | #TI-83_BASIC | TI-83 BASIC | PROGRAM:RPS
:{0,0,0}→L1
:{0,0,0}→L2
:Lbl ST
:Disp "R/P/S"
:Disp "1/2/3"
:Lbl EC
:Input A
:If A>3 or A<1
:Then
:Goto NO
:End
:randInt(1,3+L1(1)+L1(2)+L1(3)→C
:If C≤1+L1(1)
:Then
:2→B
:Goto NS
:End
:If C>2+L1(2)
:Then
:1→B
:Else
:3→B
:End
:Lbl NS
:L1(A)+1→L1(A)
:If A=B
:Then
:Disp "TIE GAME"
:L2(3)+1→L2(3)
:Goto TG
:End
... |
http://rosettacode.org/wiki/Retrieve_and_search_chat_history | Retrieve and search chat history | Task
Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library.
Details:
The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r... | #Racket | Racket | #lang racket
(require net/url)
(require racket/date)
;; generate archive url from specified number of days in the past
(define (generate-url days-ago)
(putenv "TZ" "Europe/Berlin") ; this works for Linux
(let* [(today (current-date))
(past (seconds->date (- (date->seconds today) (* days-ago 60 60 24))))
... |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #Raku | Raku | sub encode($str) { $str.subst(/(.) $0*/, { $/.chars ~ $0 }, :g) }
sub decode($str) { $str.subst(/(\d+) (.)/, { $1 x $0 }, :g) }
my $e = encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW');
say $e;
say decode($e); |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Ada | Ada | with Ada.Text_IO;
with CryptAda.Pragmatics;
with CryptAda.Digests.Message_Digests.RIPEMD_160;
with CryptAda.Digests.Hashes;
with CryptAda.Utils.Format;
procedure RC_RIPEMD_160 is
use CryptAda.Pragmatics;
use CryptAda.Digests.Message_Digests;
use CryptAda.Digests;
function To_Byte_Array (Item : String)... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #AutoHotkey | AutoHotkey | class example
{
foo()
{
Msgbox Called example.foo()
}
__Call(method, params*)
{
funcRef := Func(funcName := this.__class "." method)
if !IsObject(funcRef)
{
str := "Called undefined method " funcName "() with these parameters:"
for k,v in params
str .= "`n" v
Msgbox... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Maxima | Maxima | rot13(a) := simplode(map(ascii, map(lambda([n],
if (n >= 65 and n <= 77) or (n >= 97 and n <= 109) then n + 13
elseif (n >= 78 and n <= 90) or (n >= 110 and n <= 122) then n - 13
else n), map(cint, sexplode(a)))))$
lowercase: "abcdefghijklmnopqrstuvwxyz"$
uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"$
r... |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #Jsish | Jsish | /* Roman numerals, in Jsish */
var Roman = {
ord: ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'],
val: [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
fromRoman: function(roman:string):number {
var n = 0;
var re = /IV|IX|I|V|XC|XL|X|L|CD|CM|C|D|M/g;
... |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Maple | Maple | f := n -> convert(n, arabic):
seq(printf("%a\n", f(i)), i in [MCMXC, MMVIII, MDCLXVI]); |
http://rosettacode.org/wiki/Rock-paper-scissors | Rock-paper-scissors | Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
... | #TorqueScript | TorqueScript |
while(isobject(RockPaperScissors))
RockPaperScissors.delete();
new scriptObject(RockPaperScissors);
function RockPaperScissors::startGame(%this)
{
%this.idle = true;
echo("Starting rock paper scissors, please type choose(\"choice\"); to proceed!");
}
function RockPaperScissors::endGame(%this)
{
%this.idle =... |
http://rosettacode.org/wiki/Retrieve_and_search_chat_history | Retrieve and search chat history | Task
Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library.
Details:
The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r... | #Raku | Raku | my $needle = @*ARGS.shift // '';
my @haystack;
# 10 days before today, Zulu time
my $begin = DateTime.new(time).utc.earlier(:10days);
say " Executed at: ", DateTime.new(time).utc;
say "Begin searching from: $begin";
# Today - 10 days through today
for $begin.Date .. DateTime.now.utc.Date -> $date {
# ... |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #REXX | REXX | /*REXX program encodes and displays a string by using a run─length encoding scheme. */
parse arg input . /*normally, input would be in a file. */
default= 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'
if input=='' | input=="," then input= default /*Not spec... |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #C | C |
#ifndef RMDsize
#define RMDsize 160
#endif
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#if RMDsize == 128
#include "rmd128.h"
#include "rmd128.c" /* Added to remove errors during compilation */
#elif RMDsize == 160
#include "rmd160.h"
#include "rmd160.c" /* Added to remove errors ... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Brat | Brat | example = object.new
example.no_method = { meth_name, *args |
p "#{meth_name} was called with these arguments: #{args}"
}
example.this_does_not_exist "at all" #Prints "this_does_not_exist was called with these arguments: [at all]" |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #C.23 | C# | using System;
using System.Dynamic;
class Example : DynamicObject
{
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
result = null;
Console.WriteLine("This is {0}.", binder.Name);
return true;
}
}
class Program
{
static voi... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Mercury | Mercury | :- module rot13.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module string, set, list, char, int.
:- type transition == {character, character}.
:- type transitions == set(transition).
:- type rot_kind
---> encrypt
; decrypt.
:- pred bui... |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #Julia | Julia | using Printf
function romanencode(n::Integer)
if n < 1 || n > 4999 throw(DomainError()) end
DR = [["I", "X", "C", "M"] ["V", "L", "D", "MMM"]]
rnum = ""
for (omag, d) in enumerate(digits(n))
if d == 0
omr = ""
elseif d < 4
omr = DR[omag, 1] ^ d
elseif... |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | FromRomanNumeral["MMCDV"] |
http://rosettacode.org/wiki/Rock-paper-scissors | Rock-paper-scissors | Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
... | #uBasic.2F4tH | uBasic/4tH | 20 LET P=0: LET Q=0: LET Z=0
30 INPUT "Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? ", A
40 IF A>3 THEN GOTO 400
50 IF A=3 THEN LET A=4
60 IF A<1 THEN GOTO 400
70 C=RND(3) : LET D=4: FOR B=1 TO C+1 : LET D = D+D : NEXT : GOTO (A+D)*10
90 Z=Z+1 : PRINT "We both chose 'rock'. It's a draw." : GOTO ... |
http://rosettacode.org/wiki/Rock-paper-scissors | Rock-paper-scissors | Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
... | #UNIX_Shell | UNIX Shell | #!/bin/bash
choices=(rock paper scissors)
# comparison function, works like Perl
# winner x y = 2 if y beats x, 1 if x beats 1, 0 if it's a tie
winner() {
local left="$1" right="$2"
echo $(( (3 + left - right) % 3 ))
}
human_counts=(1 1 1)
human_count=3
computer_counts=(0 0 0)
games=0 human=0 computer=0
P... |
http://rosettacode.org/wiki/Retrieve_and_search_chat_history | Retrieve and search chat history | Task
Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library.
Details:
The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r... | #Ruby | Ruby | #! /usr/bin/env ruby
require 'net/http'
require 'time'
def gen_url(i)
day = Time.now + i*60*60*24
# Set the time zone in which to format the time, per
# https://coderwall.com/p/c7l82a/create-a-time-in-a-specific-timezone-in-ruby
old_tz = ENV['TZ']
ENV['TZ'] = 'Europe/Berlin'
url = day.strftime('http://tcl... |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #Ring | Ring |
# Project : Run-length encoding
load "stdlib.ring"
test = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
num = 0
nr = 0
decode = newlist(7,2)
for n = 1 to len(test) - 1
if test[n] = test[n+1]
num = num + 1
else
nr = nr + 1
decode[nr][1] = (num + 1)
de... |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #C.23 | C# | using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main(string[] args)
{
string text = "Rosetta Code";
byte[] bytes = Encoding.ASCII.GetBytes(text);
RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create();
byte[] hashValue = myRIPEMD160.C... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #C.2B.2B | C++ | class animal {
public:
virtual void bark() // concrete virtual, not pure
{
throw "implement me: do not know how to bark";
}
};
class elephant : public animal // does not implement bark()
{
};
int main()
{
elephant e;
e.bark(); // throws exception
}
|
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Cach.C3.A9_ObjectScript | Caché ObjectScript | Class DynamicDispatch.Example Extends %RegisteredObject
{
Method Foo()
{
Write "This is foo", !
}
Method Bar()
{
Write "This is bar", !
}
Method %DispatchMethod(Method As %String, Args...)
{
Write "Tried to handle unknown method '"_Method_"'"
For i=1:1:$Get(Args) {
Write ", " If i=1 Write "with arguments: "... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #MiniScript | MiniScript | rot13 = function(s)
chars = s.values
for i in chars.indexes
c = chars[i]
if c >= "a" and c <= "z" then chars[i] = char(97 + (code(c)-97+13)%26)
if c >= "A" and c <= "Z" then chars[i] = char(65 + (code(c)-65+13)%26)
end for
return chars.join("")
end function
print rot13("Hello w... |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #Kotlin | Kotlin | val romanNumerals = mapOf(
1000 to "M",
900 to "CM",
500 to "D",
400 to "CD",
100 to "C",
90 to "XC",
50 to "L",
40 to "XL",
10 to "X",
9 to "IX",
5 to "V",
4 to "IV",
1 to "I"
)
fun encode(number: Int): String? {
if (number > 5000 || number < 1) {
retur... |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #MATLAB | MATLAB | function x = rom2dec(s)
% ROM2DEC converts Roman numbers to decimal
% store Roman digits values: I=1, V=5, X=10, L=50, C=100, D=500, M=1000
digitsValues = [0 0 100 500 0 0 0 0 1 0 0 50 1000 0 0 0 0 0 0 0 0 5 0 10 0 0];
% convert Roman number to array of values
values = digitsValues(s-'A'+1);
% change sign if next val... |
http://rosettacode.org/wiki/Rock-paper-scissors | Rock-paper-scissors | Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
... | #Wee_Basic | Wee Basic | let entered=0
let keycode=0
let rcounter=1
print 1 "Enter R for rock, P for paper, or S for scissors. (not case sensitive)"
while entered=0
input human$
if human=$="r"
let human$="rock"
let entered=1
elseif human=$="R"
let human$="rock"
let entered=1
elseif human=$="p"
let human$="paper"
let entered=1
elseif human=$="P... |
http://rosettacode.org/wiki/Rock-paper-scissors | Rock-paper-scissors | Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
... | #Wren | Wren | import "random" for Random
import "/str" for Str
import "/ioutil" for Input
var choices = "rpsq"
var rand = Random.new()
var pWins = 0 // player wins
var cWins = 0 // computer wins
var draws = 0 // neither wins
var games = 0 // games played
var pFreqs = [0, 0, 0] // player f... |
http://rosettacode.org/wiki/Retrieve_and_search_chat_history | Retrieve and search chat history | Task
Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library.
Details:
The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r... | #Scala | Scala | import java.net.Socket
import java.net.URL
import java.time
import java.time.format
import java.time.ZoneId
import java.util.Scanner
import scala.collection.JavaConverters._
def get(rawUrl: String): List[String] = {
val url = new URL(rawUrl)
val port = if (url.getPort > -1) url.getPort else 80
val sock = ... |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #Ruby | Ruby |
# run_encode("aaabbbbc") #=> [["a", 3], ["b", 4], ["c", 1]]
def run_encode(string)
string
.chars
.chunk{|i| i}
.map {|kind, array| [kind, array.length]}
end
# run_decode([["a", 3], ["b", 4], ["c", 1]]) #=> "aaabbbbc"
def run_decode(char_counts)
char_counts
.map{|char, count| char * count}
.j... |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Clojure | Clojure | (use 'pandect.core)
(ripemd160 "Rosetta Code") |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Common_Lisp | Common Lisp | (ql:quickload 'ironclad)
(defun string-to-ripemd-160 (str)
"Return the RIPEMD-160 digest of the given ASCII string."
(ironclad:byte-array-to-hex-string
(ironclad:digest-sequence :ripemd-160
(ironclad:ascii-string-to-byte-array str)))
(string-to-ripemd-160 "Rosetta Code") |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Common_Lisp | Common Lisp | (defgeneric do-something (thing)
(:documentation "Do something to thing."))
(defmethod no-applicable-method ((method (eql #'do-something)) &rest args)
(format nil "No method for ~w on ~w." method args))
(defmethod do-something ((thing (eql 3)))
(format nil "Do something to ~w." thing)) |
http://rosettacode.org/wiki/Repunit_primes | Repunit primes | Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In ... | #C.2B.2B | C++ | #include <future>
#include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>
#include <primesieve.hpp>
std::vector<uint64_t> repunit_primes(uint32_t base,
const std::vector<uint64_t>& primes) {
std::vector<uint64_t> result;
for (uint64_t prime : primes) ... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Mirah | Mirah | def rot13 (value:string)
result = ""
d = ' '.toCharArray[0]
value.toCharArray.each do |c|
testChar = Character.toLowerCase(c)
if testChar <= 'm'.toCharArray[0] && testChar >= 'a'.toCharArray[0] then
d = char(c + 13)
end
if testChar <= 'z'.toCharArray[0] && testCh... |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #Lasso | Lasso | define br => '\r'
// encode roman
define encodeRoman(num::integer)::string => {
local(ref = array('M'=1000, 'CM'=900, 'D'=500, 'CD'=400, 'C'=100, 'XC'=90, 'L'=50, 'XL'=40, 'X'=10, 'IX'=9, 'V'=5, 'IV'=4, 'I'=1))
local(out = string)
with i in #ref do => {
while(#num >= #i->second) => {
#out->append(#i->first)
... |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Mercury | Mercury | :- module test_roman.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module char.
:- import_module exception.
:- import_module int.
:- import_module list.
:- import_module string.
:- type conversion_error ---> not_a_roman_number.
:- func build_int(lis... |
http://rosettacode.org/wiki/Rock-paper-scissors | Rock-paper-scissors | Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
... | #Yabasic | Yabasic | REM Yabasic 2.763 version
WINNER = 1 : ACTION = 2 : LOSSER = 3
dim word$(10, 3)
for n = 0 to 9
read word$(n, WINNER), word$(n, ACTION), word$(n, LOSSER)
next n
repeat
clear screen
computerChoice$ = word$(ran(10), WINNER)
print "'Rock, Paper, Scissors, Lizard, Spock!' rules are:\n"
for n = 0 to... |
http://rosettacode.org/wiki/Retrieve_and_search_chat_history | Retrieve and search chat history | Task
Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library.
Details:
The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r... | #Smalltalk | Smalltalk |
CommandLineHandler subclass: #ChatHistorySearchCommandLineHandler
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'RosettaCode'!
!ChatHistorySearchCommandLineHandler methodsFor: 'activation' stamp: 'EduardoPadoan 1/27/2019 15:18'!
activate
self searchHistoryFor: self arguments f... |
http://rosettacode.org/wiki/Retrieve_and_search_chat_history | Retrieve and search chat history | Task
Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library.
Details:
The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r... | #Tcl | Tcl | #! /usr/bin/env tclsh
package require http
proc get url {
set r [::http::geturl $url]
set content [::http::data $r]
::http::cleanup $r
return $content
}
proc grep {needle haystack} {
lsearch -all \
-inline \
-glob \
[split $haystack \n] \
*[string ... |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #Run_BASIC | Run BASIC | string$ = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
beg = 1
i = 1
[loop]
s$ = mid$(string$,beg,1)
while mid$(string$,i,1) = s$
i = i + 1
wend
press$ = press$ ; i-beg;s$
beg = i
if i < len(string$) then goto [loop]
print "Compressed:";press$
beg = 1
i = 1
[expand]
while mid$(press$... |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #D | D | void main() {
import std.stdio, std.digest.ripemd;
writefln("%(%02x%)", "Rosetta Code".ripemd160Of);
} |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Delphi | Delphi |
program RIPEMD160;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
DCPripemd160;
function HashRipemd160(const Input: Ansistring): TArray<byte>;
var
Hasher: TDCP_ripemd160;
begin
Hasher := TDCP_ripemd160.Create(nil);
try
Hasher.Init;
Hasher.UpdateStr(Input);
SetLength(Result, Hasher.HashSize div 8... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #D | D | import std.stdio;
struct Catcher {
void foo() { writeln("This is foo"); }
void bar() { writeln("This is bar"); }
void opDispatch(string name, ArgsTypes...)(ArgsTypes args) {
writef("Tried to handle unknown method '%s'", name);
if (ArgsTypes.length) {
write(", with arguments... |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #11l | 11l | V text =
‘---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------’
L(line) text.split("\n")
print(reversed(line.split(‘ ’)).join(‘ ’)) |
http://rosettacode.org/wiki/Repunit_primes | Repunit primes | Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In ... | #F.23 | F# |
// Repunit primes. Nigel Galloway: January 24th., 2022
let rUnitP(b:int)=let b=bigint b in primes32()|>Seq.takeWhile((>)1000)|>Seq.map(fun n->(n,((b**n)-1I)/(b-1I)))|>Seq.filter(fun(_,n)->Open.Numeric.Primes.MillerRabin.IsProbablePrime &n)|>Seq.map fst
[2..16]|>List.iter(fun n->printf $"Base %d{n}: "; rUnitP(n)|>Seq.... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #ML | ML | fun rot13char c =
if c >= #"a" andalso c <= #"m" orelse c >= #"A" andalso c <= #"M" then
chr (ord c + 13)
else if c >= #"n" andalso c <= #"z" orelse c >= #"N" andalso c <= #"Z" then
chr (ord c - 13)
else
c
val rot13 = String.map rot13char |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #LaTeX | LaTeX | \documentclass{minimal}
\newcounter{currentyear}
\setcounter{currentyear}{\year}
\begin{document}
Anno Domini \Roman{currentyear}
\end{document} |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Modula-2 | Modula-2 | MODULE RomanNumerals;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
FROM Strings IMPORT Length;
(* Convert given Roman numeral to binary *)
PROCEDURE DecodeRoman(s: ARRAY OF CHAR): CARDINAL;
VAR i, d, len, acc: CARDINAL;
PROCEDURE Digit(d: CHAR): CARDINAL;
BEGIN
CASE CHR( BITSET(ORD(d)) + B... |
http://rosettacode.org/wiki/Retrieve_and_search_chat_history | Retrieve and search chat history | Task
Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library.
Details:
The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r... | #Wren | Wren | /* retrieve_and_search_chat_history.wren */
import "./date" for Date
var CURLOPT_URL = 10002
var CURLOPT_FOLLOWLOCATION = 52
var CURLOPT_WRITEFUNCTION = 20011
var CURLOPT_WRITEDATA = 10001
class C {
foreign static searchStr
foreign static utcNow // format will be yyyy-mm-dd hh:MM:ss
}
foreign class Buff... |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #Rust | Rust | fn encode(s: &str) -> String {
s.chars()
// wrap all values in Option::Some
.map(Some)
// add an Option::None onto the iterator to clean the pipeline at the end
.chain(std::iter::once(None))
.scan((0usize, '\0'), |(n, c), elem| match elem {
Some(elem) if *n == 0 |... |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Factor | Factor | USING: checksums checksums.ripemd io math.parser ;
"Rosetta Code" ripemd-160 checksum-bytes bytes>hex-string print |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #FreeBASIC | FreeBASIC | ' version 22-10-2016
' compile with: fbc -s console
Function RIPEMD_160(message As String) As String
#Macro ROtate_left(x, n)
(x Shl n Or x Shr (32 - n))
#EndMacro
#Macro f1(x, y, z)
(x Xor y Xor z) ' (0 <= j <= 15)
#EndMacro
#Macro f2(x, y, z)
((x And y) Or ((Not x) An... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | }
labda:
print "One!"
:one
labda:
print "Two!"
:two
local :obj {
labda:
print "Nope, doesn't exist."
set-default obj
obj!one
obj!two
obj!three
|
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #E | E | def example {
to foo() { println("this is foo") }
to bar() { println("this is bar") }
match [verb, args] {
println(`got unrecognized message $verb`)
if (args.size() > 0) {
println(`it had arguments: $args`)
}
}
} |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #Action.21 | Action! | PROC Reverse(CHAR ARRAY src,dst)
BYTE i,j,k,beg,end
i=1 j=src(0)
WHILE j>0
DO
WHILE j>0 AND src(j)=$20
DO j==-1 OD
IF j=0 THEN
EXIT
ELSE
end=j
FI
WHILE j>0 AND src(j)#$20
DO j==-1 OD
beg=j+1
IF i>1 THEN
dst(i)=$20 i==+1
FI
FOR k=beg TO end
... |
http://rosettacode.org/wiki/Repunit_primes | Repunit primes | Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In ... | #Go | Go | package main
import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
"strings"
)
func main() {
limit := 2700
primes := rcu.Primes(limit)
s := new(big.Int)
for b := 2; b <= 36; b++ {
var rPrimes []int
for _, p := range primes {
s.SetString(strings.Repeat("1", p), b)
... |
http://rosettacode.org/wiki/Repunit_primes | Repunit primes | Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In ... | #Julia | Julia | using Primes
repunitprimeinbase(n, base) = isprime(evalpoly(BigInt(base), [1 for _ in 1:n]))
for b in 2:40
println(rpad("Base $b:", 9), filter(n -> repunitprimeinbase(n, b), 1:2700))
end
|
http://rosettacode.org/wiki/Repunit_primes | Repunit primes | Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[RepUnitPrimeQ]
RepUnitPrimeQ[b_][n_] := PrimeQ[FromDigits[ConstantArray[1, n], b]]
ClearAll[RepUnitPrimeQ]
RepUnitPrimeQ[b_][n_] := PrimeQ[FromDigits[ConstantArray[1, n], b]]
Do[
Print["Base ", b, ": ", Select[Range[2700], RepUnitPrimeQ[b]]]
,
{b, 2, 16}
]
|
http://rosettacode.org/wiki/Repunit_primes | Repunit primes | Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In ... | #Perl | Perl | use strict;
use warnings;
use ntheory <is_prime fromdigits>;
my $limit = 1000;
print "Repunit prime digits (up to $limit) in:\n";
for my $base (2..16) {
printf "Base %2d: %s\n", $base, join ' ', grep { is_prime $_ and is_prime fromdigits(('1'x$_), $base) and " $_" } 1..$limit
} |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #MMIX | MMIX | // main registers
p IS $255 % text pointer
c GREG % char
cc GREG % uppercase copy of c
u GREG % all purpose
LOC Data_Segment
GREG @
Test BYTE "dit is een bericht voor de keizer",#a,0
LOC #100
Main LDA p,Test
TRAP 0,Fputs,StdOut % show text to encrypt
LDA p,Test % points to text to encrypt
JMP 4F
// do in ... |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #Liberty_BASIC | Liberty BASIC |
dim arabic( 12)
for i =0 to 12
read k
arabic( i) =k
next i
data 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
dim roman$( 12)
for i =0 to 12
read k$
roman$( i) =k$
next i
data "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"... |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Nanoquery | Nanoquery | def decodeSingle(letter)
if letter = "M"
return 1000
else if letter = "D"
return 500
else if letter = "C"
return 100
else if letter = "L"
return 50
else if letter = "X"
return 10
else if letter = "V"
return 5
else if letter = "I"
return 1
else
return 0
end
end
def decode(roman)
result = 0
... |
http://rosettacode.org/wiki/Retrieve_and_search_chat_history | Retrieve and search chat history | Task
Summary: Find and print the mentions of a given string in the recent chat logs from a chatroom. Only use your programming language's standard library.
Details:
The Tcl Chatroom is an online chatroom. Its conversations are logged. It's useful to know if someone has mentioned you or your project in the chatroom r... | #zkl | zkl | #<<<#
http://tclers.tk/conferences/tcl/:
2017-04-03.tcl 30610 bytes Apr 03, 2017 21:55:37
2017-04-04.tcl 67996 bytes Apr 04, 2017 21:57:01
...
Contents (eg 2017-01-19.tcl):
m 2017-01-19T23:01:02Z ijchain {*** Johannes13__ leaves}
m 2017-01-19T23:15:37Z ijchain {*** fahadash leaves}
m 2017-01-19T23:27:00Z ... |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #Scala | Scala | def encode(s: String) = (1 until s.size).foldLeft((1, s(0), new StringBuilder)) {
case ((len, c, sb), index) if c != s(index) => sb.append(len); sb.append(c); (1, s(index), sb)
case ((len, c, sb), _) => (len + 1, c, sb)
} match {
case (len, c, sb) => sb.append(len); sb.append(c); sb.toString
}
def decode(s: Str... |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Go | Go | package main
import (
"golang.org/x/crypto/ripemd160"
"fmt"
)
func main() {
h := ripemd160.New()
h.Write([]byte("Rosetta Code"))
fmt.Printf("%x\n", h.Sum(nil))
} |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Haskell | Haskell | import Data.Char (ord)
import Crypto.Hash.RIPEMD160 (hash)
import Data.ByteString (unpack, pack)
import Text.Printf (printf)
main = putStrLn $ -- output to terminal
concatMap (printf "%02x") $ -- to hex string
unpack $ -- to array of Word8
hash $ ... |
http://rosettacode.org/wiki/Resistor_mesh | Resistor mesh |
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
| #11l | 11l | -V DIFF_THRESHOLD = 1e-40
T.enum Fixed
FREE
A
B
T Node
Float voltage
Fixed fixed
F (v = 0.0, f = Fixed.FREE)
.voltage = v
.fixed = f
F set_boundary(&m)
m[1][1] = Node( 1.0, Fixed.A)
m[6][7] = Node(-1.0, Fixed.B)
F calc_difference(m, &d)
V h = m.len
V w = m[0].len
V t... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Elena | Elena | import extensions;
class Example
{
generic()
{
// __received is an built-in variable containing the incoming message name
console.printLine(__received," was invoked")
}
generic(x)
{
console.printLine(__received,"(",x,") was invoked")
}
generic(x,y)
{
... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Fancy | Fancy |
class CatchThemAll {
def foo {
"foo received" println
}
def bar {
"bar received" println
}
def unknown_message: msg with_params: params {
"message: " ++ msg print
"arguments: " ++ (params join: ", ") println
}
}
a = CatchThemAll new
a foo
a bar
a we_can_do_it
a they_can_too: "eat" an... |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #Ada | Ada | package Simple_Parse is
-- a very simplistic parser, useful to split a string into words
function Next_Word(S: String; Point: in out Positive)
return String;
-- a "word" is a sequence of non-space characters
-- if S(Point .. S'Last) holds at least one word W
-- then Next_Word increments Point ... |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #Aime | Aime | integer j;
list l, x;
text s, t;
l = list("---------- Ice and Fire ------------",
"",
"fire, in end will world the say Some",
"ice. in say Some",
"desire of tasted I've what From",
"fire. favor who those with hold I",
"",
"... elided paragraph last ...",
... |
http://rosettacode.org/wiki/Repunit_primes | Repunit primes | Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In ... | #Phix | Phix | with javascript_semantics
include mpfr.e
procedure repunit(mpz z, integer n, base=10)
mpz_set_si(z,0)
for i=1 to n do
mpz_mul_si(z,z,base)
mpz_add_si(z,z,1)
end for
end procedure
atom t0 = time()
constant {limit,blimit} = iff(platform()=JS?{400,16} -- 8.8s
... |
http://rosettacode.org/wiki/Repunit_primes | Repunit primes | Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In ... | #Python | Python | from sympy import isprime
for b in range(2, 17):
print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))]) |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Modula-2 | Modula-2 |
MODULE Rot13;
FROM STextIO IMPORT
ReadString, WriteString, WriteLn;
FROM Strings IMPORT
Length;
TYPE
MyString = ARRAY [0..80] OF CHAR;
VAR
S, T : MyString;
PROCEDURE Rot13(S : ARRAY OF CHAR; VAR T : ARRAY OF CHAR);
VAR
I, J : CARDINAL;
BEGIN
FOR I := 0 TO Length(S) - 1
DO
... |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #LiveCode | LiveCode | function toRoman intNum
local roman,numArabic
put "M,CM,D,CD,C,XC,L,XL,X,IX,V,IV,I" into romans
put "1000,900,500,400,100,90,50,40,10,9,5,4,1" into arabics
put intNum into numArabic
repeat with n = 1 to the number of items of romans
put numArabic div item n of arabics into nums
if nu... |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols binary
/* 1990 2008 1666 */
years = Rexx('MCMXC MMVIII MDCLXVI')
loop y_ = 1 to years.words
Say years.word(y_).right(10) || ':' decode(years.word(y_))
end y_
return
method decode(arg) public static returns int s... |
http://rosettacode.org/wiki/Run-length_encoding | Run-length encoding | Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression... | #Scheme | Scheme | (define (run-length-decode v)
(apply string-append (map (lambda (p) (make-string (car p) (cdr p))) v)))
(define (run-length-encode s)
(let ((n (string-length s)))
(let loop ((i (- n 2)) (c (string-ref s (- n 1))) (k 1) (v '()))
(if (negative? i) (cons (cons k c) v)
(let ((x (string-ref s i)))
(if (char=? c... |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #11l | 11l | F addsub(x, y)
R (x + y, x - y)
V (summ, difference) = addsub(33, 12)
print(‘33 + 12 = ’summ)
print(‘33 - 12 = ’difference) |
http://rosettacode.org/wiki/RIPEMD-160 | RIPEMD-160 | RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Cod... | #Java | Java | import org.bouncycastle.crypto.digests.RIPEMD160Digest;
import org.bouncycastle.util.encoders.Hex;
public class RosettaRIPEMD160
{
public static void main (String[] argv) throws Exception
{
byte[] r = "Rosetta Code".getBytes("US-ASCII");
RIPEMD160Digest d = new RIPEMD160Digest();
d.upd... |
http://rosettacode.org/wiki/Resistor_mesh | Resistor mesh |
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure ResistMesh is
H, W : constant Positive := 10;
rowA, colA : constant Positive := 2; -- row/col indexed from 1
rowB : constant Positive := 7;
colB : constant Positive := 8;
type Ntype is (A, B, Free);
type Vtype is digits 15;
type Node is record
vo... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Fantom | Fantom |
class A
{
public Void doit (Int n)
{
echo ("known function called on $n")
}
// override the 'trap' method, which catches dynamic invocations of methods
override Obj? trap(Str name, Obj?[]? args := null)
{
try
{
return super.trap(name, args)
}
catch (UnknownSlotErr err)
{
... |
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call | Respond to an unknown method call | Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defin... | #Forth | Forth | include FMS-SI.f
include FMS-SILib.f
var x \ instantiate a class var object named x
x add: \ => "aborted: message not understood"
|
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #ALGOL_68 | ALGOL 68 | # returns original phrase with the order of the words reversed #
# a word is a sequence of non-blank characters #
PROC reverse word order = ( STRING original phrase )STRING:
BEGIN
STRING words reversed := "";
STRING separator := "";
INT start pos := LWB original... |
http://rosettacode.org/wiki/Repunit_primes | Repunit primes | Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In ... | #Raku | Raku | my $limit = 2700;
say "Repunit prime digits (up to $limit) in:";
.put for (2..16).hyper(:1batch).map: -> $base {
$base.fmt("Base %2d: ") ~ (1..$limit).grep(&is-prime).grep( (1 x *).parse-base($base).is-prime )
} |
http://rosettacode.org/wiki/Repunit_primes | Repunit primes | Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In ... | #Scheme | Scheme | ; Test whether any integer is a probable prime.
(define prime<probably>?
(lambda (n)
; Fast modular exponentiation.
(define modexpt
(lambda (b e m)
(cond
((zero? e) 1)
((even? e) (modexpt (mod (* b b) m) (div e 2) m))
((odd? e) (mod (* b (modexpt b (- e 1) m)) m))))... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Modula-3 | Modula-3 | MODULE Rot13 EXPORTS Main;
IMPORT Stdio, Rd, Wr;
VAR c: CHAR;
<*FATAL ANY*>
BEGIN
WHILE NOT Rd.EOF(Stdio.stdin) DO
c := Rd.GetChar(Stdio.stdin);
IF c >= 'A' AND c <= 'M' OR c >= 'a' AND c <= 'm' THEN
c := VAL(ORD((ORD(c) + 13)), CHAR);
ELSIF c >= 'N' AND c <= 'Z' OR c >= 'n' AND c <= 'z' THE... |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #Logo | Logo | make "roman.rules [
[1000 M] [900 CM] [500 D] [400 CD]
[ 100 C] [ 90 XC] [ 50 L] [ 40 XL]
[ 10 X] [ 9 IX] [ 5 V] [ 4 IV]
[ 1 I]
]
to roman :n [:rules :roman.rules] [:acc "||]
if empty? :rules [output :acc]
if :n < first first :rules [output (roman :n bf :rules :acc)]
output (roman :n - first first... |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Nim | Nim | import tables
let rdecode = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}.toTable
proc decode(roman: string): int =
for i in 0 ..< roman.high:
let (rd, rd1) = (rdecode[roman[i]], rdecode[roman[i+1]])
result += (if rd < rd1: -rd else: rd)
result += rdecode[roman[roman.high]]
for r i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.