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/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 numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#FreeBASIC_2
|
FreeBASIC
|
' FB 1.05.0 Win64
Function romanEncode(n As Integer) As String
If n < 1 OrElse n > 3999 Then Return "" '' can only encode numbers in range 1 to 3999
Dim roman1(0 To 2) As String = {"MMM", "MM", "M"}
Dim roman2(0 To 8) As String = {"CM", "DCCC", "DCC", "DC", "D", "CD", "CCC", "CC", "C"}
Dim roman3(0 To 8) As String = {"XC", "LXXX", "LXX", "LX", "L", "XL", "XXX", "XX", "X"}
Dim roman4(0 To 8) As String = {"IX", "VIII", "VII", "VI", "V", "IV", "III", "II", "I"}
Dim As Integer thousands, hundreds, tens, units
thousands = n \ 1000
n Mod= 1000
hundreds = n \ 100
n Mod= 100
tens = n \ 10
units = n Mod 10
Dim roman As String = ""
If thousands > 0 Then roman += roman1(3 - thousands)
If hundreds > 0 Then roman += roman2(9 - hundreds)
If tens > 0 Then roman += roman3(9 - tens)
If units > 0 Then roman += roman4(9 - units)
Return roman
End Function
Dim a(2) As Integer = {1990, 2008, 1666}
For i As Integer = 0 To 2
Print a(i); " => "; romanEncode(a(i))
Next
Print
Print "Press any key to quit"
Sleep
|
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 decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#J
|
J
|
rom2d=: [: (+/ .* _1^ 0,~ 2</\ ]) 1 5 10 50 100 500 1000 {~ 'IVXLCDM'&i.
|
http://rosettacode.org/wiki/Roots_of_a_function
|
Roots of a function
|
Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
|
#Tcl
|
Tcl
|
proc froots {lambda {start -3} {end 3} {step 0.0001}} {
set res {}
set lastsign [sgn [apply $lambda $start]]
for {set x $start} {$x <= $end} {set x [expr {$x + $step}]} {
set sign [sgn [apply $lambda $x]]
if {$sign != $lastsign} {
lappend res [format ~%.11f $x]
}
set lastsign $sign
}
return $res
}
proc sgn x {expr {($x>0) - ($x<0)}}
puts [froots {x {expr {$x**3 - 3*$x**2 + 2*$x}}}]
|
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:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#Racket
|
Racket
|
#lang racket
(require math)
(define history (make-hash '((paper . 1) (scissors . 1) (rock . 1))))
(define total 3)
(define (update-history! human-choice)
(set! total (+ total 1))
(hash-update! history human-choice add1 0))
(define (pick-one)
(sample
(discrete-dist '(paper scissors rock)
(map (λ (x) (hash-ref history x))
'(scissors paper rock)))))
(define (find-winner computer human)
(define order '(scissors paper rock scissors))
(cond
[(eq? computer human) 'none]
[(eq? (second (member computer order)) human) 'computer]
[ 'human]))
(define (game-loop)
(define computer-choice (pick-one))
(define human-choice (read))
(define winner (find-winner computer-choice human-choice))
(update-history! human-choice)
(displayln (~a "Computer picked " computer-choice ", "
"human picked " human-choice ", "
winner " wins."))
(game-loop))
(game-loop)
|
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.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#PHP
|
PHP
|
<?php
function encode($str)
{
return preg_replace_callback('/(.)\1*/', function ($match) {
return strlen($match[0]) . $match[1];
}, $str);
}
function decode($str)
{
return preg_replace_callback('/(\d+)(\D)/', function($match) {
return str_repeat($match[2], $match[1]);
}, $str);
}
echo encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'), PHP_EOL;
echo decode('12W1B12W3B24W1B14W'), PHP_EOL;
?>
|
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 input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
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
|
abcdefghijklomnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXZ.
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#Tcl
|
Tcl
|
set haystack {Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo}
foreach needle {Bush Washington} {
if {[set idx [lsearch -exact $haystack $needle]] == -1} {
error "$needle does not appear in the haystack"
} else {
puts "$needle appears at index $idx in the haystack"
}
}
|
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 numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#FutureBasic
|
FutureBasic
|
window 1
local fn DecimaltoRoman( decimal as short ) as Str15
short arabic(12)
Str15 roman(12)
long i
Str15 result : result = ""
arabic(0) = 1000 : arabic(1) = 900 : arabic(2) = 500 : arabic(3) = 400
arabic(4) = 100 : arabic(5) = 90 : arabic(6) = 50 : arabic(7) = 40
arabic(8) = 10 : arabic(9) = 9 : arabic(10) = 5 : arabic(11) = 4: arabic(12) = 1
roman(0) = "M" : roman(1) = "CM" : roman(2) = "D" : roman(3) = "CD"
roman(4) = "C" : roman(5) = "XC" : roman(6) = "L" : roman(7) = "XL"
roman(8) = "X" : roman(9) = "IX" : roman(10) = "V" : roman(11) = "IV" : roman(12) = "I"
for i = 0 to 12
while ( decimal >= arabic(i) )
result = result + roman(i)
decimal = decimal - arabic(i)
wend
next i
if result == "" then result = "Zepherium"
end fn = result
print "1990 = "; fn DecimaltoRoman( 1990 )
print "2008 = "; fn DecimaltoRoman( 2008 )
print "2016 = "; fn DecimaltoRoman( 2016 )
print "1666 = "; fn DecimaltoRoman( 1666 )
print "3888 = "; fn DecimaltoRoman( 3888 )
print "1914 = "; fn DecimaltoRoman( 1914 )
print "1000 = "; fn DecimaltoRoman( 1000 )
print " 513 = "; fn DecimaltoRoman( 513 )
print " 33 = "; fn DecimaltoRoman( 33 )
HandleEvents
|
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 decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#Java_2
|
Java
|
public class Roman {
private static int decodeSingle(char letter) {
switch(letter) {
case 'M': return 1000;
case 'D': return 500;
case 'C': return 100;
case 'L': return 50;
case 'X': return 10;
case 'V': return 5;
case 'I': return 1;
default: return 0;
}
}
public static int decode(String roman) {
int result = 0;
String uRoman = roman.toUpperCase(); //case-insensitive
for(int i = 0;i < uRoman.length() - 1;i++) {//loop over all but the last character
//if this character has a lower value than the next character
if (decodeSingle(uRoman.charAt(i)) < decodeSingle(uRoman.charAt(i+1))) {
//subtract it
result -= decodeSingle(uRoman.charAt(i));
} else {
//add it
result += decodeSingle(uRoman.charAt(i));
}
}
//decode the last character, which is always added
result += decodeSingle(uRoman.charAt(uRoman.length()-1));
return result;
}
public static void main(String[] args) {
System.out.println(decode("MCMXC")); //1990
System.out.println(decode("MMVIII")); //2008
System.out.println(decode("MDCLXVI")); //1666
}
}
|
http://rosettacode.org/wiki/Roots_of_a_function
|
Roots of a function
|
Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
|
#TI-89_BASIC
|
TI-89 BASIC
|
import "/fmt" for Fmt
var secant = Fn.new { |f, x0, x1|
var f0 = 0
var f1 = f.call(x0)
for (i in 0...100) {
f0 = f1
f1 = f.call(x1)
if (f1 == 0) return [x1, "exact"]
if ((x1-x0).abs < 1e-6) return [x1, "approximate"]
var t = x0
x0 = x1
x1 = x1-f1*(x1-t)/(f1-f0)
}
return [0, ""]
}
var findRoots = Fn.new { |f, lower, upper, step|
var x0 = lower
var x1 = lower + step
while (x0 < upper) {
x1 = (x1 < upper) ? x1 : upper
var res = secant.call(f, x0, x1)
var r = res[0]
var status = res[1]
if (status != "" && r >= x0 && r < x1) {
Fmt.print(" $6.3f $s", r, status)
}
x0 = x1
x1 = x1 + step
}
}
var example = Fn.new { |x| x*x*x - 3*x*x + 2*x }
findRoots.call(example, -0.5, 2.6, 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:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#Raku
|
Raku
|
my %vs = (
options => [<Rock Paper Scissors>],
ro => {
ro => [ 2, '' ],
pa => [ 1, 'Paper covers Rock: ' ],
sc => [ 0, 'Rock smashes Scissors: ' ]
},
pa => {
ro => [ 0, 'Paper covers Rock: ' ],
pa => [ 2, '' ],
sc => [ 1, 'Scissors cut Paper: ' ]
},
sc => {
ro => [ 1, 'Rock smashes Scissors: '],
pa => [ 0, 'Scissors cut Paper: ' ],
sc => [ 2, '' ]
}
);
my %choices = %vs<options>.map({; $_.substr(0,2).lc => $_ });
my $keys = %choices.keys.join('|');
my $prompt = %vs<options>.map({$_.subst(/(\w\w)/, -> $/ {"[$0]"})}).join(' ')~"? ";
my %weight = %choices.keys »=>» 1;
my @stats = 0,0,0;
my $round;
while my $player = (prompt "Round {++$round}: " ~ $prompt).lc {
$player.=substr(0,2);
say 'Invalid choice, try again.' and $round-- and next
unless $player.chars == 2 and $player ~~ /<$keys>/;
my $computer = (flat %weight.keys.map( { $_ xx %weight{$_} } )).pick;
%weight{$_.key}++ for %vs{$player}.grep( { $_.value[0] == 1 } );
my $result = %vs{$player}{$computer}[0];
@stats[$result]++;
say "You chose %choices{$player}, Computer chose %choices{$computer}.";
print %vs{$player}{$computer}[1];
print ( 'You win!', 'You Lose!','Tie.' )[$result];
say " - (W:{@stats[0]} L:{@stats[1]} T:{@stats[2]})\n",
};
|
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.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#Picat
|
Picat
|
rle(S) = RLE =>
RLE = "",
Char = S[1],
I = 2,
Count = 1,
while (I <= S.len)
if Char == S[I] then
Count := Count + 1
else
RLE := RLE ++ Count.to_string() ++ Char.to_string(),
Count := 1,
Char := S[I]
end,
I := I + 1
end,
RLE := RLE ++ Count.to_string() ++ Char.to_string().
|
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 input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
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
|
abcdefghijklomnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXZ.
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#TorqueScript
|
TorqueScript
|
function findIn(%haystack,%needles)
{
%hc = getWordCount(%haystack);
%nc = getWordCount(%needles);
for(%i=0;%i<%nc;%i++)
{
%nword = getWord(%needles,%i);
%index[%nword] = -1;
}
for(%i=0;%i<%hc;%i++)
{
%hword = getWord(%haystack,%i);
for(%j=0;%j<%nc;%j++)
{
%nword = getWord(%needles,%j);
if(%hword $= %nword)
{
%index[%nword] = %i;
}
}
}
for(%i=0;%i<%nc;%i++)
{
%nword = getWord(%needles,%i);
%string = %string SPC %nword@"_"@%index[%nword];
%string = trim(%string);
}
return %string;
}
|
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 numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#Go
|
Go
|
package main
import "fmt"
var (
m0 = []string{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}
m1 = []string{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}
m2 = []string{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}
m3 = []string{"", "M", "MM", "MMM", "I̅V̅",
"V̅", "V̅I̅", "V̅I̅I̅", "V̅I̅I̅I̅", "I̅X̅"}
m4 = []string{"", "X̅", "X̅X̅", "X̅X̅X̅", "X̅L̅",
"L̅", "L̅X̅", "L̅X̅X̅", "L̅X̅X̅X̅", "X̅C̅"}
m5 = []string{"", "C̅", "C̅C̅", "C̅C̅C̅", "C̅D̅",
"D̅", "D̅C̅", "D̅C̅C̅", "D̅C̅C̅C̅", "C̅M̅"}
m6 = []string{"", "M̅", "M̅M̅", "M̅M̅M̅"}
)
func formatRoman(n int) (string, bool) {
if n < 1 || n >= 4e6 {
return "", false
}
// this is efficient in Go. the seven operands are evaluated,
// then a single allocation is made of the exact size needed for the result.
return m6[n/1e6] + m5[n%1e6/1e5] + m4[n%1e5/1e4] + m3[n%1e4/1e3] +
m2[n%1e3/1e2] + m1[n%100/10] + m0[n%10],
true
}
func main() {
// show three numbers mentioned in task descriptions
for _, n := range []int{1990, 2008, 1666} {
r, ok := formatRoman(n)
if ok {
fmt.Println(n, "==", r)
} else {
fmt.Println(n, "not representable")
}
}
}
|
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 decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#JavaScript
|
JavaScript
|
var Roman = {
Values: [['CM', 900], ['CD', 400], ['XC', 90], ['XL', 40], ['IV', 4],
['IX', 9], ['V', 5], ['X', 10], ['L', 50],
['C', 100], ['M', 1000], ['I', 1], ['D', 500]],
UnmappedStr : 'Q',
parse: function(str) {
var result = 0
for (var i=0; i<Roman.Values.length; ++i) {
var pair = Roman.Values[i]
var key = pair[0]
var value = pair[1]
var regex = RegExp(key)
while (str.match(regex)) {
result += value
str = str.replace(regex, Roman.UnmappedStr)
}
}
return result
}
}
var test_data = ['MCMXC', 'MDCLXVI', 'MMVIII']
for (var i=0; i<test_data.length; ++i) {
var test_datum = test_data[i]
print(test_datum + ": " + Roman.parse(test_datum))
}
|
http://rosettacode.org/wiki/Roots_of_a_function
|
Roots of a function
|
Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
|
#Wren
|
Wren
|
import "/fmt" for Fmt
var secant = Fn.new { |f, x0, x1|
var f0 = 0
var f1 = f.call(x0)
for (i in 0...100) {
f0 = f1
f1 = f.call(x1)
if (f1 == 0) return [x1, "exact"]
if ((x1-x0).abs < 1e-6) return [x1, "approximate"]
var t = x0
x0 = x1
x1 = x1-f1*(x1-t)/(f1-f0)
}
return [0, ""]
}
var findRoots = Fn.new { |f, lower, upper, step|
var x0 = lower
var x1 = lower + step
while (x0 < upper) {
x1 = (x1 < upper) ? x1 : upper
var res = secant.call(f, x0, x1)
var r = res[0]
var status = res[1]
if (status != "" && r >= x0 && r < x1) {
Fmt.print(" $6.3f $s", r, status)
}
x0 = x1
x1 = x1 + step
}
}
var example = Fn.new { |x| x*x*x - 3*x*x + 2*x }
findRoots.call(example, -0.5, 2.6, 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:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#Rascal
|
Rascal
|
import Prelude;
rel[str, str] whatbeats = {<"Rock", "Scissors">, <"Scissors", "Paper">, <"Paper", "Rock">};
list[str] ComputerChoices = ["Rock", "Paper", "Scissors"];
str CheckWinner(a, b){
if(b == getOneFrom(whatbeats[a]))
return a;
elseif(a == getOneFrom(whatbeats[b]))
return b;
else return "Nobody";
}
public str RPS(human){
computer = getOneFrom(ComputerChoices);
x = if(human == "Rock") "Paper"; elseif(human == "Paper") "Scissors"; else "Rock";
ComputerChoices += x;
return "Computer played <computer>. <CheckWinner(human, computer)> wins!";
}
|
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.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#PicoLisp
|
PicoLisp
|
(de encode (Str)
(pack
(make
(for (Lst (chop Str) Lst)
(let (N 1 C)
(while (= (setq C (pop 'Lst)) (car Lst))
(inc 'N) )
(link N C) ) ) ) ) )
(de decode (Str)
(pack
(make
(let N 0
(for C (chop Str)
(if (>= "9" C "0")
(setq N (+ (format C) (* 10 N)))
(do N (link C))
(zero N) ) ) ) ) ) )
(and
(prinl "Data: " "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW")
(prinl "Encoded: " (encode @))
(prinl "Decoded: " (decode @)) )
|
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 input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
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
|
#Lasso
|
Lasso
|
// Extend the string type
define string->rot13 => {
local(
rot13 = bytes,
i, a, b
)
with char in .eachCharacter
let int = #char->integer
do {
// We only modify these ranges, set range if we should modify
#int >= 65 and #int < 91 ? local(a=65,b=91) |
#int >= 97 and #int < 123 ? local(a=97,b=123) | local(a=0,b=0)
if(#a && #b) => {
#i = (#int+13) % #b // loop back if past ceiling (#b)
#i += #a * (1 - #i / #a) // offset if below floor (#a)
#rot13->import8bits(#i) // import the new character
else
#rot13->append(#char) // just append the character
}
}
return #rot13->asstring
}
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT
SET haystack="Zig'Zag'Wally'Ronald'Bush'Krusty'Charlie'Bush'Bozo"
PRINT "haystack=",haystack
LOOP needle="Washington'Bush'Wally"
SET table =QUOTES (needle)
BUILD S_TABLE needle = table
IF (haystack.ct.needle) THEN
BUILD R_TABLE needle = table
SET position=FILTER_INDEX(haystack,needle,-)
RELEASE R_TABLE needle
PRINT "haystack contains ", needle, " on position(s): ",position
ELSE
PRINT "haystack not contains ",needle
ENDIF
RELEASE S_TABLE needle
ENDLOOP
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#UNIX_Shell
|
UNIX Shell
|
if [ $1 ];then
haystack="Zip Zag Wally Ronald Bush Krusty Charlie Bush Bozo"
index=$(echo $haystack|tr " " "\n"|grep -in "^$1$")
if [ $? = 0 ];then
quantity_of_hits=$(echo $index|tr " " "\n"|wc -l|tr -d " ")
first_index=$(echo $index|cut -f 1 -d ":")
if [ $quantity_of_hits = 1 ];then
echo The sole index for $1 is: $first_index
else
echo The smallest index for $1 is: $first_index
greatest_index=$(echo $index|tr " " "\n"|tail -1|cut -f 1 -d ":")
echo "The greatest index for $1 is: $greatest_index";fi
else echo $1 is absent from haystatck.;fi
else echo Must provide string to find in haystack.;fi
|
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 numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#Golo
|
Golo
|
#!/usr/bin/env golosh
----
This module takes a decimal integer and converts it to a Roman numeral.
----
module Romannumeralsencode
augment java.lang.Integer {
function digits = |this| {
var remaining = this
let digits = vector[]
while remaining > 0 {
digits: prepend(remaining % 10)
remaining = remaining / 10
}
return digits
}
----
123: digitsWithPowers() will return [[1, 2], [2, 1], [3, 0]]
----
function digitsWithPowers = |this| -> vector[
[ this: digits(): get(i), (this: digits(): size() - 1) - i ] for (var i = 0, i < this: digits(): size(), i = i + 1)
]
function encode = |this| {
require(this > 0, "the integer must be positive!")
let romanPattern = |digit, powerOf10| -> match {
when digit == 1 then i
when digit == 2 then i + i
when digit == 3 then i + i + i
when digit == 4 then i + v
when digit == 5 then v
when digit == 6 then v + i
when digit == 7 then v + i + i
when digit == 8 then v + i + i + i
when digit == 9 then i + x
otherwise ""
} with {
i, v, x = [
[ "I", "V", "X" ],
[ "X", "L", "C" ],
[ "C", "D", "M" ],
[ "M", "?", "?" ]
]: get(powerOf10)
}
return vector[ romanPattern(digit, power) foreach digit, power in this: digitsWithPowers() ]: join("")
}
}
function main = |args| {
println("1990 == MCMXC? " + (1990: encode() == "MCMXC"))
println("2008 == MMVIII? " + (2008: encode() == "MMVIII"))
println("1666 == MDCLXVI? " + (1666: encode() == "MDCLXVI"))
}
|
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 decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#jq
|
jq
|
def fromRoman:
def addRoman(n):
if length == 0 then n
elif startswith("M") then .[1:] | addRoman(1000 + n)
elif startswith("CM") then .[2:] | addRoman(900 + n)
elif startswith("D") then .[1:] | addRoman(500 + n)
elif startswith("CD") then .[2:] | addRoman(400 + n)
elif startswith("C") then .[1:] | addRoman(100 + n)
elif startswith("XC") then .[2:] | addRoman(90 + n)
elif startswith("L") then .[1:] | addRoman(50 + n)
elif startswith("XL") then .[2:] | addRoman(40 + n)
elif startswith("X") then .[1:] | addRoman(10 + n)
elif startswith("IX") then .[2:] | addRoman(9 + n)
elif startswith("V") then .[1:] | addRoman(5 + n)
elif startswith("IV") then .[2:] | addRoman(4 + n)
elif startswith("I") then .[1:] | addRoman(1 + n)
else
error("invalid Roman numeral: " + tostring)
end;
addRoman(0);
|
http://rosettacode.org/wiki/Roots_of_a_function
|
Roots of a function
|
Task
Create a program that finds and outputs the roots of a given function, range and (if applicable) step width.
The program should identify whether the root is exact or approximate.
For this task, use: ƒ(x) = x3 - 3x2 + 2x
|
#zkl
|
zkl
|
fcn findRoots(f,start,stop,step,eps){
[start..stop,step].filter('wrap(x){ f(x).closeTo(0.0,eps) })
}
|
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:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#Red
|
Red
|
Red [Purpose: "Implement a rock-paper-scissors game with weighted probability"]
prior: rejoin choices: ["r" "p" "s"]
while [
find choices pchoice: ask "choose rock: r, paper: p, or scissors: s^/"
] [
print ["AI Draws:" cchoice: random/only prior]
cwin: select "rpsr" pchoice
close: select "rspr" pchoice
print case [
pchoice = cchoice ["tie"]
cchoice = cwin ["you lose"]
'else ["you win"]
]
append prior cwin ;adds what would have beaten player
remove find prior close ;removes what would have lost to player
]
|
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.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#PL.2FI
|
PL/I
|
declare (c1, c2) character (1);
declare run_length fixed binary;
declare input file;
open file (input) title ('/RLE.DAT,type(text),recsize(20000)');
on endfile (input) go to epilog;
get file (input) edit (c1) (a(1));
run_length = 1;
do forever;
get file (input) edit (c2) (a(1));
if c1 = c2 then
run_length = run_length + 1;
else
do; put edit (trim(run_length), c1) (a); run_length=1; end;
c1 = c2;
end;
epilog:
put edit (trim(run_length), c1) (a);
put skip;
/* The reverse of the above operation: */
declare c character (1);
declare i fixed binary;
declare new file;
open file (new) title ('/NEW.DAT,type(text),recsize(20000)');
on endfile (new) stop;
do forever;
run_length = 0;
do forever;
get file (new) edit (c) (a(1));
if index('0123456789', c) = 0 then leave;
run_length = run_length*10 + c;
end;
put edit ((c do i = 1 to run_length)) (a);
end;
|
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 input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
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
|
#Liberty_BASIC
|
Liberty BASIC
|
input "Type some text to be encoded, then ENTER. ";tx$
tex$ = Rot13$(tx$)
print tex$
'check
print Rot13$(tex$)
wait
Function Rot13$(t$)
if t$="" then
Rot13$=""
exit function
end if
for i = 1 to len(t$)
c$=mid$(t$,i,1)
ch$=c$
if (asc(c$)>=asc("A")) and (asc(c$)<=asc("Z")) then
ch$=chr$(asc(c$)+13)
if (asc(ch$)>asc("Z")) then ch$=chr$(asc(ch$)-26)
end if
if (asc(c$)>=asc("a")) and (asc(c$)<=asc("z")) then
ch$=chr$(asc(c$)+13)
if (asc(ch$)>asc("z")) then ch$=chr$(asc(ch$)-26)
end if
rot$=rot$+ch$
next
Rot13$=rot$
end function
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#Ursala
|
Ursala
|
#import std
indices = ||<'missing'>!% ~&nSihzXB+ ~&lrmPE~|^|/~& num
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#VBA
|
VBA
|
Function IsInArray(stringToBeFound As Variant, arr As Variant, _
Optional start As Integer = 1, Optional reverse As Boolean = False) As Long
'Adapted from https://stackoverflow.com/questions/12414168/use-of-custom-data-types-in-vba
Dim i As Long, lo As Long, hi As Long, stp As Long
' default return value if value not found in array
IsInArray = -1
If reverse Then
lo = UBound(arr): hi = start: stp = -1
Else
lo = start: hi = UBound(arr): stp = 1
End If
For i = lo To hi Step stp 'start in stead of LBound(arr)
If StrComp(stringToBeFound, arr(i), vbTextCompare) = 0 Then
IsInArray = i
Exit For
End If
Next i
End Function
Public Sub search_a_list()
Dim haystack() As Variant, needles() As Variant
haystack = [{"Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"}]
needles = [{"Washington","Bush"}]
For i = 1 To 2
If IsInArray(needles(i), haystack) = -1 Then
Debug.Print needles(i); " not found in haystack."
Else
Debug.Print needles(i); " is at position "; CStr(IsInArray(needles(i), haystack)); ".";
Debug.Print " And last position is ";
Debug.Print CStr(IsInArray(needles(i), haystack, 1, True)); "."
End If
Next i
End Sub
|
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 numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#Groovy
|
Groovy
|
symbols = [ 1:'I', 4:'IV', 5:'V', 9:'IX', 10:'X', 40:'XL', 50:'L', 90:'XC', 100:'C', 400:'CD', 500:'D', 900:'CM', 1000:'M' ]
def roman(arabic) {
def result = ""
symbols.keySet().sort().reverse().each {
while (arabic >= it) {
arabic-=it
result+=symbols[it]
}
}
return result
}
assert roman(1) == 'I'
assert roman(2) == 'II'
assert roman(4) == 'IV'
assert roman(8) == 'VIII'
assert roman(16) == 'XVI'
assert roman(32) == 'XXXII'
assert roman(25) == 'XXV'
assert roman(64) == 'LXIV'
assert roman(128) == 'CXXVIII'
assert roman(256) == 'CCLVI'
assert roman(512) == 'DXII'
assert roman(954) == 'CMLIV'
assert roman(1024) == 'MXXIV'
assert roman(1666) == 'MDCLXVI'
assert roman(1990) == 'MCMXC'
assert roman(2008) == 'MMVIII'
|
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 decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#Jsish
|
Jsish
|
prompt$ jsish -e 'require("Roman"); puts(Roman.fromRoman("MDCLXVI"));'
1666
|
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:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#REXX
|
REXX
|
/*REXX program plays rock─paper─scissors with a human; tracks what human tends to use. */
!= '────────'; err=! "***error***"; @.=0 /*some constants for this program. */
prompt= ! 'Please enter one of: Rock Paper Scissors (or Quit)'
$.p= 'paper' ; $.s= "scissors"; $.r= 'rock' /*list of the choices in this program. */
t.p= $.r ; t.s= $.p ; t.r= $.s /*thingys that beats stuff. */
w.p= $.s ; w.s= $.r ; w.r= $.p /*stuff " " thingys. */
b.p= 'covers'; b.s= "cuts" ; b.r= 'breaks' /*verbs: how the choice wins. */
do forever; say; say prompt; say /*prompt the CBLF; then get a response.*/
c= word($.p $.s $.r, random(1, 3) ) /*choose the computer's first pick. */
m= max(@.r, @.p, @.s); c= w.r /*prepare to examine the choice history*/
if @.p==m then c= w.p /*emulate JC's: The Amazing Karnac. */
if @.s==m then c= w.s /* " " " " " */
c1= left(c, 1) /*C1 is used for faster comparing. */
parse pull u; a= strip(u) /*get the CBLF's choice/pick (answer). */
upper a c1 ; a1= left(a, 1) /*uppercase choices, get 1st character.*/
ok= 0 /*indicate answer isn't OK (so far). */
select /*process/verify the CBLF's choice. */
when words(u)==0 then say err 'nothing entered'
when words(u)>1 then say err 'too many choices: ' u
when abbrev('QUIT', a) then do; say ! "quitting."; exit; end
when abbrev('ROCK', a) |,
abbrev('PAPER', a) |,
abbrev('SCISSORS',a) then ok=1 /*Yes? This is a valid answer by CBLF.*/
otherwise say err 'you entered a bad choice: ' u
end /*select*/
if \ok then iterate /*answer ¬OK? Then get another choice.*/
@.a1= @.a1 + 1 /*keep a history of the CBLF's choices.*/
say ! 'computer chose: ' c
if a1== c1 then do; say ! 'draw.'; iterate; end
if $.a1==t.c1 then say ! 'the computer wins. ' ! $.c1 b.c1 $.a1
else say ! 'you win! ' ! $.a1 b.a1 $.c1
end /*forever*/ /*stick a fork in it, we're all done. */
|
http://rosettacode.org/wiki/Rhonda_numbers
|
Rhonda numbers
|
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.
25662 is a Rhonda number to base-10. The prime factorization is 2 × 3 × 7 × 13 × 47; the product of its base-10 digits is equal to the base times the sum of its prime factors:
2 × 5 × 6 × 6 × 2 = 720 = 10 × (2 + 3 + 7 + 13 + 47)
Rhonda numbers only exist in bases that are not a prime.
Rhonda numbers to base 10 always contain at least 1 digit 5 and always contain at least 1 even digit.
Task
For the non-prime bases b from 2 through 16 , find and display here, on this page, at least the first 10 Rhonda numbers to base b. Display the found numbers at least in base 10.
Stretch
Extend out to base 36.
See also
Wolfram Mathworld - Rhonda numbers
Numbers Aplenty - Rhonda numbers
OEIS:A100968 - Integers n that are Rhonda numbers to base 4
OEIS:A100969 - Integers n that are Rhonda numbers to base 6
OEIS:A100970 - Integers n that are Rhonda numbers to base 8
OEIS:A100973 - Integers n that are Rhonda numbers to base 9
OEIS:A099542 - Rhonda numbers to base 10
OEIS:A100971 - Integers n that are Rhonda numbers to base 12
OEIS:A100972 - Integers n that are Rhonda numbers to base 14
OEIS:A100974 - Integers n that are Rhonda numbers to base 15
OEIS:A100975 - Integers n that are Rhonda numbers to base 16
OEIS:A255735 - Integers n that are Rhonda numbers to base 18
OEIS:A255732 - Rhonda numbers in vigesimal number system (base 20)
OEIS:A255736 - Integers that are Rhonda numbers to base 30
Related Task: Smith numbers
|
#C.2B.2B
|
C++
|
#include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
int digit_product(int base, int n) {
int product = 1;
for (; n != 0; n /= base)
product *= n % base;
return product;
}
int prime_factor_sum(int n) {
int sum = 0;
for (; (n & 1) == 0; n >>= 1)
sum += 2;
for (int p = 3; p * p <= n; p += 2)
for (; n % p == 0; n /= p)
sum += p;
if (n > 1)
sum += n;
return sum;
}
bool is_prime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
bool is_rhonda(int base, int n) {
return digit_product(base, n) == base * prime_factor_sum(n);
}
std::string to_string(int base, int n) {
assert(base <= 36);
static constexpr char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
std::string str;
for (; n != 0; n /= base)
str += digits[n % base];
std::reverse(str.begin(), str.end());
return str;
}
int main() {
const int limit = 15;
for (int base = 2; base <= 36; ++base) {
if (is_prime(base))
continue;
std::cout << "First " << limit << " Rhonda numbers to base " << base
<< ":\n";
int numbers[limit];
for (int n = 1, count = 0; count < limit; ++n) {
if (is_rhonda(base, n))
numbers[count++] = n;
}
std::cout << "In base 10:";
for (int i = 0; i < limit; ++i)
std::cout << ' ' << numbers[i];
std::cout << "\nIn base " << base << ':';
for (int i = 0; i < limit; ++i)
std::cout << ' ' << to_string(base, numbers[i]);
std::cout << "\n\n";
}
}
|
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.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#PowerBASIC
|
PowerBASIC
|
FUNCTION RLDecode (i AS STRING) AS STRING
DIM Loop0 AS LONG, rCount AS STRING, outP AS STRING, m AS STRING
FOR Loop0 = 1 TO LEN(i)
m = MID$(i, Loop0, 1)
SELECT CASE m
CASE "0" TO "9"
rCount = rCount & m
CASE ELSE
IF LEN(rCount) THEN
outP = outP & STRING$(VAL(rCount), m)
rCount=""
ELSE
outP = outP & m
END IF
END SELECT
NEXT
FUNCTION = outP
END FUNCTION
FUNCTION RLEncode (i AS STRING) AS STRING
DIM tmp1 AS STRING, tmp2 AS STRING, outP AS STRING
DIM Loop0 AS LONG, rCount AS LONG
tmp1 = MID$(i, 1, 1)
tmp2 = tmp1
rCount = 1
FOR Loop0 = 2 TO LEN(i)
tmp1 = MID$(i, Loop0, 1)
IF tmp1 <> tmp2 THEN
outP = outP & TRIM$(STR$(rCount)) & tmp2
tmp2 = tmp1
rCount = 1
ELSE
INCR rCount
END IF
NEXT
outP = outP & TRIM$(STR$(rCount))
outP = outP & tmp2
FUNCTION = outP
END FUNCTION
FUNCTION PBMAIN () AS LONG
DIM initial AS STRING, encoded AS STRING, decoded AS STRING
initial = INPUTBOX$("Type something.")
encoded = RLEncode(initial)
decoded = RLDecode(encoded)
'in PB/Win, "?" = MSGBOX; in PB/DOS & PB/CC. "?" = PRINT
? initial & $CRLF & encoded & $CRLF & decoded
END FUNCTION
|
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 input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
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
|
#Limbo
|
Limbo
|
implement Rot13;
include "sys.m"; sys: Sys;
include "draw.m";
Rot13: module
{
init: fn(ctxt: ref Draw->Context, argv: list of string);
};
stdout: ref Sys->FD;
tab: array of int;
init(nil: ref Draw->Context, args: list of string)
{
sys = load Sys Sys->PATH;
stdout = sys->fildes(1);
inittab();
args = tl args;
if(args == nil)
args = "-" :: nil;
for(; args != nil; args = tl args){
file := hd args;
if(file != "-"){
fd := sys->open(file, Sys->OREAD);
if(fd == nil){
sys->fprint(sys->fildes(2), "rot13: cannot open %s: %r\n", file);
raise "fail:bad open";
}
rot13cat(fd, file);
}else
rot13cat(sys->fildes(0), "<stdin>");
}
}
inittab()
{
tab = array[256] of int;
for(i := 0; i < 256; i++)
tab[i] = i;
for(i = 'a'; i <= 'z'; i++)
tab[i] = (((i - 'a') + 13) % 26) + 'a';
for(i = 'A'; i <= 'Z'; i++)
tab[i] = (((i - 'A') + 13) % 26) + 'A';
}
rot13(s: string): string
{
for(i := 0; i < len s; i++) {
if(s[i] < 256)
s[i] = tab[s[i]];
}
return s;
}
rot13cat(fd: ref Sys->FD, file: string)
{
buf := array[Sys->ATOMICIO] of byte;
while((n := sys->read(fd, buf, len buf)) > 0) {
obuf := array of byte (rot13(string buf));
if(sys->write(stdout, obuf, n) < n) {
sys->fprint(sys->fildes(2), "rot13: write error: %r\n");
raise "fail:write error";
}
}
if(n < 0) {
sys->fprint(sys->fildes(2), "rot13: error reading %s: %r\n", file);
raise "fail:read error";
}
}
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#VBScript
|
VBScript
|
data = "foo,bar,baz,quux,quuux,quuuux,bazola,ztesch,foo,bar,thud,grunt," &_
"foo,bar,bletch,foo,bar,fum,fred,jim,sheila,barney,flarp,zxc," &_
"spqr,wombat,shme,foo,bar,baz,bongo,spam,eggs,snork,foo,bar," &_
"zot,blarg,wibble,toto,titi,tata,tutu,pippo,pluto,paperino,aap," &_
"noot,mies,oogle,foogle,boogle,zork,gork,bork"
haystack = Split(data,",")
Do
WScript.StdOut.Write "Word to search for? (Leave blank to exit) "
needle = WScript.StdIn.ReadLine
If needle <> "" Then
found = 0
For i = 0 To UBound(haystack)
If UCase(haystack(i)) = UCase(needle) Then
found = 1
WScript.StdOut.Write "Found " & Chr(34) & needle & Chr(34) & " at index " & i
WScript.StdOut.WriteLine
End If
Next
If found < 1 Then
WScript.StdOut.Write Chr(34) & needle & Chr(34) & " not found."
WScript.StdOut.WriteLine
End If
Else
Exit do
End If
Loop
|
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 numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#Haskell
|
Haskell
|
digit :: Char -> Char -> Char -> Integer -> String
digit x y z k =
[[x], [x, x], [x, x, x], [x, y], [y], [y, x], [y, x, x], [y, x, x, x], [x, z]] !!
(fromInteger k - 1)
toRoman :: Integer -> String
toRoman 0 = ""
toRoman x
| x < 0 = error "Negative roman numeral"
toRoman x
| x >= 1000 = 'M' : toRoman (x - 1000)
toRoman x
| x >= 100 = digit 'C' 'D' 'M' q ++ toRoman r
where
(q, r) = x `divMod` 100
toRoman x
| x >= 10 = digit 'X' 'L' 'C' q ++ toRoman r
where
(q, r) = x `divMod` 10
toRoman x = digit 'I' 'V' 'X' x
main :: IO ()
main = print $ toRoman <$> [1999, 25, 944]
|
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 decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#Julia
|
Julia
|
function parseroman(rnum::AbstractString)
romandigits = Dict('I' => 1, 'V' => 5, 'X' => 10, 'L' => 50,
'C' => 100, 'D' => 500, 'M' => 1000)
mval = accm = 0
for d in reverse(uppercase(rnum))
val = try
romandigits[d]
catch
throw(DomainError())
end
if val > mval maxval = val end
if val < mval
accm -= val
else
accm += val
end
end
return accm
end
|
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:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#Ring
|
Ring
|
# Project : Rock-paper-scissors
load "stdlib.ring"
load "guilib.ring"
width = 200
height = 200
myChose = 1
compChose = 1
nextPlayer = 1
myScore = 0
compScore = 0
C_FONTSIZE = 15
C_ROCK = "images/rock.jpg"
C_PAPER = "images/paper.jpg"
C_SCISSORS = "images/scissors.jpg"
ChoseList = [C_ROCK,C_PAPER,C_SCISSORS]
Button = list(len(ChoseList))
app = new QApp
{
StyleFusion()
win = new QWidget() {
setWindowTitle('Stone Paper Scissors Game')
setWinIcon(self,C_ROCK)
setStyleSheet("background-color:cyan;")
setWindowFlags(Qt_Window | Qt_WindowTitleHint | Qt_WindowCloseButtonHint | Qt_CustomizeWindowHint)
reSize(900,600)
winheight = height()
fontSize = 8 + (winheight / 100)
for Col = 1 to len(ChoseList)
Button[Col] = new QPushButton(win) {
x = 150+(Col-1)*height
setgeometry(x,35,width,height)
setStyleSheet("background-color:white;")
seticon(new qicon(new qpixmap(ChoseList[Col])))
setIconSize(new qSize(200,200))
setclickevent("ButtonPress(" + string(Col) + ")")
setSizePolicy(1,1)
}
next
labelMyChose = new QLabel(win) {
setgeometry(200,250,150,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("My Chose:")
}
labelCompChose = new QLabel(win) {
setgeometry(580,250,150,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("Comp Chose:")
}
labelScoreEnd = new QLabel(win) {
setgeometry(0,510,win.width(),30)
setAlignment(Qt_AlignHCenter | Qt_AlignVCenter)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("")
}
btnMyChose = new QPushButton(win) {
setgeometry(150,300,width,height)
setStyleSheet("background-color:white;")
}
btnCompChose = new QPushButton(win) {
setgeometry(550,300,width,height)
setStyleSheet("background-color:white;")
}
btnNewGame = new QPushButton(win) {
setgeometry(170,550,150,40)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
setclickevent("NewGame()")
settext("New Game")
}
btnExit = new QPushButton(win) {
setgeometry(580,550,150,40)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
setclickevent("Close()")
settext("Exit")
}
labelMyScore = new QLabel(win) {
setgeometry(170,0,100,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("My Score: ")
}
labelMyScoreSum = new QLabel(win) {
setgeometry(300,0,100,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("")
}
labelCompScore = new QLabel(win) {
setgeometry(580,0,130,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("Comp Score: ")
}
labelCompScoreSum = new QLabel(win) {
setgeometry(730,0,100,30)
setFont(new qFont("Verdana",C_FONTSIZE,50,0))
settext("")
}
show()
}
exec()
}
func ButtonPress Col
if nextPlayer = 1
myChose = Col
btnMyChose {
seticon(new qicon(new qpixmap(ChoseList[Col])))
setIconSize(new qSize(width,height))
}
nextPlayer = 2
compChose()
ok
func compChose
rndChose = random(len(ChoseList)-1) + 1
compChose = rndChose
btnCompChose {
seticon(new qicon(new qpixmap(ChoseList[compChose])))
setIconSize(new qSize(width,height))
}
nextPlayer = 1
Result()
func Result
if (myChose = compChose)
labelScoreEnd.settext("Draw!")
ok
if (myChose = 1) and (compChose = 2)
labelScoreEnd.settext("Computer Win!")
compScore = compScore + 1
labelCompScoreSum.settext(string(compScore))
ok
if (myChose = 1) and (compChose = 3)
labelScoreEnd.settext("I Win!")
myScore = myScore + 1
labelMyScoreSum.settext(string(myScore))
ok
if (myChose = 2) and (compChose = 3)
labelScoreEnd.settext("Computer Win!")
compScore = compScore + 1
labelCompScoreSum.settext(string(compScore))
ok
if (myChose = 2) and (compChose = 1)
labelScoreEnd.settext("I Win!")
myScore = myScore + 1
labelMyScoreSum.settext(string(myScore))
ok
if (myChose = 3) and (compChose = 1)
labelScoreEnd.settext("Computer Win!")
compScore = compScore + 1
labelCompScoreSum.settext(string(compScore))
ok
if (myChose = 3) and (compChose = 2)
labelScoreEnd.settext("I Win!")
myScore = myScore + 1
labelMyScoreSum.settext(string(myScore))
ok
func NewGame
nextPlayer = 1
myScore = 0
compScore = 0
btnMyChose {
seticon(new qicon(new qpixmap("")))
setIconSize(new qSize(200,200))
}
btnCompChose {
seticon(new qicon(new qpixmap("")))
setIconSize(new qSize(200,200))
}
labelScoreEnd.settext("")
labelMyScoreSum.settext("0")
labelCompScoreSum.settext("0")
func Close
win.close()
app.quit()
|
http://rosettacode.org/wiki/Rhonda_numbers
|
Rhonda numbers
|
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.
25662 is a Rhonda number to base-10. The prime factorization is 2 × 3 × 7 × 13 × 47; the product of its base-10 digits is equal to the base times the sum of its prime factors:
2 × 5 × 6 × 6 × 2 = 720 = 10 × (2 + 3 + 7 + 13 + 47)
Rhonda numbers only exist in bases that are not a prime.
Rhonda numbers to base 10 always contain at least 1 digit 5 and always contain at least 1 even digit.
Task
For the non-prime bases b from 2 through 16 , find and display here, on this page, at least the first 10 Rhonda numbers to base b. Display the found numbers at least in base 10.
Stretch
Extend out to base 36.
See also
Wolfram Mathworld - Rhonda numbers
Numbers Aplenty - Rhonda numbers
OEIS:A100968 - Integers n that are Rhonda numbers to base 4
OEIS:A100969 - Integers n that are Rhonda numbers to base 6
OEIS:A100970 - Integers n that are Rhonda numbers to base 8
OEIS:A100973 - Integers n that are Rhonda numbers to base 9
OEIS:A099542 - Rhonda numbers to base 10
OEIS:A100971 - Integers n that are Rhonda numbers to base 12
OEIS:A100972 - Integers n that are Rhonda numbers to base 14
OEIS:A100974 - Integers n that are Rhonda numbers to base 15
OEIS:A100975 - Integers n that are Rhonda numbers to base 16
OEIS:A255735 - Integers n that are Rhonda numbers to base 18
OEIS:A255732 - Rhonda numbers in vigesimal number system (base 20)
OEIS:A255736 - Integers that are Rhonda numbers to base 30
Related Task: Smith numbers
|
#Factor
|
Factor
|
USING: formatting grouping io kernel lists lists.lazy math
math.parser math.primes math.primes.factors prettyprint ranges
sequences sequences.extras ;
: rhonda? ( n base -- ? )
[ [ >base 1 group ] keep '[ _ base> ] map-product ]
[ swap factors sum * ] 2bi = ;
: rhonda ( base -- list ) 1 lfrom swap '[ _ rhonda? ] lfilter ;
: list. ( list base -- ) '[ _ >base write bl ] leach nl ;
:: rhonda. ( base -- )
15 base rhonda ltake :> r
base "First 15 Rhonda numbers to base %d:\n" printf
"In base 10: " write r 10 list.
base "In base %d: " printf r base list. ;
2 36 [a..b] [ prime? not ] filter [ rhonda. nl ] each
|
http://rosettacode.org/wiki/Rhonda_numbers
|
Rhonda numbers
|
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.
25662 is a Rhonda number to base-10. The prime factorization is 2 × 3 × 7 × 13 × 47; the product of its base-10 digits is equal to the base times the sum of its prime factors:
2 × 5 × 6 × 6 × 2 = 720 = 10 × (2 + 3 + 7 + 13 + 47)
Rhonda numbers only exist in bases that are not a prime.
Rhonda numbers to base 10 always contain at least 1 digit 5 and always contain at least 1 even digit.
Task
For the non-prime bases b from 2 through 16 , find and display here, on this page, at least the first 10 Rhonda numbers to base b. Display the found numbers at least in base 10.
Stretch
Extend out to base 36.
See also
Wolfram Mathworld - Rhonda numbers
Numbers Aplenty - Rhonda numbers
OEIS:A100968 - Integers n that are Rhonda numbers to base 4
OEIS:A100969 - Integers n that are Rhonda numbers to base 6
OEIS:A100970 - Integers n that are Rhonda numbers to base 8
OEIS:A100973 - Integers n that are Rhonda numbers to base 9
OEIS:A099542 - Rhonda numbers to base 10
OEIS:A100971 - Integers n that are Rhonda numbers to base 12
OEIS:A100972 - Integers n that are Rhonda numbers to base 14
OEIS:A100974 - Integers n that are Rhonda numbers to base 15
OEIS:A100975 - Integers n that are Rhonda numbers to base 16
OEIS:A255735 - Integers n that are Rhonda numbers to base 18
OEIS:A255732 - Rhonda numbers in vigesimal number system (base 20)
OEIS:A255736 - Integers that are Rhonda numbers to base 30
Related Task: Smith numbers
|
#Go
|
Go
|
package main
import (
"fmt"
"rcu"
"strconv"
)
func contains(a []int, n int) bool {
for _, e := range a {
if e == n {
return true
}
}
return false
}
func main() {
for b := 2; b <= 36; b++ {
if rcu.IsPrime(b) {
continue
}
count := 0
var rhonda []int
for n := 1; count < 15; n++ {
digits := rcu.Digits(n, b)
if !contains(digits, 0) {
var anyEven = false
for _, d := range digits {
if d%2 == 0 {
anyEven = true
break
}
}
if b != 10 || (contains(digits, 5) && anyEven) {
calc1 := 1
for _, d := range digits {
calc1 *= d
}
calc2 := b * rcu.SumInts(rcu.PrimeFactors(n))
if calc1 == calc2 {
rhonda = append(rhonda, n)
count++
}
}
}
}
if len(rhonda) > 0 {
fmt.Printf("\nFirst 15 Rhonda numbers in base %d:\n", b)
rhonda2 := make([]string, len(rhonda))
counts2 := make([]int, len(rhonda))
for i, r := range rhonda {
rhonda2[i] = fmt.Sprintf("%d", r)
counts2[i] = len(rhonda2[i])
}
rhonda3 := make([]string, len(rhonda))
counts3 := make([]int, len(rhonda))
for i, r := range rhonda {
rhonda3[i] = strconv.FormatInt(int64(r), b)
counts3[i] = len(rhonda3[i])
}
maxLen2 := rcu.MaxInts(counts2)
maxLen3 := rcu.MaxInts(counts3)
maxLen := maxLen2
if maxLen3 > maxLen {
maxLen = maxLen3
}
maxLen++
fmt.Printf("In base 10: %*s\n", maxLen, rhonda2)
fmt.Printf("In base %-2d: %*s\n", b, maxLen, rhonda3)
}
}
}
|
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.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#PowerShell
|
PowerShell
|
function Compress-RLE ($s) {
$re = [regex] '(.)\1*'
$ret = ""
foreach ($m in $re.Matches($s)) {
$ret += $m.Length
$ret += $m.Value[0]
}
return $ret
}
function Expand-RLE ($s) {
$re = [regex] '(\d+)(.)'
$ret = ""
foreach ($m in $re.Matches($s)) {
$ret += [string] $m.Groups[2] * [int] [string] $m.Groups[1]
}
return $ret
}
|
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 input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
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
|
#LiveCode
|
LiveCode
|
function rot13 S
repeat with i = 1 to length(S)
get chartonum(char i of S)
if it < 65 or it > 122 or (it > 90 and it < 97) then next repeat
put char it - 64 of "NOPQRSTUVWXYZABCDEFGHIJKLM nopqrstuvwxyzabcdefghijklm" into char i of S
end repeat
return S
end rot13
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#Wart
|
Wart
|
def (pos x (seq | (head ... tail)) n)
default n :to 0
if seq
if (head = x)
n
(pos x tail n+1)
|
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 numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#HicEst
|
HicEst
|
CHARACTER Roman*20
CALL RomanNumeral(1990, Roman) ! MCMXC
CALL RomanNumeral(2008, Roman) ! MMVIII
CALL RomanNumeral(1666, Roman) ! MDCLXVI
END
SUBROUTINE RomanNumeral( arabic, roman)
CHARACTER roman
DIMENSION ddec(13)
DATA ddec/1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1/
roman = ' '
todo = arabic
DO d = 1, 13
DO rep = 1, todo / ddec(d)
roman = TRIM(roman) // TRIM(CHAR(d, 13, "M CM D CD C XC L XL X OX V IV I "))
todo = todo - ddec(d)
ENDDO
ENDDO
END
|
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 decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#K
|
K
|
romd: {v:1 5 10 50 100 500 1000@"IVXLCDM"?/:x; +/v*_-1^(>':v),0}
|
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:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#Ruby
|
Ruby
|
class RockPaperScissorsGame
CHOICES = %w[rock paper scissors quit]
BEATS = {
'rock' => 'paper',
'paper' => 'scissors',
'scissors' => 'rock',
}
def initialize()
@plays = {
'rock' => 1,
'paper' => 1,
'scissors' => 1,
}
@score = [0, 0, 0] # [0]:Human wins, [1]:Computer wins, [2]:draw
play
end
def humanPlay
loop do
print "\nYour choice: #{CHOICES}? "
answer = STDIN.gets.strip.downcase
next if answer.empty?
idx = CHOICES.find_index {|choice| choice.match(/^#{answer}/)}
return CHOICES[idx] if idx
puts "invalid answer, try again"
end
end
def computerPlay
total = @plays.values.reduce(:+)
r = rand(total) + 1
sum = 0
CHOICES.each do |choice|
sum += @plays[choice]
return BEATS[choice] if r <= sum
end
end
def play
loop do
h = humanPlay
break if h == "quit"
c = computerPlay
print "H: #{h}, C: #{c} => "
# only update the human player's history after the computer has chosen
@plays[h] += 1
if h == c
puts "draw"
@score[2] += 1
elsif h == BEATS[c]
puts "Human wins"
@score[0] += 1
else
puts "Computer wins"
@score[1] += 1
end
puts "score: human=%d, computer=%d, draw=%d" % [*@score]
end
@plays.each_key{|k| @plays[k] -= 1}
puts "\nhumans chose #{@plays}"
end
end
RockPaperScissorsGame.new
|
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 recently. You can find this out by searching the chat logs. The logs are publicly available at http://tclers.tk/conferences/tcl/. One log file corresponds to the messages from one day in Germany's current time zone. Each chat log file has the name YYYY-MM-DD.tcl where YYYY is the year, MM is the month and DD the day. The logs store one message per line. The messages themselves are human-readable and their internal structure doesn't matter.
Retrieve the chat logs from the last 10 days via HTTP. Find the lines that include a particular substring and print them in the following format:
<log file URL>
------
<matching line 1>
<matching line 2>
...
<matching line N>
------
The substring will be given to your program as a command line argument.
You need to account for the possible time zone difference between the client running your program and the chat log writer on the server to not miss any mentions. (For example, if you generated the log file URLs naively based on the local date, you could miss mentions if it was already April 5th for the logger but only April 4th for the client.) What this means in practice is that you should either generate the URLs in the time zone Europe/Berlin or, if your language can not do that, add an extra day (today + 1) to the range of dates you check, but then make sure to not print parts of a "not found" page by accident if a log file doesn't exist yet.
The code should be contained in a single-file script, with no "project" or "dependency" file (e.g., no requirements.txt for Python). It should only use a given programming language's standard library to accomplish this task and not rely on the user having installed any third-party packages.
If your language does not have an HTTP client in the standard library, you can speak raw HTTP 1.0 to the server. If it can't parse command line arguments in a standalone script, read the string to look for from the standard input.
|
#C
|
C
|
#include<curl/curl.h>
#include<string.h>
#include<stdio.h>
#define MAX_LEN 1000
void searchChatLogs(char* searchString){
char* baseURL = "http://tclers.tk/conferences/tcl/";
time_t t;
struct tm* currentDate;
char dateString[30],dateStringFile[30],lineData[MAX_LEN],targetURL[100];
int i,flag;
FILE *fp;
CURL *curl;
CURLcode res;
time(&t);
currentDate = localtime(&t);
strftime(dateString, 30, "%Y-%m-%d", currentDate);
printf("Today is : %s",dateString);
if((curl = curl_easy_init())!=NULL){
for(i=0;i<=10;i++){
flag = 0;
sprintf(targetURL,"%s%s.tcl",baseURL,dateString);
strcpy(dateStringFile,dateString);
printf("\nRetrieving chat logs from %s\n",targetURL);
if((fp = fopen("nul","w"))==0){
printf("Cant's read from %s",targetURL);
}
else{
curl_easy_setopt(curl, CURLOPT_URL, targetURL);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
if(res == CURLE_OK){
while(fgets(lineData,MAX_LEN,fp)!=NULL){
if(strstr(lineData,searchString)!=NULL){
flag = 1;
fputs(lineData,stdout);
}
}
if(flag==0)
printf("\nNo matching lines found.");
}
fflush(fp);
fclose(fp);
}
currentDate->tm_mday--;
mktime(currentDate);
strftime(dateString, 30, "%Y-%m-%d", currentDate);
}
curl_easy_cleanup(curl);
}
}
int main(int argC,char* argV[])
{
if(argC!=2)
printf("Usage : %s <followed by search string, enclosed by \" if it contains spaces>",argV[0]);
else
searchChatLogs(argV[1]);
return 0;
}
|
http://rosettacode.org/wiki/Rhonda_numbers
|
Rhonda numbers
|
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.
25662 is a Rhonda number to base-10. The prime factorization is 2 × 3 × 7 × 13 × 47; the product of its base-10 digits is equal to the base times the sum of its prime factors:
2 × 5 × 6 × 6 × 2 = 720 = 10 × (2 + 3 + 7 + 13 + 47)
Rhonda numbers only exist in bases that are not a prime.
Rhonda numbers to base 10 always contain at least 1 digit 5 and always contain at least 1 even digit.
Task
For the non-prime bases b from 2 through 16 , find and display here, on this page, at least the first 10 Rhonda numbers to base b. Display the found numbers at least in base 10.
Stretch
Extend out to base 36.
See also
Wolfram Mathworld - Rhonda numbers
Numbers Aplenty - Rhonda numbers
OEIS:A100968 - Integers n that are Rhonda numbers to base 4
OEIS:A100969 - Integers n that are Rhonda numbers to base 6
OEIS:A100970 - Integers n that are Rhonda numbers to base 8
OEIS:A100973 - Integers n that are Rhonda numbers to base 9
OEIS:A099542 - Rhonda numbers to base 10
OEIS:A100971 - Integers n that are Rhonda numbers to base 12
OEIS:A100972 - Integers n that are Rhonda numbers to base 14
OEIS:A100974 - Integers n that are Rhonda numbers to base 15
OEIS:A100975 - Integers n that are Rhonda numbers to base 16
OEIS:A255735 - Integers n that are Rhonda numbers to base 18
OEIS:A255732 - Rhonda numbers in vigesimal number system (base 20)
OEIS:A255736 - Integers that are Rhonda numbers to base 30
Related Task: Smith numbers
|
#J
|
J
|
tobase=: (a.{~;48 97(+ i.)each 10 26) {~ #.inv
isrhonda=: (*/@:(#.inv) = (* +/@q:))"0
task=: {{
for_base.(#~ 0=1&p:) }.1+i.36 do.
k=.i.0
block=. 1+i.1e4
while. 15>#k do.
k=. k, block#~ base isrhonda block
block=. block+1e4
end.
echo ''
echo 'First 15 Rhondas in',b=.' base ',':',~":base
echo 'In base 10: ',":15{.k
echo 'In',;:inv b;base tobase each 15{.k
end.
}}
task''
|
http://rosettacode.org/wiki/Rhonda_numbers
|
Rhonda numbers
|
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.
25662 is a Rhonda number to base-10. The prime factorization is 2 × 3 × 7 × 13 × 47; the product of its base-10 digits is equal to the base times the sum of its prime factors:
2 × 5 × 6 × 6 × 2 = 720 = 10 × (2 + 3 + 7 + 13 + 47)
Rhonda numbers only exist in bases that are not a prime.
Rhonda numbers to base 10 always contain at least 1 digit 5 and always contain at least 1 even digit.
Task
For the non-prime bases b from 2 through 16 , find and display here, on this page, at least the first 10 Rhonda numbers to base b. Display the found numbers at least in base 10.
Stretch
Extend out to base 36.
See also
Wolfram Mathworld - Rhonda numbers
Numbers Aplenty - Rhonda numbers
OEIS:A100968 - Integers n that are Rhonda numbers to base 4
OEIS:A100969 - Integers n that are Rhonda numbers to base 6
OEIS:A100970 - Integers n that are Rhonda numbers to base 8
OEIS:A100973 - Integers n that are Rhonda numbers to base 9
OEIS:A099542 - Rhonda numbers to base 10
OEIS:A100971 - Integers n that are Rhonda numbers to base 12
OEIS:A100972 - Integers n that are Rhonda numbers to base 14
OEIS:A100974 - Integers n that are Rhonda numbers to base 15
OEIS:A100975 - Integers n that are Rhonda numbers to base 16
OEIS:A255735 - Integers n that are Rhonda numbers to base 18
OEIS:A255732 - Rhonda numbers in vigesimal number system (base 20)
OEIS:A255736 - Integers that are Rhonda numbers to base 30
Related Task: Smith numbers
|
#Java
|
Java
|
public class RhondaNumbers {
public static void main(String[] args) {
final int limit = 15;
for (int base = 2; base <= 36; ++base) {
if (isPrime(base))
continue;
System.out.printf("First %d Rhonda numbers to base %d:\n", limit, base);
int numbers[] = new int[limit];
for (int n = 1, count = 0; count < limit; ++n) {
if (isRhonda(base, n))
numbers[count++] = n;
}
System.out.printf("In base 10:");
for (int i = 0; i < limit; ++i)
System.out.printf(" %d", numbers[i]);
System.out.printf("\nIn base %d:", base);
for (int i = 0; i < limit; ++i)
System.out.printf(" %s", Integer.toString(numbers[i], base));
System.out.printf("\n\n");
}
}
private static int digitProduct(int base, int n) {
int product = 1;
for (; n != 0; n /= base)
product *= n % base;
return product;
}
private static int primeFactorSum(int n) {
int sum = 0;
for (; (n & 1) == 0; n >>= 1)
sum += 2;
for (int p = 3; p * p <= n; p += 2)
for (; n % p == 0; n /= p)
sum += p;
if (n > 1)
sum += n;
return sum;
}
private static boolean isPrime(int n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
for (int p = 5; p * p <= n; p += 4) {
if (n % p == 0)
return false;
p += 2;
if (n % p == 0)
return false;
}
return true;
}
private static boolean isRhonda(int base, int n) {
return digitProduct(base, n) == base * primeFactorSum(n);
}
}
|
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.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#Prolog
|
Prolog
|
% the test
run_length :-
L = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW",
writef('encode %s\n', [L]),
encode(L, R),
writeln(R), nl,
writef('decode %w\n', [R]),
decode(R, L1),
writeln(L1).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% encode
%
% translation
% from
% "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
% to
% "12W1B12W3B24W1B14W"
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
encode(In, Out) :-
% Because of the special management of the "strings" by Prolog
( is_list(In) -> I = In; string_to_list(In, I)),
packList(I, R1),
dcg_packList2List(R1,R2, []),
string_to_list(Out,R2).
dcg_packList2List([[N, V]|T]) -->
{ number_codes(N, LN)},
LN,
[V],
dcg_packList2List(T).
dcg_packList2List([]) --> [].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% decode
%
% translation
% from
% "12W1B12W3B24W1B14W"
% to
% "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
decode(In, Out) :-
% Because of the special management of the "strings" by Prolog
( is_list(In) -> I = In; string_to_list(In, I)),
dcg_List2packList(I, R1, []),
packList(L1, R1),
string_to_list(Out, L1).
dcg_List2packList([H|T]) -->
{code_type(H, digit)},
parse_number([H|T], 0).
dcg_List2packList([]) --> [].
parse_number([H|T], N) -->
{code_type(H, digit), !,
N1 is N*10 + H - 48 },
parse_number(T, N1).
parse_number([H|T], N) -->
[[N, H]],
dcg_List2packList(T).
% use of library clpfd allows packList(?In, ?Out) to works
% in both ways In --> Out and In <-- Out.
:- use_module(library(clpfd)).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ?- packList([a,a,a,b,c,c,c,d,d,e], L).
% L = [[3,a],[1,b],[3,c],[2,d],[1,e]] .
% ?- packList(R, [[3,a],[1,b],[3,c],[2,d],[1,e]]).
% R = [a,a,a,b,c,c,c,d,d,e] .
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
packList([],[]).
packList([X],[[1,X]]) :- !.
packList([X|Rest],[XRun|Packed]):-
run(X,Rest, XRun,RRest),
packList(RRest,Packed).
run(Var,[],[1,Var],[]).
run(Var,[Var|LRest],[N1, Var],RRest):-
N #> 0,
N1 #= N + 1,
run(Var,LRest,[N, Var],RRest).
run(Var,[Other|RRest], [1,Var],[Other|RRest]):-
dif(Var,Other).
|
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 input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
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
|
#Locomotive_Basic
|
Locomotive Basic
|
10 INPUT "Enter a string: ",a$
20 GOSUB 50
30 PRINT b$
40 END
50 FOR i=1 TO LEN(a$)
60 n=ASC(MID$(a$,i,1))
70 e=255
80 IF n>64 AND n<91 THEN e=90 ' uppercase
90 IF n>96 AND n<123 THEN e=122 ' lowercase
100 IF e<255 THEN n=n+13
110 IF n>e THEN n=n-26
120 b$=b$+CHR$(n)
130 NEXT
140 RETURN
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#Wren
|
Wren
|
import "/seq" for Lst
var find = Fn.new { |haystack, needle|
var res = Lst.indicesOf(haystack, needle)
if (!res[0]) Fiber.abort("Needle not found in haystack.")
System.print("The needle occurs %(res[1]) time(s) in the haystack.")
if (res[1] == 1) {
System.print("It occurs at index %(res[2][0])")
} else {
System.print("It first occurs at index %(res[2][0])")
System.print("It last occurs at index %(res[2][-1])")
}
System.print()
}
var haystack = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag"]
System.print("The haystack is:\n%(haystack)\n")
var needles = ["Wally", "Bush", "Zag", "George"]
for (needle in needles) {
System.print("The needle is %(needle).")
find.call(haystack, needle)
}
|
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 numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#Icon_and_Unicon
|
Icon and Unicon
|
link numbers # commas, roman
procedure main(arglist)
every x := !arglist do
write(commas(x), " -> ",roman(x)|"*** can't convert to Roman numerals ***")
end
|
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 decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#Kotlin
|
Kotlin
|
// version 1.0.6
fun romanDecode(roman: String): Int {
if (roman.isEmpty()) return 0
var n = 0
var last = 'O'
for (c in roman) {
when (c) {
'I' -> n += 1
'V' -> if (last == 'I') n += 3 else n += 5
'X' -> if (last == 'I') n += 8 else n += 10
'L' -> if (last == 'X') n += 30 else n += 50
'C' -> if (last == 'X') n += 80 else n += 100
'D' -> if (last == 'C') n += 300 else n += 500
'M' -> if (last == 'C') n += 800 else n += 1000
}
last = c
}
return n
}
fun main(args: Array<String>) {
val romans = arrayOf("I", "III", "IV", "VIII", "XLIX", "CCII", "CDXXXIII", "MCMXC", "MMVIII", "MDCLXVI")
for (roman in romans) println("${roman.padEnd(10)} = ${romanDecode(roman)}")
}
|
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:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#Run_BASIC
|
Run BASIC
|
pri$ = "RSPR"
rps$ = "Rock,Paper,Sissors"
[loop]
button #r, "Rock", [r]
button #p, "Paper", [p]
button #s, "Scissors",[s]
button #q, "Quit", [q]
wait
[r] y = 1 :goto [me]
[p] y = 2 :goto [me]
[s] y = 3
[me]
cls
y$ = word$(rps$,y,",")
m = int((rnd(0) * 2) + 1)
m$ = word$(rps$,m,",")
print chr$(10);"You Chose:";y$;" I chose:";m$
yp = instr(pri$,left$(y$,1))
mp = instr(pri$,left$(m$,1))
if yp = 1 and mp = 3 then mp = 0
if mp = 1 and yp = 3 then yp = 0
if yp < mp then print "You win"
if yp = mp then print "Tie"
if yp > mp then print "I win"
goto [loop]
wait
[q] cls
print "Good Bye! I enjoyed the game"
end
|
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:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#Rust
|
Rust
|
extern crate rand;
#[macro_use]
extern crate rand_derive;
use std::io;
use rand::Rng;
use Choice::*;
#[derive(PartialEq, Clone, Copy, Rand, Debug)]
enum Choice {
Rock,
Paper,
Scissors,
}
fn beats(c1: Choice, c2: Choice) -> bool {
(c1 == Rock && c2 == Scissors) || (c1 == Scissors && c2 == Paper) || (c1 == Paper && c2 == Rock)
}
fn ai_move<R: Rng>(rng: &mut R, v: [usize; 3]) -> Choice {
// weighted random choice, a dynamic version of `rand::distributions::WeightedChoice`
let rand = rng.gen_range(0, v[0] + v[1] + v[2]);
if rand < v[0] {
Paper
} else if rand < v[0] + v[1] {
Scissors
} else {
Rock
}
}
fn main() {
let mut rng = rand::thread_rng();
println!("Rock, paper, scissors!");
let mut ai_choice: Choice = rng.gen();
let mut ucf = [0, 0, 0]; // user choice frequency
let mut score = [0, 0];
loop {
println!("Please input your move: 'r', 'p' or 's'. Type 'q' to quit");
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("failed to read line");
let u_choice = match input.to_lowercase().trim() {
s if s.starts_with('r') => {
ucf[0] += 1;
Rock
}
s if s.starts_with('p') => {
ucf[1] += 1;
Paper
}
s if s.starts_with('s') => {
ucf[2] += 1;
Scissors
}
s if s.starts_with('q') => break,
_ => {
println!("Please enter a correct choice!");
continue;
}
};
println!("You chose {:?}, I chose {:?}.", u_choice, ai_choice);
if beats(u_choice, ai_choice) {
score[0] += 1;
println!("You win!");
} else if u_choice == ai_choice {
println!("It's a tie!");
} else {
score[1] += 1;
println!("I win!");
}
println!("-Score: You {}, Me {}", score[0], score[1]);
// only after the 1st iteration the AI knows the stats and can make
// its weighted random move
ai_choice = ai_move(&mut rng, ucf);
}
println!("Thank you for the game!");
}
|
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 recently. You can find this out by searching the chat logs. The logs are publicly available at http://tclers.tk/conferences/tcl/. One log file corresponds to the messages from one day in Germany's current time zone. Each chat log file has the name YYYY-MM-DD.tcl where YYYY is the year, MM is the month and DD the day. The logs store one message per line. The messages themselves are human-readable and their internal structure doesn't matter.
Retrieve the chat logs from the last 10 days via HTTP. Find the lines that include a particular substring and print them in the following format:
<log file URL>
------
<matching line 1>
<matching line 2>
...
<matching line N>
------
The substring will be given to your program as a command line argument.
You need to account for the possible time zone difference between the client running your program and the chat log writer on the server to not miss any mentions. (For example, if you generated the log file URLs naively based on the local date, you could miss mentions if it was already April 5th for the logger but only April 4th for the client.) What this means in practice is that you should either generate the URLs in the time zone Europe/Berlin or, if your language can not do that, add an extra day (today + 1) to the range of dates you check, but then make sure to not print parts of a "not found" page by accident if a log file doesn't exist yet.
The code should be contained in a single-file script, with no "project" or "dependency" file (e.g., no requirements.txt for Python). It should only use a given programming language's standard library to accomplish this task and not rely on the user having installed any third-party packages.
If your language does not have an HTTP client in the standard library, you can speak raw HTTP 1.0 to the server. If it can't parse command line arguments in a standalone script, read the string to look for from the standard input.
|
#Elixir
|
Elixir
|
#! /usr/bin/env elixir
defmodule Mentions do
def get(url) do
{:ok, {{_, 200, _}, _, body}} =
url
|> String.to_charlist()
|> :httpc.request()
data = List.to_string(body)
if Regex.match?(~r|<!Doctype HTML.*<Title>URL Not Found</Title>|s, data) do
{:error, "log file not found"}
else
{:ok, data}
end
end
def perg(haystack, needle) do
haystack
|> String.split("\n")
|> Enum.filter(fn x -> String.contains?(x, needle) end)
end
def generate_url(n) do
date_str =
DateTime.utc_now()
|> DateTime.to_unix()
|> (fn x -> x + 60*60*24*n end).()
|> DateTime.from_unix!()
|> (fn %{year: y, month: m, day: d} ->
:io_lib.format("~B-~2..0B-~2..0B", [y, m, d])
end).()
"http://tclers.tk/conferences/tcl/#{date_str}.tcl"
end
end
[needle] = System.argv()
:application.start(:inets)
back = 10
# Elixir does not come standard with time zone definitions, so we add an extra
# day to account for the possible difference between the local and the server
# time.
for i <- -back..1 do
url = Mentions.generate_url(i)
with {:ok, haystack} <- Mentions.get(url),
# If the result is a non-empty list...
[h | t] <- Mentions.perg(haystack, needle) do
IO.puts("#{url}\n------\n#{Enum.join([h | t], "\n")}\n------\n")
end
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 recently. You can find this out by searching the chat logs. The logs are publicly available at http://tclers.tk/conferences/tcl/. One log file corresponds to the messages from one day in Germany's current time zone. Each chat log file has the name YYYY-MM-DD.tcl where YYYY is the year, MM is the month and DD the day. The logs store one message per line. The messages themselves are human-readable and their internal structure doesn't matter.
Retrieve the chat logs from the last 10 days via HTTP. Find the lines that include a particular substring and print them in the following format:
<log file URL>
------
<matching line 1>
<matching line 2>
...
<matching line N>
------
The substring will be given to your program as a command line argument.
You need to account for the possible time zone difference between the client running your program and the chat log writer on the server to not miss any mentions. (For example, if you generated the log file URLs naively based on the local date, you could miss mentions if it was already April 5th for the logger but only April 4th for the client.) What this means in practice is that you should either generate the URLs in the time zone Europe/Berlin or, if your language can not do that, add an extra day (today + 1) to the range of dates you check, but then make sure to not print parts of a "not found" page by accident if a log file doesn't exist yet.
The code should be contained in a single-file script, with no "project" or "dependency" file (e.g., no requirements.txt for Python). It should only use a given programming language's standard library to accomplish this task and not rely on the user having installed any third-party packages.
If your language does not have an HTTP client in the standard library, you can speak raw HTTP 1.0 to the server. If it can't parse command line arguments in a standalone script, read the string to look for from the standard input.
|
#F.23
|
F#
|
#!/usr/bin/env fsharpi
let server_tz =
try
// CLR on Windows
System.TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time")
with
// Mono
:? System.TimeZoneNotFoundException ->
System.TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin")
let get url =
let req = System.Net.WebRequest.Create(System.Uri(url))
use resp = req.GetResponse()
use stream = resp.GetResponseStream()
use reader = new System.IO.StreamReader(stream)
reader.ReadToEnd()
let grep needle (haystack : string) =
haystack.Split('\n')
|> Array.toList
|> List.filter (fun x -> x.Contains(needle))
let genUrl n =
let day = System.DateTime.UtcNow.AddDays(float n)
let server_dt = System.TimeZoneInfo.ConvertTimeFromUtc(day, server_tz)
let timestamp = server_dt.ToString("yyyy-MM-dd")
sprintf "http://tclers.tk/conferences/tcl/%s.tcl" timestamp
let _ =
match fsi.CommandLineArgs with
| [|_; needle|] ->
let back = 10
for i in -back .. 0 do
let url = genUrl i
let found = url |> get |> grep needle |> String.concat "\n"
if found <> "" then printfn "%s\n------\n%s\n------\n" url found
else ()
| x ->
printfn "Usage: %s literal" (Array.get x 0)
System.Environment.Exit(1)
|
http://rosettacode.org/wiki/Rhonda_numbers
|
Rhonda numbers
|
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.
25662 is a Rhonda number to base-10. The prime factorization is 2 × 3 × 7 × 13 × 47; the product of its base-10 digits is equal to the base times the sum of its prime factors:
2 × 5 × 6 × 6 × 2 = 720 = 10 × (2 + 3 + 7 + 13 + 47)
Rhonda numbers only exist in bases that are not a prime.
Rhonda numbers to base 10 always contain at least 1 digit 5 and always contain at least 1 even digit.
Task
For the non-prime bases b from 2 through 16 , find and display here, on this page, at least the first 10 Rhonda numbers to base b. Display the found numbers at least in base 10.
Stretch
Extend out to base 36.
See also
Wolfram Mathworld - Rhonda numbers
Numbers Aplenty - Rhonda numbers
OEIS:A100968 - Integers n that are Rhonda numbers to base 4
OEIS:A100969 - Integers n that are Rhonda numbers to base 6
OEIS:A100970 - Integers n that are Rhonda numbers to base 8
OEIS:A100973 - Integers n that are Rhonda numbers to base 9
OEIS:A099542 - Rhonda numbers to base 10
OEIS:A100971 - Integers n that are Rhonda numbers to base 12
OEIS:A100972 - Integers n that are Rhonda numbers to base 14
OEIS:A100974 - Integers n that are Rhonda numbers to base 15
OEIS:A100975 - Integers n that are Rhonda numbers to base 16
OEIS:A255735 - Integers n that are Rhonda numbers to base 18
OEIS:A255732 - Rhonda numbers in vigesimal number system (base 20)
OEIS:A255736 - Integers that are Rhonda numbers to base 30
Related Task: Smith numbers
|
#Julia
|
Julia
|
using Primes
isRhonda(n, b) = prod(digits(n, base=b)) == b * sum([prod(pair) for pair in factor(n).pe])
function displayrhondas(low, high, nshow)
for b in filter(!isprime, low:high)
n, rhondas = 1, Int[]
while length(rhondas) < nshow
isRhonda(n, b) && push!(rhondas, n)
n += 1
end
println("First $nshow Rhondas in base $b:")
println("In base 10: ", rhondas)
println("In base $b: ", replace(string([string(i, base=b) for i in rhondas]), "\"" => ""), "\n")
end
end
displayrhondas(2, 16, 15)
|
http://rosettacode.org/wiki/Rhonda_numbers
|
Rhonda numbers
|
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.
25662 is a Rhonda number to base-10. The prime factorization is 2 × 3 × 7 × 13 × 47; the product of its base-10 digits is equal to the base times the sum of its prime factors:
2 × 5 × 6 × 6 × 2 = 720 = 10 × (2 + 3 + 7 + 13 + 47)
Rhonda numbers only exist in bases that are not a prime.
Rhonda numbers to base 10 always contain at least 1 digit 5 and always contain at least 1 even digit.
Task
For the non-prime bases b from 2 through 16 , find and display here, on this page, at least the first 10 Rhonda numbers to base b. Display the found numbers at least in base 10.
Stretch
Extend out to base 36.
See also
Wolfram Mathworld - Rhonda numbers
Numbers Aplenty - Rhonda numbers
OEIS:A100968 - Integers n that are Rhonda numbers to base 4
OEIS:A100969 - Integers n that are Rhonda numbers to base 6
OEIS:A100970 - Integers n that are Rhonda numbers to base 8
OEIS:A100973 - Integers n that are Rhonda numbers to base 9
OEIS:A099542 - Rhonda numbers to base 10
OEIS:A100971 - Integers n that are Rhonda numbers to base 12
OEIS:A100972 - Integers n that are Rhonda numbers to base 14
OEIS:A100974 - Integers n that are Rhonda numbers to base 15
OEIS:A100975 - Integers n that are Rhonda numbers to base 16
OEIS:A255735 - Integers n that are Rhonda numbers to base 18
OEIS:A255732 - Rhonda numbers in vigesimal number system (base 20)
OEIS:A255736 - Integers that are Rhonda numbers to base 30
Related Task: Smith numbers
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
ClearAll[RhondaNumberQ]
RhondaNumberQ[b_Integer][n_Integer] := Module[{l, r},
l = Times @@ IntegerDigits[n, b];
r = Total[Catenate[ConstantArray @@@ FactorInteger[n]]];
l == b r
]
bases = Select[Range[2, 36], PrimeQ/*Not];
Do[
Print["base ", b, ":", Take[Select[Range[700000], RhondaNumberQ[b]], UpTo[15]]];
,
{b, bases}
]
|
http://rosettacode.org/wiki/Rhonda_numbers
|
Rhonda numbers
|
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.
25662 is a Rhonda number to base-10. The prime factorization is 2 × 3 × 7 × 13 × 47; the product of its base-10 digits is equal to the base times the sum of its prime factors:
2 × 5 × 6 × 6 × 2 = 720 = 10 × (2 + 3 + 7 + 13 + 47)
Rhonda numbers only exist in bases that are not a prime.
Rhonda numbers to base 10 always contain at least 1 digit 5 and always contain at least 1 even digit.
Task
For the non-prime bases b from 2 through 16 , find and display here, on this page, at least the first 10 Rhonda numbers to base b. Display the found numbers at least in base 10.
Stretch
Extend out to base 36.
See also
Wolfram Mathworld - Rhonda numbers
Numbers Aplenty - Rhonda numbers
OEIS:A100968 - Integers n that are Rhonda numbers to base 4
OEIS:A100969 - Integers n that are Rhonda numbers to base 6
OEIS:A100970 - Integers n that are Rhonda numbers to base 8
OEIS:A100973 - Integers n that are Rhonda numbers to base 9
OEIS:A099542 - Rhonda numbers to base 10
OEIS:A100971 - Integers n that are Rhonda numbers to base 12
OEIS:A100972 - Integers n that are Rhonda numbers to base 14
OEIS:A100974 - Integers n that are Rhonda numbers to base 15
OEIS:A100975 - Integers n that are Rhonda numbers to base 16
OEIS:A255735 - Integers n that are Rhonda numbers to base 18
OEIS:A255732 - Rhonda numbers in vigesimal number system (base 20)
OEIS:A255736 - Integers that are Rhonda numbers to base 30
Related Task: Smith numbers
|
#Perl
|
Perl
|
use strict;
use warnings;
use feature 'say';
use ntheory qw<is_prime factor vecsum vecprod todigitstring todigits>;
sub rhonda {
my($b, $cnt) = @_;
my(@r,$n);
while (++$n) {
push @r, $n if ($b * vecsum factor($n)) == vecprod todigits($n,$b);
return @r if $cnt == @r;
}
}
for my $b (grep { ! is_prime $_ } 2..36) {
my @Rb = map { todigitstring($_,$b) } my @R = rhonda($b, 15);
say <<~EOT;
First 15 Rhonda numbers to base $b:
In base $b: @Rb
In base 10: @R
EOT
}
|
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.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#Pure
|
Pure
|
using system;
encode s = strcat $ map (sprintf "%d%s") $ encode $ chars s with
encode [] = [];
encode xs@(x:_) = (#takewhile (==x) xs,x) : encode (dropwhile (==x) xs);
end;
decode s = strcat [c | n,c = parse s; i = 1..n] with
parse s::string = regexg item "([0-9]+)(.)" REG_EXTENDED s 0;
item info = val (reg 1 info!1), reg 2 info!1;
end;
let s = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
let r = encode s; // "12W1B12W3B24W1B14W"
decode r;
|
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 input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
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 rot13 :c
make "a difference ascii lowercase :c ascii "a
if or :a < 0 :a > 25 [output :c]
make "delta ifelse :a < 13 [13] [-13]
output char sum :delta ascii :c
end
print map "rot13 "|abjurer NOWHERE|
nowhere ABJURER
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#XPL0
|
XPL0
|
\Based on C example:
include c:\cxpl\stdlib; \provides StrCmp routine, etc.
int Haystack; \('int' is used instead of 'char' for 2D array)
func Search(Str, First); \Return first (or last) index for string in haystack
char Str; int First;
int I, SI;
[I:= 0; SI:= 0;
repeat if StrCmp(Str, Haystack(I)) = 0 then
[if First then return I;
SI:= I; \save index
];
I:= I+1;
until Haystack(I) = 0;
return SI;
];
[Haystack:= ["Zig", "Zag", "Wally", "Ronald", "Bush",
"Krusty", "Charlie", "Bush", "Boz", "Zag", 0];
Text(0, "Bush is at "); IntOut(0, Search("Bush", true)); CrLf(0);
if Search("Washington", true) = 0 then
Text(0, "Washington is not in the haystack^M^J");
Text(0, "First index for Zag: "); IntOut(0, Search("Zag", true)); CrLf(0);
Text(0, "Last index for Zag: "); IntOut(0, Search("Zag", false)); CrLf(0);
]
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#Yabasic
|
Yabasic
|
list$ = "mouse,hat,cup,deodorant,television,soap,methamphetamine,severed cat heads,cup"
dim item$(1)
n = token(list$, item$(), ",")
line input "Enter string to search: " line$
for i = 1 to n
if line$ = item$(i) then
if not t print "First index for ", line$, ": ", i
t = i
j = j + 1
end if
next
if t = 0 then
print "String not found in list"
else
if j > 1 print "Last index for ", line$, ": ", t
end if
|
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 numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#Intercal
|
Intercal
|
PLEASE WRITE IN .1
DO READ OUT .1
DO GIVE UP
|
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 decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#Lasso
|
Lasso
|
define br => '\r'
//decode roman
define decodeRoman(roman::string)::integer => {
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 = integer)
while(#roman->size) => {
// need to use neset while instead of query expr to utilize loop_abort
while(loop_count <= #ref->size) => {
if(#roman->beginswith(#ref->get(loop_count)->first)) => {
#out += #ref->get(loop_count)->second
#roman->remove(1,#ref->get(loop_count)->first->size)
loop_abort
}
}
}
return #out
}
'MCMXC as integer is '+decodeRoman('MCMXC')
br
'MMVIII as integer is '+decodeRoman('MMVIII')
br
'MDCLXVI as integer is '+decodeRoman('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:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#Scala
|
Scala
|
object RockPaperScissors extends App {
import scala.collection.mutable.LinkedHashMap
def play(beats: LinkedHashMap[Symbol,Set[Symbol]], played: scala.collection.Map[Symbol,Int]) {
val h = readLine(s"""Your move (${beats.keys mkString ", "}): """) match {
case null => println; return
case "" => return
case s => Symbol(s)
}
beats get h match {
case Some(losers) =>
def weighted(todo: Iterator[(Symbol,Int)], rand: Int, accum: Int = 0): Symbol = todo.next match {
case (s, i) if rand <= (accum + i) => s
case (_, i) => weighted(todo, rand, accum + i)
}
val c = weighted(played.toIterator, 1 + scala.util.Random.nextInt(played.values.sum)) match {
// choose an opponent that would beat the player's anticipated move
case h => beats.find{case (s, l) => l contains h}.getOrElse(beats.head)._1
}
print(s" My move: $c\n ")
c match {
case c if losers contains c => println("You won")
case c if beats(c) contains h => println("You lost")
case _ => println("We drew") // or underspecified
}
case x => println(" Unknown weapon, try again.")
}
play(beats, played get h match {
case None => played
case Some(count) => played.updated(h, count + 1)
})
}
def play(beats: LinkedHashMap[Symbol,Set[Symbol]]): Unit =
play(beats, beats.mapValues(_ => 1)) // init with uniform probabilities
play(LinkedHashMap(
'rock -> Set('lizard, 'scissors),
'paper -> Set('rock, 'spock),
'scissors -> Set('paper, 'lizard),
'lizard -> Set('spock, 'paper),
'spock -> Set('scissors, 'rock)
))
}
|
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 recently. You can find this out by searching the chat logs. The logs are publicly available at http://tclers.tk/conferences/tcl/. One log file corresponds to the messages from one day in Germany's current time zone. Each chat log file has the name YYYY-MM-DD.tcl where YYYY is the year, MM is the month and DD the day. The logs store one message per line. The messages themselves are human-readable and their internal structure doesn't matter.
Retrieve the chat logs from the last 10 days via HTTP. Find the lines that include a particular substring and print them in the following format:
<log file URL>
------
<matching line 1>
<matching line 2>
...
<matching line N>
------
The substring will be given to your program as a command line argument.
You need to account for the possible time zone difference between the client running your program and the chat log writer on the server to not miss any mentions. (For example, if you generated the log file URLs naively based on the local date, you could miss mentions if it was already April 5th for the logger but only April 4th for the client.) What this means in practice is that you should either generate the URLs in the time zone Europe/Berlin or, if your language can not do that, add an extra day (today + 1) to the range of dates you check, but then make sure to not print parts of a "not found" page by accident if a log file doesn't exist yet.
The code should be contained in a single-file script, with no "project" or "dependency" file (e.g., no requirements.txt for Python). It should only use a given programming language's standard library to accomplish this task and not rely on the user having installed any third-party packages.
If your language does not have an HTTP client in the standard library, you can speak raw HTTP 1.0 to the server. If it can't parse command line arguments in a standalone script, read the string to look for from the standard input.
|
#Go
|
Go
|
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
)
func get(url string) (res string, err error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(buf), nil
}
func grep(needle string, haystack string) (res []string) {
for _, line := range strings.Split(haystack, "\n") {
if strings.Contains(line, needle) {
res = append(res, line)
}
}
return res
}
func genUrl(i int, loc *time.Location) string {
date := time.Now().In(loc).AddDate(0, 0, i)
return date.Format("http://tclers.tk/conferences/tcl/2006-01-02.tcl")
}
func main() {
needle := os.Args[1]
back := -10
serverLoc, err := time.LoadLocation("Europe/Berlin")
if err != nil {
log.Fatal(err)
}
for i := back; i <= 0; i++ {
url := genUrl(i, serverLoc)
contents, err := get(url)
if err != nil {
log.Fatal(err)
}
found := grep(needle, contents)
if len(found) > 0 {
fmt.Printf("%v\n------\n", url)
for _, line := range found {
fmt.Printf("%v\n", line)
}
fmt.Printf("------\n\n")
}
}
}
|
http://rosettacode.org/wiki/Rhonda_numbers
|
Rhonda numbers
|
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.
25662 is a Rhonda number to base-10. The prime factorization is 2 × 3 × 7 × 13 × 47; the product of its base-10 digits is equal to the base times the sum of its prime factors:
2 × 5 × 6 × 6 × 2 = 720 = 10 × (2 + 3 + 7 + 13 + 47)
Rhonda numbers only exist in bases that are not a prime.
Rhonda numbers to base 10 always contain at least 1 digit 5 and always contain at least 1 even digit.
Task
For the non-prime bases b from 2 through 16 , find and display here, on this page, at least the first 10 Rhonda numbers to base b. Display the found numbers at least in base 10.
Stretch
Extend out to base 36.
See also
Wolfram Mathworld - Rhonda numbers
Numbers Aplenty - Rhonda numbers
OEIS:A100968 - Integers n that are Rhonda numbers to base 4
OEIS:A100969 - Integers n that are Rhonda numbers to base 6
OEIS:A100970 - Integers n that are Rhonda numbers to base 8
OEIS:A100973 - Integers n that are Rhonda numbers to base 9
OEIS:A099542 - Rhonda numbers to base 10
OEIS:A100971 - Integers n that are Rhonda numbers to base 12
OEIS:A100972 - Integers n that are Rhonda numbers to base 14
OEIS:A100974 - Integers n that are Rhonda numbers to base 15
OEIS:A100975 - Integers n that are Rhonda numbers to base 16
OEIS:A255735 - Integers n that are Rhonda numbers to base 18
OEIS:A255732 - Rhonda numbers in vigesimal number system (base 20)
OEIS:A255736 - Integers that are Rhonda numbers to base 30
Related Task: Smith numbers
|
#Phix
|
Phix
|
with javascript_semantics
constant fmt = """
First 15 Rhonda numbers in base %d:
In base 10: %s
In base %-2d: %s
"""
function digit(integer d) return d-iff(d<='9'?'0':'a'-10) end function
for base=2 to 36 do
if not is_prime(base) then
sequence rhondab = {}, -- (base)
rhondad = {} -- (decimal)
integer n = 1
while length(rhondab)<15 do
string digits = sprintf("%a",{{base,n}})
if not find('0',digits)
and (base!=10 or (find('5',digits) and sum(apply(digits,even))!=0)) then
integer pd = product(apply(digits,digit)),
bs = base*sum(prime_factors(n,true,-1))
if pd==bs then
string decdig = sprintf("%d",n)
integer l = max(length(decdig),length(digits))
rhondab = append(rhondab,pad_head(digits,l))
rhondad = append(rhondad,pad_head(decdig,l))
end if
end if
n += 1
end while
printf(1,fmt,{base,join(rhondad),base,join(rhondab)})
end if
end for
|
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.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#PureBasic
|
PureBasic
|
Procedure.s RLDecode(toDecode.s)
Protected.s repCount, output, currChar, tmp
Protected *c.Character = @toDecode
While *c\c <> #Null
currChar = Chr(*c\c)
Select *c\c
Case '0' To '9'
repCount + currChar
Default
If repCount
tmp = Space(Val(repCount))
ReplaceString(tmp, " ", currChar, #PB_String_InPlace)
output + tmp
repCount = ""
Else
output + currChar
EndIf
EndSelect
*c + SizeOf(Character)
Wend
ProcedureReturn output
EndProcedure
Procedure.s RLEncode(toEncode.s)
Protected.s currChar, prevChar, output
Protected repCount
Protected *c.Character = @toEncode
prevChar = Chr(*c\c)
repCount = 1
*c + SizeOf(Character)
While *c\c <> #Null
currChar = Chr(*c\c)
If currChar <> prevChar
output + Str(repCount) + prevChar
prevChar = currChar
repCount = 1
Else
repCount + 1
EndIf
*c + SizeOf(Character)
Wend
output + Str(repCount)
output + prevChar
ProcedureReturn output
EndProcedure
If OpenConsole()
Define initial.s, encoded.s, decoded.s
Print("Type something: ")
initial = Input()
encoded = RLEncode(initial)
decoded = RLDecode(encoded)
PrintN(initial)
PrintN(RLEncode(initial))
PrintN(RLDecode(encoded))
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf
|
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 input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
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 rot13(s)
local a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
local b = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"
return (s:gsub("%a", function(c) return b:sub(a:find(c)) end))
end
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#Yorick
|
Yorick
|
haystack = ["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"];
needles = ["Bush", "Washington"];
for(i = 1; i <= numberof(needles); i++) {
w = where(haystack == needles(i));
if(!numberof(w))
error, "Needle "+needles(i)+" not found";
write, format="Needle %s appears first at index %d\n", needles(i), w(1);
if(numberof(w) > 1)
write, format="Needle %s appears last at index %d\n", needles(i), w(0);
}
|
http://rosettacode.org/wiki/Search_a_list
|
Search a list
|
Task[edit]
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack).
Raise an exception if the needle is missing.
If there is more than one occurrence then return the smallest index to the needle.
Extra credit
Return the largest index to a needle that has multiple occurrences in the haystack.
See also
Search a list of records
|
#zkl
|
zkl
|
L("Krusty","Charlie","Bozo","Bozo").index("Charlie") //--> 1
L("Krusty","Charlie","Bozo","Bozo").index("fred") //--> throws index error
|
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 numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#Io
|
Io
|
Roman := Object clone do (
nums := list(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
rum := list("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")
numeral := method(number,
result := ""
for(i, 0, nums size,
if(number == 0, break)
while(number >= nums at(i),
number = number - nums at(i)
result = result .. rum at(i)
)
)
return result
)
)
Roman numeral(1666) println
|
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 decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#Liberty_BASIC
|
Liberty BASIC
|
print "MCMXCIX = "; romanDec( "MCMXCIX") '1999
print "MDCLXVI = "; romanDec( "MDCLXVI") '1666
print "XXV = "; romanDec( "XXV") '25
print "CMLIV = "; romanDec( "CMLIV") '954
print "MMXI = "; romanDec( "MMXI") '2011
end
function romanDec( roman$)
arabic =0
lastval =0
for i = len( roman$) to 1 step -1
select case upper$( mid$( roman$, i, 1))
case "M"
n = 1000
case "D"
n = 500
case "C"
n = 100
case "L"
n = 50
case "X"
n = 10
case "V"
n = 5
case "I"
n = 1
case else
n = 0
end select
if n <lastval then
arabic =arabic -n
else
arabic =arabic +n
end if
lastval =n
next
romanDec =arabic
end function
|
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:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
$ include "keybd.s7i";
const array string: rockPaperScissors is [] ("Rock", "Paper", "Scissors");
const proc: main is func
local
var char: command is ' ';
var integer: user is 0;
var integer: comp is 0;
begin
writeln("Hello, Welcome to rock-paper-scissors");
repeat
write("Please type in 1 for Rock, 2 for Paper, 3 for Scissors, q to quit ");
flush(OUT);
repeat
command := lower(getc(KEYBOARD));
until command in {'1', '2', '3', 'q'};
writeln(command);
if command <> 'q' then
user := integer parse str(command);
comp := rand(1, 3);
writeln("You Played: " <& rockPaperScissors[user]);
writeln("Computer Played: " <& rockPaperScissors[comp]);
if comp = user then
writeln("You Tied");
elsif succ(comp) = user or user + 2 = comp then
writeln("Yay, You Won!");
else
writeln("Sorry, You Lost!");
end if;
end if;
until command = 'q';
writeln("Goodbye! Thanks for playing!");
end func;
|
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 recently. You can find this out by searching the chat logs. The logs are publicly available at http://tclers.tk/conferences/tcl/. One log file corresponds to the messages from one day in Germany's current time zone. Each chat log file has the name YYYY-MM-DD.tcl where YYYY is the year, MM is the month and DD the day. The logs store one message per line. The messages themselves are human-readable and their internal structure doesn't matter.
Retrieve the chat logs from the last 10 days via HTTP. Find the lines that include a particular substring and print them in the following format:
<log file URL>
------
<matching line 1>
<matching line 2>
...
<matching line N>
------
The substring will be given to your program as a command line argument.
You need to account for the possible time zone difference between the client running your program and the chat log writer on the server to not miss any mentions. (For example, if you generated the log file URLs naively based on the local date, you could miss mentions if it was already April 5th for the logger but only April 4th for the client.) What this means in practice is that you should either generate the URLs in the time zone Europe/Berlin or, if your language can not do that, add an extra day (today + 1) to the range of dates you check, but then make sure to not print parts of a "not found" page by accident if a log file doesn't exist yet.
The code should be contained in a single-file script, with no "project" or "dependency" file (e.g., no requirements.txt for Python). It should only use a given programming language's standard library to accomplish this task and not rely on the user having installed any third-party packages.
If your language does not have an HTTP client in the standard library, you can speak raw HTTP 1.0 to the server. If it can't parse command line arguments in a standalone script, read the string to look for from the standard input.
|
#Julia
|
Julia
|
using Dates, TimeZones, HTTP, Printf
function geturlbyday(n)
d = DateTime(now(tz"Europe/Berlin")) + Day(n) # n should be <= 0
uri = @sprintf("http://tclers.tk/conferences/tcl/%04d-%02d-%02d.tcl",
year(d), month(d), day(d))
return uri, String(HTTP.request("GET", uri).body)
end
function searchlogs(text = ARGS[1], daysback = 9)
for n in -daysback:0
fname, searchtext = geturlbyday(n)
println("$fname\n------")
for line in split(searchtext, "\n")
if findfirst(text, line) != nothing
println(line)
end
end
println("------\n")
end
end
if length(ARGS) != 1
println("Usage: type search phrase in quotes as an argument.")
else
searchlogs()
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 recently. You can find this out by searching the chat logs. The logs are publicly available at http://tclers.tk/conferences/tcl/. One log file corresponds to the messages from one day in Germany's current time zone. Each chat log file has the name YYYY-MM-DD.tcl where YYYY is the year, MM is the month and DD the day. The logs store one message per line. The messages themselves are human-readable and their internal structure doesn't matter.
Retrieve the chat logs from the last 10 days via HTTP. Find the lines that include a particular substring and print them in the following format:
<log file URL>
------
<matching line 1>
<matching line 2>
...
<matching line N>
------
The substring will be given to your program as a command line argument.
You need to account for the possible time zone difference between the client running your program and the chat log writer on the server to not miss any mentions. (For example, if you generated the log file URLs naively based on the local date, you could miss mentions if it was already April 5th for the logger but only April 4th for the client.) What this means in practice is that you should either generate the URLs in the time zone Europe/Berlin or, if your language can not do that, add an extra day (today + 1) to the range of dates you check, but then make sure to not print parts of a "not found" page by accident if a log file doesn't exist yet.
The code should be contained in a single-file script, with no "project" or "dependency" file (e.g., no requirements.txt for Python). It should only use a given programming language's standard library to accomplish this task and not rely on the user having installed any third-party packages.
If your language does not have an HTTP client in the standard library, you can speak raw HTTP 1.0 to the server. If it can't parse command line arguments in a standalone script, read the string to look for from the standard input.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
matchFrom[url_String, str_String] := Select[StringSplit[Import[url, "String"], "\n"], StringMatchQ[str]]
getLogLinks[n_] :=
Select[Import["http://tclers.tk/conferences/tcl/", "Hyperlinks"],
First[
StringCases[#1, "tcl/" ~~ date__ ~~ ".tcl" :> DateDifference[DateObject[URLDecode[date], TimeZone -> "Europe/Berlin"], Now]]] <=
Quantity[n, "Days"] & ]
searchLogs[str_String] := Block[{data},
Map[
(data = matchFrom[#, str];
If[Length[data] > 0,
Print /@ Join[{#, "-----"}, data, {"----\n"}]]) &,
getLogLinks[10]]]
searchLogs["*lazy*"];
|
http://rosettacode.org/wiki/Rhonda_numbers
|
Rhonda numbers
|
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.
25662 is a Rhonda number to base-10. The prime factorization is 2 × 3 × 7 × 13 × 47; the product of its base-10 digits is equal to the base times the sum of its prime factors:
2 × 5 × 6 × 6 × 2 = 720 = 10 × (2 + 3 + 7 + 13 + 47)
Rhonda numbers only exist in bases that are not a prime.
Rhonda numbers to base 10 always contain at least 1 digit 5 and always contain at least 1 even digit.
Task
For the non-prime bases b from 2 through 16 , find and display here, on this page, at least the first 10 Rhonda numbers to base b. Display the found numbers at least in base 10.
Stretch
Extend out to base 36.
See also
Wolfram Mathworld - Rhonda numbers
Numbers Aplenty - Rhonda numbers
OEIS:A100968 - Integers n that are Rhonda numbers to base 4
OEIS:A100969 - Integers n that are Rhonda numbers to base 6
OEIS:A100970 - Integers n that are Rhonda numbers to base 8
OEIS:A100973 - Integers n that are Rhonda numbers to base 9
OEIS:A099542 - Rhonda numbers to base 10
OEIS:A100971 - Integers n that are Rhonda numbers to base 12
OEIS:A100972 - Integers n that are Rhonda numbers to base 14
OEIS:A100974 - Integers n that are Rhonda numbers to base 15
OEIS:A100975 - Integers n that are Rhonda numbers to base 16
OEIS:A255735 - Integers n that are Rhonda numbers to base 18
OEIS:A255732 - Rhonda numbers in vigesimal number system (base 20)
OEIS:A255736 - Integers that are Rhonda numbers to base 30
Related Task: Smith numbers
|
#Raku
|
Raku
|
use Prime::Factor;
my @factor-sum;
@factor-sum[1000000] = 42; # Sink a large index to make access thread safe
sub rhonda ($base) {
(1..∞).hyper.map: { $_ if $base * (@factor-sum[$_] //= .&prime-factors.sum) == [×] .polymod($base xx *) }
}
for (flat 2..16, 17..36).grep: { !.&is-prime } -> $b {
put "\nFirst 15 Rhonda numbers to base $b:";
my @rhonda = rhonda($b)[^15];
my $ch = @rhonda[*-1].chars max @rhonda[*-1].base($b).chars;
put "In base 10: " ~ @rhonda».fmt("%{$ch}s").join: ', ';
put $b.fmt("In base %2d: ") ~ @rhonda».base($b)».fmt("%{$ch}s").join: ', ';
}
|
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.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#Python
|
Python
|
def encode(input_string):
count = 1
prev = None
lst = []
for character in input_string:
if character != prev:
if prev:
entry = (prev, count)
lst.append(entry)
count = 1
prev = character
else:
count += 1
else:
try:
entry = (character, count)
lst.append(entry)
return (lst, 0)
except Exception as e:
print("Exception encountered {e}".format(e=e))
return (e, 1)
def decode(lst):
q = []
for character, count in lst:
q.append(character * count)
return ''.join(q)
#Method call
value = encode("aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa")
if value[1] == 0:
print("Encoded value is {}".format(value[0]))
decode(value[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 input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
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
|
#Malbolge
|
Malbolge
|
b'BA@?>=<;:9876543210/.-,+*)('&%$#"!Q=+^:('&Y$#m!1So.QOO=v('98$65a`_^]\[ZYXWVUTSRQ#I2MLKJIHGFE
DCBA@#!7~|4{y1xv.us+rp(om%lj"ig}fd"cx``uz]rwvYnslkTonPfOjiKgJeG]\EC_X]@[Z<R;VU7S6QP2N1LK-I,GF(
D'BA#?>7~;:9y16w43s10)p-,l*#(i&%e#d!~``{tyxZpuXsrTTongOkdMhg`Hd]ba`_^W@[ZYXW9UNSRQPOHMLKJ-++FE
''<A$?>=<;:387xw43s10/(-&m*)('&}${d!~}|^zyxwvutmVqpiRQlkjiKafedc\E`_^@\[ZYX;V9NMRQ42NGLK.IH*F?
DCBA$#>7~;{{8xx5uu2rr/oo,ll)ii&f|e"!aw`{z\r[vXnmVTpongPkNihgJ_dcFa`B^]\UZ=RWV8TSLQ4ON0LE.IHA)E
>'BA:?!7~5|38y6/v321q).-&m*)i'&%|{d!~}_{zs\wvutsUqTonPlOjiKgJedFbE`_A]@[Z<X;VU7S6QP22GL/JIB+FE
DC%;@?>7~;:987w5v32r0)p-,+k)('~g$#"b~w|uz]xwvutsrqTinQlOjLhgfeH]bE`CB]\>ZSXWVUTSRQPON1LE.I,+*(
(&&$$""~~||zzxxv4u210/(-n+l)ji~g|eccaa_{zy[qZoXVVTponPfOdiLJJ_HFba`BXAV?==;;9977pQPONMLKJIHGFE
DCBA@?>=<;:9876543210/.-,+*)('&%$#"!~}|{zyxwvutsrqponmlkjihgfedcF!`_^]\[ZYXWVUTSRQPONMLKJIHGFE
DCBA@?>=<;:9876543210/.-JI*)FE&%$#"!~}|{zyxwvutsrqponmlkjihgJ%dcF!`_^]\[ZYXWVUTSRQPO2kLKJIHGF)
bCBA@?>=<;:9876543210/.-JI*)FE3%$#"!~}|{zyxwvutsrqponmlkjihgJ%dcF!`_B{\[>wXWVUTSRQPO2kLKJIHGF)
bCBA@?>=<;:9876543210/.-JI*)FE&%$#"!~}|{zyxwvutsrqponmlkjihgJ%dcF!`_B{\[ZYX;VUTS6Q4O200EJIH*@)
>'%A@?!7~5|zzx65u3,s*qoommk)(h&}f{dbb``^^\xwYutWVkToRmlkjMLgfHdcF[DBB@\?==RWV8TM6K4220LK-IB+@E
(&&;$""~~||zzxxv4u21r/.o,mlk"i&g$#"!b}`{^\\qvYWWlUSSQQOkjiKaJ_HFFD`_A]V?T=;;997SRQ3I2G0.JIH*@)
>'%A@">=~}4{8y6wv3trr).omm$)j'&g$#d!ba`u^y\wZYtWrqTonmOOdihK`IHG\a`_AW@U><XWV8N7LQ422G0.JI+G@)
>C&$$9"~~||z87w5.u,sqqoommkki'h%$e"yb}`_t][wvXtmVkpSQQfOMihgI_H]FD`_A]V?T=;;99775QPO1G0E.,HG)E
>'<A$""7~||z8y654u,s0qp',m*)ii&}$e"cb``^z][[putVrkTiRPPNjMKK`edFb[DYB@\?==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LLJJHdcbDZCX]@>>S<::88664P3NMLE.-,AF)
DC&$$9"!<;{92y05vtt+rppnnlljjh&%$dzcx}`^^s\ZZXXVVTTRnQlkNiLaJeHG\a`_A]@UZ=XWV9TMR54O2ML/--HG@)
(C&$$9>=};:{2ywwuus10p.'n%ljjhhffddbb``^z]xwZuXsrkToRmPkjLLgfe^cFaDCXAV?=YX:VO8MR533H1//--+GF(
D=&;$""~~||zzxxv4u210q.-,%*k(i&g$#cc~}|{t]x[vuWsrUjSQQOkNLLafeGc\EZCAA??==;W:88MRQ3OH1F/--++))
'C&$$9>!<;:{8765.u2sr)p'nlljjhhffddb~}_{t]r[YYWWUUSoRmlkdMhKJ_dcbDZCX]@>>S<::8866442200..,,**(
D'BA@9"=~}4{27x54tt+0q.onlljjhhf$#c!xav_]][[YYWWUUSoRmlkNchKJeHcbECC^W@?Z=;;PUT6RK4I200..,,**(
(&&$$""~~|:{87x5v3,s0q.o,+kk('~%f#d!b``uz][[pYnsVTTinQlkjMhg`eHGF[`C^]@>>YXWP98SR4PO2G0..,,*FE
'C<%:#!!}}{{yywwuus1r/.o,m*)(!h%f#d!~``{zyxqvYtWVkTinQOOdihJf_H]FD`CAAV[Z<XQ:O8664PO1MF/D-++))
''%%##!!};|987x5432+0q.o,mkk"'&f$#dybw|_zyxqZuXWlqTonmfOjMhKfeGG\E`C^A??T=R;997S644INM/KD-B+)E
D&B;$9"~~||zzxxvvttr0q.-,m$kji~%f#"caa|uz]\wZXXmrqSonQfOMihJf_H]FDDBB@\[=YR;PU866K4220LK-IB+@E
(&&;$""~~||z8y65v3t1*/p-n+l)(hh%${d!bav{^\\qZXtWUUjonPleNcLJJHdcbDZCXA??==;;9977553O2MLK.IHA*)
D'BA$""=<;49zyx/v-trrppnnl*)i'~g|eccaa__]][[YuXsrUpSnmlejMLgJedGEE`_^]V?>YX:VU8MRQ3OH1FK.,,A*(
D'%%:?>~<5|3zx6wuu,10p.'n%ljjhhffd"caav{z\xqZoXVVTTRRPlOMMbgJedGbE`_^]V?Z=X;VUTSR44INM0E.I,+@E
(&&;@?>~6}4{y765u-t+rppnnllj('g%|ezcaa__]][[YuXsrqjSRmPkjMKK`eHGbECCXAV?==;W:88MRQ3OH1F/-I,**?
DC%A:#8!};:9y1x/vttrrppnnllj(i&%f#dy~a`{zy[wZoXmVTTRRPlkMibK`eHFF[DBB@\[=YR;PU866K42NM/KD-BG*(
(=&$$""~~|:{87x5v3,sr/p-,mkk('~%fedybw`^zy[wpYnsVTTiRPPNNLLJfeGc\EZCAA??==;;9U8SR5P3NMFK.I,+@E
(CB$$?>=6}:{zxxv432r*q(ommkki'&%e{dy~a__t][[YYWWUUSoRmlkNihg`IdGbE`_AA\[ZYRW:U87LQ422G0.JIH*@)
>'%%##!!}}{{yywwuus1r/.-n+*)(!&gf#d!~a|{z\\qvuXmVUpSQQfOMihgI_H]bECCXA??=YX:VO8M6442200..,,**(
D'BA$?8!~}49z76wuu,sr/pnn%l#(igg|#d!~a|_t]x[ZotWrqSSnglOjMhgIedG\ECCA]@>>SXW9UN7L53311//--++))
''%A$""7<}:98y6/4uts*q(o&+l)(igg$#zcb}`^^sxwYunWlUSSQQOOMiLJJ_dcEaZCXA??=YX:VO8MR533H1//--++)E
(CB%@#>=6}:{8y65uu210).o,m*kii~%fddy~}_{t]r[YYWWUUSSQmlNjcLaJHHFFDDBB@\?ZYX;VUTMR543HM0KJ-++FE
DC<%$#!!};:z81x/4uss*qoommk)('g}f{dbb``^^\\ZvYtsVqTonmleNiLgJedcbaCCX]\?T=X;:O86RQP2H1FK.,,A*(
DCB$:#8!};:z81x/vttrrppnnlljjh&g$#"yba`u^sx[vuXVVkpSRmlNjcLaJHHFFDDBB@@>><<::886R5PO2M0EJ-,+@E
(CB%##>7~}:98x0w.ussq/.n,%l#(igg|ec!~`|u^sx[YYnWUqpoQgPejMKK`IGGEECCAA??=Y<WV9T7RK4O21FK.IH**E
D=B%@#>=};:{27xvv-2s0/.o,+$)j'h%f#"bb}|{t]x[vYWWl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qq(-,l*)j!&%e#zcxa__]][[YYWWUUSSQQOOMiLgfIdGbaZC^A\?==R;PU8SRQ4ONMFK.-H+FE
(&&A@?>7~}:{yy054t21r).omm$)j'&g$e"!~}v_z]\qZoXmrqpRhQfOMihJf_H]bECCXA??==;;9977553311/K.IHG@)
(C&A@#!!6;|{z16wuu,1rpp',+k)"i~geeccaa_{^\\qvuWslUjSQQOkjLhaJ_dGEEZCAA??==;W:UT7R5JO2M0/DI,GF(
(C<%@#>=};:{2ywwuus10p.'n%*kii~geec!~`|u^s\ZZXXVVTTRnQlkjMhaJIH]bE`_B@@[ZSX;:U866KPO1ML/D-++))
''%%##!=<|:3z16wuu,sqqoommk)j'&g$e"!x}`{^y\wvXXsrqjSnQlOMMbgJHH]FDDB^A??TYX:VO8M6442200..,,**(
(&B%@?>!<;:3z7x5v32rr/.-,%*k(i&geez!b``u^s\ZvuWslUjSQmlNjcLafIGG\EC_^@\U>SX;99N7553311//--++)E
(CBA$?>=<5:{8yx/432r0q(-n+*)"i&gf{"!~`v_ty\ZZoXVVTTRRPPNNLLJJHHFFD`C^]\U>=X;VU866K43N1//D-+GF(
D=&;@#!!6}{98x6/v-trrppnnlljjhhffd"c~}`{^s\wZuXsrTTohmPkNiLJJ_H]FD`_A]V?T=;;9UT6RK4IN1//D-++))
''%%##!!};|987x5.3t1rq(-nll#j!&g$#"c~}v_^]rwZutWUUponglONMKKIeHFF[`_A]V?T=;WV8TM6K42N1//DIH*F?
(=&$$""~~||zzx6w43t1r/.-&+l)ji~%f#"bb}|{zs\wZuXVVkpoQmlOdihJf_H]FDDBB@@>><<::8866442N1LKJ-HGFE
>'&A$?>!<;:zz165v-ts0/o-,m$)jhh}$#c!xav_]][[YYWsrTpiRglOMMbKIIGGEECCAA?[>YX;VO876K4IN1LK.,,AF)
(C&$$9>=};:{27x54u2s*/p-nm$k"'h%$dd!xa|_z][[putVrqTinQlkjMhaJIH]bE`_B@@[ZSX;:9N7553ONM/E.C,*FE
'C<%:#!!}}{{yywwuus1r/.o,m*)"'hgf{"c~}`^^yxwpYXsVTTiRglOMMbgJedGbE`_^W@[>=RW:UT66QPONGL/J-,**(
(&BA#?8!6}{{yywwuussqqo-n+*)j'&%${"cb}`{z]xwvXXmrqTiRQPejiKg`I^cFDDYB@@>ZY;WP9NS644I20LK-IB+@E
(&&;$">=};4{27xvv-trrppnnlljjh&g$#d!xa`_ty\wvYWWlUTonPleNchKII^GEECCA]\>ZS<Q:8866442200..,H+FE
(C&;$#>=<|:{2765u-t+rppnnlljjh&%e#zcx}`^^s\ZvuWslUjoRPPeNLLJJHHFbE`_B]@[TY<;:OT7RQ422MLE.-H+))
>CB$@9"7~|:{yy054t2+r)pn,+k)"i~geeccaa_{zy[qZotWUUjSQQOOMMKgJedGbE`_XA@[>YX;99TSRKP32M0..CH+))
>'<%#?>=}5|3zx65u3,s*/pnn%ljjhhffddbb``^^\x[vuXsVqpohmPkNMbgJedFFa`_^W@[>YX:VU8MR533HM0KJI,GFE
D=&A$?"=<;:9yy054u,s0qp'n%lj(igg|#"b~w`u^\xwYunWlUSonPleNchKII^GEa`B^W@UZ=;;P977553311//-I,GFE
>'&A$?>!}}49zy6wuu,10p.-n%*kii~%f#"c~av{^]\qvYtsVTTohQPkNLLafeGc\EZCAA?[><<QVU7SL5J31ML.JC,A*(
(&&$$""~~||z8y65v3t1*qp-n+*kii&%|#dcbw|_]]r[YuXVVkpoQmfOdMKKIIGGEa`B^W@U><<::88664P3NM0K.IHAF)
('<A$""7~5:{87x5v321*qpo&+l)(i&g$#"!x}`{^y\wvutsUUjonQfOjMhKII^cbD`YBW@>Z=;;PUT6RK4I200..,,**(
(&&$$""~<}:981xw4uss*q(-n+*k(i~gfez!b}|_]]xqvYXsrTpiRglOMMbKIIGcFDDY^]?[T=R;9UT6RK4I200..,,**(
(&&$@#>=~;|927x5v3t10pp-,%l)j'hff{"!~`v_t][[YYWsrTpiRgPNNLLJfeGc\EZ_B@@U><<::886R5PON1LKD-,+@E
(CB%##>=<5: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866K42NML.D-B+)E
(CBA$?>=<5|{8y65v321qq(-,m$kji~g|#dbbw|{]yr[pYWWUUSonPleNcLJfeGc\EZ_B@@U><<::8866442N1LK.IB+*E
(CB%##8=~}|3876v.u,sq/.n,%l#jh&%e#zcx}`^^s\ZvutVlUjSQQOkjLhaJ_HFFDDBB@@>Z=XW:U8MR543HM0..CHG)E
>'<%##!!};|zz165u3,s*qoom+ljj!&%$dzcxa_{z\xqZotWUUjSQQOOMMKgJedGbE`YBA\?ZY<::UTMR543H1F/--+G*(
(=BA#?8!6}{9zxx/43s1*q(ommkkiiggeecca}`^^sx[vuXsVqpinQlONchgIedG\EZ_B]\[>YXWP9T7R5PO11LKJIBG*E
('<%:#!!};|zz165u3,s*qoom+ljj!&%e#zcxa__]][[YYWWUqTRRglOjihKfedc\aD_B]@[ZYXW99NSR5J3N1LK-IH+@)
'CB$@9"7<}{{2ywwuussqqoommkkiig%f#"!xa`{^yx[YYnWVqTRRglkMibK`IGGEEC_^@\U>SX;99N7553311//--++)E
(CB%@#8!~;|98yww4-2sr/pnn%*kii~ge#"b~w`uz][[pYWWUUSSQQOOMMKKIIGcFa`C^A\UZ=<;PUTS5Q4IN1LK.I,GF?
(C&A$?>~~;:927x5v3trr)pnnllj('g%|ezca}`^^sxwYunWlUSSQQOOMMKKIeHcbaD_^]V[>=X;VU866QPONG0/.C,AF)
''<A@">7~5|zzx6wuu,10p.'n%lj('g%|ezcaa__]][[YYWWUqTonQlOjihg`IHcFa`C^]\>>SXW:O87R533HM0..C,A*(
(&BA@"8!6}{{y76v4-t+0qoo&mkkiiggeecca}`{z]xqZYtWrqTRRglONMbgJHH]ba`BXAV?==;;9UT6RK4IN1//D-++))
''%%##!!};|98y6w.3t1r/p-,ll)"i&g$eccx}|^zs\qZXXVVTTRRPPNNLLJJHHFbE`_^A\U>Y<;PU8SR44ONGL/J-H+))
>'<A$""7<}:98y65.3ts0q.-nll)('~gf#"b~}`uzy[wpYnWUqpRngPeNLLJJHdGEEZ_^@\U>S<::886644220L/JI,G*E
DC<%$?"=<}{{8765.3tsr).omm$)('g}f{dbb``^zyxZpYnWUqTRRglkMibK`IGGEa`B^W@UZ=;;P97755331M0KJ-H+FE
DC<A$?"!6}4{2yw543s+r).omm$kiigge#dbbw|{]yr[pYWWUUSSQQOOMiLgfe^GFaDBBW@U><<:VU7SL5JO200E.,,*FE
D&<%:#!!}}{{yywwu3t10q.o&ml)j'&gee"y~a`_ty\ZZoXVVTTRnQOOdihJf_H]FDDBB@\[=YR;PU866K42200..,H+FE
(C&A:?"=~}4987w/v-trrppnnl*)i'~g|ec!~`|u^sx[YYnWUUSSQQOOMiLgfeHcb[D_B]@[Z<<WVUNS6Q4ON0LK.C,**(
D'%%:?>~<5|3zx65u3,s*/pnn%ljjh&%e#zcxa__]][[YYWsVqpoRmlkdiLgJeHcbDD_^]\U>Y<W:88MRQ3ON1FK.,,AFE
'C<%:#!!}}{98x6/v-trrppnnlljjhhf$e"!~a|{zyr[ZuXsrUponPPejiLaJIH]F[DBB@\[=YR;P9775QP2NG0EJ-++@)
''%%##!!}}{9z76w4-ts0q.-nll#(ih%fddybw|{z\r[pYWsrqSiRgPNjiKg`I^GEECCA]\[=S<QV977L53311//-IHG)?
(=B%##8!};|98y6w.3t1r/p-,ll)"i&g$eccx}|^zy\qZXXVVTpoQmfOdMKKIIGGEECCAA?[>YXW:UN76Q4ON1//JIBG*)
(=&;$">!}}498x6/v-trrppn,+k)"i~geeccaa__]][wZutWrUpohmPONcLaJHHFbECCX]\[=S<Q:886644220L/--BGFE
'=&;$">!}}4987w/v-tr0qoo&+*)i!h}fd"c~}`{^yxwpYXsVqpSQQlkjibgJIdGEEZCAA??==;WV8TM6KP311F/-IHG)?
(=B%##8!};:9y1x/4uss*qoommkki'h%$e"c~}|{ty\wZYnWlUSSQQOkjLhaJ_HFFDDBB@@>><<:V9TSRK4O21F/DI,GF(
(=&A$?"~~5:9y70w.ussq/.-m%l#jh&%e#zcx}`^^s\ZZXXVVTTRRPPNj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_^]r[pYWsVTTinmOkdMbKIedFb[DYB@@>><<::8866442N1LK.IB+*E
(CB%##8=~}:{yy054t21r)pnnl*kii~%$d"ybw`^zy[wpYnWUUSSQQOOMMKKIeHcbE`CX]@?>SX;VU866QJ321/KJ,HA*?
(&&$$""~~||zzxxvvt2s0/p-n+$k(ih}$e"!aa|{ty\wZYWWUUSSQmlNjcLafIGG\ECCA]\>ZS<QV977L53311//-I,GFE
(CB;@#"=~;:{yy654-tsr)p',+k)"i~geecca}|^zs\qvYWWlUSSQQOOMMKKIIGcFa`C^A\[ZS<W:9NS6QP22MLKJCH+F)
(&&$$""~~||z876v.u,1rpp'nlljjhhf$e"!~a|{zyrwZYtWrqTonmOOdihK`IHcbD`_BW@>><X;99NSR4PI2G0..,H+))
>CB$@9"7~||zzxxvvttr0q.-n+$kj'h%$eccxa`_ty\ZZoXVVTponPfOdMKKIedcE[DY^A??T=;;997755331M0KJ-H+@)
(C&A@#!!<5:{zy0wu32r0)p',mkk"iggeeccaa__]][[YYWsVqpSnQlejMhKfIdcEE`_XA\?ZY;WV9N75Q422GLK-IB+@)
''%%##!=<|:3z16wuu,sqqoommkki'hff{"c~}|_zyr[ZuXsrUSSnmlejMLgJHH]baC_^AV?==;W:88MRQ3OH1F/--++))
''%%##!!};|zz16w43t1r/.-&+l)ji~g|#"!aw`uz][[pYWWUUSonPleNchKII^GEECCA]\>ZS<QV977L53311//-I,GFE
(CBA@9"!<}:9z765uu,10q(onm$k"ig%fddy~}_{t]r[YYWsVTTinmOkdMbKIedFb[DYB@@>><<::886R5PO2MF/J-,AFE
'CB%:#8=~;:9z16wv32r0/p'nllj(igg|#"b~w`u^\x[YYnsrTpiRgPNNLLJJHHFFDDB^A\[>Y<WP9T76KP3NM//JIBG*E
('<A$""7<;:z2y0wuussq/.-m%l#jh&%$dzcxa_{zy[qZoXVVTTRRPPNjMhgfIdc\aDC^]?[Z=R;99775Q422GLK-IB+@)
'CB$@9"7<}{{2ywwuussqqoom+l)(i&g$#"y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y65vtt10).on+ljj!&geez!b}|_z]xwpuXsVUjonPleNchKII^GEEC_B@@UZYX:P9N7553ON0LE.CH+))
>'%%##!!}}{{y7x543t10/(on+l)(igg$#"!x}`_z][[puXVVkpSnmPkNihgf_dGbE`C^]\[Z<<QVU8M6Q43H1FKJ,HA*?
D'%%:#!!};|zz165u3,s*qo-,l*#j!hffddbb``^^\\ZvYtsrkToRQfkNLLafedF\EZCA]@>>SXW9UN7L53311//--++))
''%%#?"=<;|3zy6w43trr/(-nm*kii~%fddy~a|{^y\wpuXsVUjSQmlNjcLafIGG\ECCA]\[=S<QV977L53311//--++))
'C&A@?"=<5|9z7x54tt10/(-n+l)jhh}$#"bxav_]][[YYWWUUSSQQOOMMKgJedcFa`_X]@?Z=;;PU866KP3NM0K.IHGF?
(C&%:#8=~||387w5.u,sqqo-,l*#j!hffddbb``^^\\ZZXtWrqpiRQlOjiLJJ_dGFaDBBW\?==RW:UT7R5JO2M0K.,,A*?
DC%A:#8=~||3zxxvvttr0/o-&m$)jhh}fddbb``^^\\ZvYtsrUpiRQPejMhgJHHcb[`CB]\[=S<Q:8866442NML.D-B+))
''%%##!!};|98y6w43,1r/po&+*)i!h}fd"!~`v_t][wvXtmVkTRnmOkdMbKIedFb[DY^A??T=;;997755331M0KJI,GFE
>'&%:?"=<}{{8765.3ts0/o-&m$kiiggeec!~}_u^s\ZZXXVVTTRRPlOjiLgJedcb[`C^A\?ZYXWV88MRQ4I2M0/D-B+))
'CB$@9"7<}{{2yw54t2+r)pnnlljjhhffddb~a|{zs\[vYWWlqTRRglOjiLgJ_HGbE`_B@@[TY<;V977LQ422GL/JI,G*E
>C&%@#!!6;|zz16w43t1r/.'nm*k('hff#"!x}`_z][[puXVVkpSnmPkNihg`eHGbECCX]@>>SX;VU8S6QPONG0K.-BG*(
(=&;@#!!6;:9y1x/vttrrp.-m+$k"iggeeccaa__]][wZutslUToRmlOMMbgJIdGEEZ_B@@UZ=XW:U8MR54O200EJ-++@E
(CB%@#>7~;|9z76vv32+0q.on%l#jh&geez!~`|u^s\ZZXtsUqjShmPNNcLJfeGc\EZ_B@@U><<::8866442N1LKJ-HG@E
('B%##8=~||38y65v3t10/(on+l)(igg$#"!x}`_z][[puXVVkpSnmPkNihgf_dGbEDYBW\?==RWV8TM6K42NML.D-B+))
''%%##!!}}{{yyw5v321*qp-nll#(igg|ez!b}|_zs\[ZoXmVTponPfOdiLJJ_HFFD`CAAV[Z<XQ:O866442200..,,*F)
DC&A$9"!<}:9zxx5.3ts0qoo&+ljj!&g$#d!b}v{^y\[putVrqTiRPPNNLLJfeGc\EZ_B@@U><<::8866442N1LKJ-HG@)
D'&;@#!!6}49z765v321*/pon%l#j!hffd"caav{z\xqZoXVrqpRhQfOMihJf_H]bECCXA?[Z<XQ:OT755J311//--++))
(aBA@?>=<;:9876543210/.-,+*)54&%ed/.a=_^zy87YXts21}|nm,+j)hg&%qpbam_kj\[>=ed:U87_^PO2MLXJI,+SR
DP&AML>=}|Gz87wvA@21qp;n,+kj54&%e#/.>=_^zy[7YXts21}|nz,+wvhg&%q#baDCkj\[>=edVU87_^4\21YXJI,+F)
DC&%ML>JI|GF87wvAts1qp;:,+kj5h&%ed/.>=_^zy87YXts2q}|nm,+wvht&%qpbaDCkj\[>=edVU8S_^PO21YXJV,+SR
DC&%M#>=}|GF8DC5A@21qp;nm+kj54&%ed".>=_^zy8wv5ts21}|nm,kwvhg&%qpbaDCkj\[>YXdVU87_^PO2MYXJI,+SR
DC&%ML>=}|Gz87wvA@2>=p;:,+kj(43%$d/.>=_;]y[7YXts2~}o{m,+wv(t&rqpbaDCkj\[>=edVU8SR5PO21YXJV,+SR
DC&%ML>J}|GF87wvA@21qp;:,+7)54&%ed/.a=_^zy87YXts21}|nm,+j)hg&%qpbam_kj\[>=ed:U87_^PO2MLXJI,+SR
DP&AML>=}|Gz87wvA@21qp;n,+kj54&%e#/.>=_^zy[7YXts21}|nz,+wvhg&%q#baDCkj\?Z=<dVU87_Q]ON1YXJI,+SE
DC&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n9+kj54&fe#cb>=_^z98wYXW3r~0o{m,k*vhg&rqp"n`lB]i?Zfed:baSR54O[MLKW-HT*E
DPON$?K~<|G9yx6Bu3?1=/.-9l*6i43f10c!~`<;:9[Z6uW3r1}o{-lx*iut&%d#"nm_^A\hgf<Wc9TSR^4O21YKJV,GSR
DC&A$?K~}H{9Ex6vA@s1qp.:9+*j54&%e0/.>}_^zy87Y5t32~0o{-lkjih'fr$coaDCkj\[>fe;:ba`6Q]3NMYK.I,+SR
DP&AM?K~<H{F8x6Bu3?r0/.-9+kj5h3f$#"!~`<{]\8Z6uW3r~po{mlx*iu'feqpo!`lB]i?ZfXWc9T`65P\[1YX.V,GS)
('BN$?KJ}H:9Ex6B43?>0<o-9l*j5'g%ed".~=<^zy87YXtVr~}|nmykw)htsr$co!`CkA\[>=XdcUa`_^PO21Y/W-,+SR
(P&AM#>~<H{9EDwv4@21q<.:9+kj54&%ed".>=_^z9[w6X4s21p/nzykjvhgs%$ponDlB]i?ZYeWVU87R54\NM0XJIUGF)
DCO%ML"=IHGFE7wvAt?rqp.:,+k654gf$T/RQ
|
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 numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#J
|
J
|
R1000=. ;L:1 ,{ <@(<;._1);._2]0 :0
C CC CCC CD D DC DCC DCCC CM
X XX XXX XL L LX LXX LXXX XC
I II III IV V VI VII VIII IX
)
rfd=: ('M' $~ <.@%&1000) , R1000 {::~ 1000&|
|
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 decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#LiveScript
|
LiveScript
|
require! 'prelude-ls': {fold, sum}
# String → Number
decimal_of_roman = do
# [Number, Number] → String → [Number, Number]
_convert = ([acc, last_value], ch) ->
current_value = { M:1000 D:500 C:100 L:50 X:10 V:5 I:1 }[ch] ? 0
op = if last_value < current_value then (-) else (+)
[op(acc, last_value), current_value]
# fold the string and sum the resulting tuple (array)
fold(_convert, [0, 0]) >> sum
{[rom, decimal_of_roman rom] for rom in <[ MCMXC MMVII MDCLXVII MMMCLIX MCMLXXVII MMX ]>}
|
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:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#Sidef
|
Sidef
|
const rps = %w(r p s)
const msg = [
"Rock breaks scissors",
"Paper covers rock",
"Scissors cut paper",
]
say <<"EOT"
\n>> Rock Paper Scissors <<\n
** Enter 'r', 'p', or 's' as your play.
** Enter 'q' to exit the game.
** Running score shown as <your wins>:<my wins>
EOT
var plays = 0
var aScore = 0
var pScore = 0
var pcf = [0,0,0] # pcf = player choice frequency
var aChoice = pick(0..2) # ai choice for first play is completely random
loop {
var pi = Sys.scanln("Play: ")
pi == 'q' && break
var pChoice = rps.index(pi)
if (pChoice == -1) {
STDERR.print("Invalid input!\n")
next
}
++pcf[pChoice]
++plays
# show result of play
">> My play: %-8s".printf(rps[aChoice])
given ((aChoice - pChoice + 3) % 3) {
when (0) { say "Tie." }
when (1) { "%-*s %s".printlnf(30, msg[aChoice], 'My point'); aScore++ }
when (2) { "%-*s %s".printlnf(30, msg[pChoice], 'Your point'); pScore++ }
}
# show score
"%-6s".printf("%d:%d" % (pScore, aScore))
# compute ai choice for next play
given (plays.rand.int) { |rn|
case (rn < pcf[0]) { aChoice = 1 }
case (pcf[0]+pcf[1] > rn) { aChoice = 2 }
default { aChoice = 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 recently. You can find this out by searching the chat logs. The logs are publicly available at http://tclers.tk/conferences/tcl/. One log file corresponds to the messages from one day in Germany's current time zone. Each chat log file has the name YYYY-MM-DD.tcl where YYYY is the year, MM is the month and DD the day. The logs store one message per line. The messages themselves are human-readable and their internal structure doesn't matter.
Retrieve the chat logs from the last 10 days via HTTP. Find the lines that include a particular substring and print them in the following format:
<log file URL>
------
<matching line 1>
<matching line 2>
...
<matching line N>
------
The substring will be given to your program as a command line argument.
You need to account for the possible time zone difference between the client running your program and the chat log writer on the server to not miss any mentions. (For example, if you generated the log file URLs naively based on the local date, you could miss mentions if it was already April 5th for the logger but only April 4th for the client.) What this means in practice is that you should either generate the URLs in the time zone Europe/Berlin or, if your language can not do that, add an extra day (today + 1) to the range of dates you check, but then make sure to not print parts of a "not found" page by accident if a log file doesn't exist yet.
The code should be contained in a single-file script, with no "project" or "dependency" file (e.g., no requirements.txt for Python). It should only use a given programming language's standard library to accomplish this task and not rely on the user having installed any third-party packages.
If your language does not have an HTTP client in the standard library, you can speak raw HTTP 1.0 to the server. If it can't parse command line arguments in a standalone script, read the string to look for from the standard input.
|
#Nim
|
Nim
|
import httpclient, os, re, strformat, strutils, sugar, times
const Template = "'http://tclers.tk/conferences/tcl/'yyyy-MM-dd'.tcl'"
proc get(url: string): string =
var client = newHttpClient()
result = client.getContent(url)
if result.match(re"<!Doctype HTML[\s\S]*<Title>URL Not Found</Title>"):
result = ""
client.close()
let today = now()
const Back = 10
if paramCount() != 1:
quit "Wrong number of parameters", QuitFailure
let needle = paramStr(1)
for i in -Back..1:
let day = today + initTimeInterval(days = i)
let url = day.format(Template)
let haystack = url.get()
if haystack.len != 0:
let mentions = collect(newSeq):
for line in haystack.splitLines(keepEol = true):
if needle in line:
line
if mentions.len > 0:
echo &"{url}\n------\n{mentions.join()}------\n"
|
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 recently. You can find this out by searching the chat logs. The logs are publicly available at http://tclers.tk/conferences/tcl/. One log file corresponds to the messages from one day in Germany's current time zone. Each chat log file has the name YYYY-MM-DD.tcl where YYYY is the year, MM is the month and DD the day. The logs store one message per line. The messages themselves are human-readable and their internal structure doesn't matter.
Retrieve the chat logs from the last 10 days via HTTP. Find the lines that include a particular substring and print them in the following format:
<log file URL>
------
<matching line 1>
<matching line 2>
...
<matching line N>
------
The substring will be given to your program as a command line argument.
You need to account for the possible time zone difference between the client running your program and the chat log writer on the server to not miss any mentions. (For example, if you generated the log file URLs naively based on the local date, you could miss mentions if it was already April 5th for the logger but only April 4th for the client.) What this means in practice is that you should either generate the URLs in the time zone Europe/Berlin or, if your language can not do that, add an extra day (today + 1) to the range of dates you check, but then make sure to not print parts of a "not found" page by accident if a log file doesn't exist yet.
The code should be contained in a single-file script, with no "project" or "dependency" file (e.g., no requirements.txt for Python). It should only use a given programming language's standard library to accomplish this task and not rely on the user having installed any third-party packages.
If your language does not have an HTTP client in the standard library, you can speak raw HTTP 1.0 to the server. If it can't parse command line arguments in a standalone script, read the string to look for from the standard input.
|
#Perl
|
Perl
|
# 20210316 Perl programming solution
use strict;
use warnings;
use Time::Piece;
use IO::Socket::INET;
use HTTP::Tiny;
use feature 'say';
my $needle = shift @ARGV // '';
my @haystack = ();
my $page = '';
# 10 days before today
my $begin = Time::Piece->new - 10 * Time::Piece::ONE_DAY;
say " Executed at: ", Time::Piece->new;
say "Begin searching from: $begin";
for (my $date = $begin ; Time::Piece->new > $date ; $date += Time::Piece::ONE_DAY) {
$page .= HTTP::Tiny->new()->get( 'http://tclers.tk/conferences/tcl/'.$date->strftime('%Y-%m-%d').'.tcl')->{content};
}
# process pages
my @lines = split /\n/, $page;
for (@lines) { push @haystack, $_ if substr($_, 0, 13) =~ m/^m \d\d\d\d-\d\d-\d\dT/ }
# print the first and last line of the haystack
say "First and last lines of the haystack:";
say $haystack[0] and say $haystack[-1];
say "Needle: ", $needle;
say '-' x 79;
# find and print needle lines
for (@haystack) { say $_ if (index($_, $needle) != -1) }
|
http://rosettacode.org/wiki/Rhonda_numbers
|
Rhonda numbers
|
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.
25662 is a Rhonda number to base-10. The prime factorization is 2 × 3 × 7 × 13 × 47; the product of its base-10 digits is equal to the base times the sum of its prime factors:
2 × 5 × 6 × 6 × 2 = 720 = 10 × (2 + 3 + 7 + 13 + 47)
Rhonda numbers only exist in bases that are not a prime.
Rhonda numbers to base 10 always contain at least 1 digit 5 and always contain at least 1 even digit.
Task
For the non-prime bases b from 2 through 16 , find and display here, on this page, at least the first 10 Rhonda numbers to base b. Display the found numbers at least in base 10.
Stretch
Extend out to base 36.
See also
Wolfram Mathworld - Rhonda numbers
Numbers Aplenty - Rhonda numbers
OEIS:A100968 - Integers n that are Rhonda numbers to base 4
OEIS:A100969 - Integers n that are Rhonda numbers to base 6
OEIS:A100970 - Integers n that are Rhonda numbers to base 8
OEIS:A100973 - Integers n that are Rhonda numbers to base 9
OEIS:A099542 - Rhonda numbers to base 10
OEIS:A100971 - Integers n that are Rhonda numbers to base 12
OEIS:A100972 - Integers n that are Rhonda numbers to base 14
OEIS:A100974 - Integers n that are Rhonda numbers to base 15
OEIS:A100975 - Integers n that are Rhonda numbers to base 16
OEIS:A255735 - Integers n that are Rhonda numbers to base 18
OEIS:A255732 - Rhonda numbers in vigesimal number system (base 20)
OEIS:A255736 - Integers that are Rhonda numbers to base 30
Related Task: Smith numbers
|
#Rust
|
Rust
|
// [dependencies]
// radix_fmt = "1.0"
fn digit_product(base: u32, mut n: u32) -> u32 {
let mut product = 1;
while n != 0 {
product *= n % base;
n /= base;
}
product
}
fn prime_factor_sum(mut n: u32) -> u32 {
let mut sum = 0;
while (n & 1) == 0 {
sum += 2;
n >>= 1;
}
let mut p = 3;
while p * p <= n {
while n % p == 0 {
sum += p;
n /= p;
}
p += 2;
}
if n > 1 {
sum += n;
}
sum
}
fn is_prime(n: u32) -> bool {
if n < 2 {
return false;
}
if n % 2 == 0 {
return n == 2;
}
if n % 3 == 0 {
return n == 3;
}
let mut p = 5;
while p * p <= n {
if n % p == 0 {
return false;
}
p += 2;
if n % p == 0 {
return false;
}
p += 4;
}
true
}
fn is_rhonda(base: u32, n: u32) -> bool {
digit_product(base, n) == base * prime_factor_sum(n)
}
fn main() {
let limit = 15;
for base in 2..=36 {
if is_prime(base) {
continue;
}
println!("First {} Rhonda numbers to base {}:", limit, base);
let numbers: Vec<u32> = (1..).filter(|x| is_rhonda(base, *x)).take(limit).collect();
print!("In base 10:");
for n in &numbers {
print!(" {}", n);
}
print!("\nIn base {}:", base);
for n in &numbers {
print!(" {}", radix_fmt::radix(*n, base as u8));
}
print!("\n\n");
}
}
|
http://rosettacode.org/wiki/Rhonda_numbers
|
Rhonda numbers
|
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.
25662 is a Rhonda number to base-10. The prime factorization is 2 × 3 × 7 × 13 × 47; the product of its base-10 digits is equal to the base times the sum of its prime factors:
2 × 5 × 6 × 6 × 2 = 720 = 10 × (2 + 3 + 7 + 13 + 47)
Rhonda numbers only exist in bases that are not a prime.
Rhonda numbers to base 10 always contain at least 1 digit 5 and always contain at least 1 even digit.
Task
For the non-prime bases b from 2 through 16 , find and display here, on this page, at least the first 10 Rhonda numbers to base b. Display the found numbers at least in base 10.
Stretch
Extend out to base 36.
See also
Wolfram Mathworld - Rhonda numbers
Numbers Aplenty - Rhonda numbers
OEIS:A100968 - Integers n that are Rhonda numbers to base 4
OEIS:A100969 - Integers n that are Rhonda numbers to base 6
OEIS:A100970 - Integers n that are Rhonda numbers to base 8
OEIS:A100973 - Integers n that are Rhonda numbers to base 9
OEIS:A099542 - Rhonda numbers to base 10
OEIS:A100971 - Integers n that are Rhonda numbers to base 12
OEIS:A100972 - Integers n that are Rhonda numbers to base 14
OEIS:A100974 - Integers n that are Rhonda numbers to base 15
OEIS:A100975 - Integers n that are Rhonda numbers to base 16
OEIS:A255735 - Integers n that are Rhonda numbers to base 18
OEIS:A255732 - Rhonda numbers in vigesimal number system (base 20)
OEIS:A255736 - Integers that are Rhonda numbers to base 30
Related Task: Smith numbers
|
#Sidef
|
Sidef
|
func is_rhonda_number(n, base = 10) {
base.is_composite || return false
n > 0 || return false
n.digits(base).prod == base*n.factor.sum
}
for b in (2..16 -> grep { .is_composite }) {
say ("First 10 Rhonda numbers to base #{b}: ",
10.by { is_rhonda_number(_, b) })
}
|
http://rosettacode.org/wiki/Rhonda_numbers
|
Rhonda numbers
|
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.
25662 is a Rhonda number to base-10. The prime factorization is 2 × 3 × 7 × 13 × 47; the product of its base-10 digits is equal to the base times the sum of its prime factors:
2 × 5 × 6 × 6 × 2 = 720 = 10 × (2 + 3 + 7 + 13 + 47)
Rhonda numbers only exist in bases that are not a prime.
Rhonda numbers to base 10 always contain at least 1 digit 5 and always contain at least 1 even digit.
Task
For the non-prime bases b from 2 through 16 , find and display here, on this page, at least the first 10 Rhonda numbers to base b. Display the found numbers at least in base 10.
Stretch
Extend out to base 36.
See also
Wolfram Mathworld - Rhonda numbers
Numbers Aplenty - Rhonda numbers
OEIS:A100968 - Integers n that are Rhonda numbers to base 4
OEIS:A100969 - Integers n that are Rhonda numbers to base 6
OEIS:A100970 - Integers n that are Rhonda numbers to base 8
OEIS:A100973 - Integers n that are Rhonda numbers to base 9
OEIS:A099542 - Rhonda numbers to base 10
OEIS:A100971 - Integers n that are Rhonda numbers to base 12
OEIS:A100972 - Integers n that are Rhonda numbers to base 14
OEIS:A100974 - Integers n that are Rhonda numbers to base 15
OEIS:A100975 - Integers n that are Rhonda numbers to base 16
OEIS:A255735 - Integers n that are Rhonda numbers to base 18
OEIS:A255732 - Rhonda numbers in vigesimal number system (base 20)
OEIS:A255736 - Integers that are Rhonda numbers to base 30
Related Task: Smith numbers
|
#Swift
|
Swift
|
func digitProduct(base: Int, num: Int) -> Int {
var product = 1
var n = num
while n != 0 {
product *= n % base
n /= base
}
return product
}
func primeFactorSum(_ num: Int) -> Int {
var sum = 0
var n = num
while (n & 1) == 0 {
sum += 2
n >>= 1
}
var p = 3
while p * p <= n {
while n % p == 0 {
sum += p
n /= p
}
p += 2
}
if n > 1 {
sum += n
}
return sum
}
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
if n % 2 == 0 {
return n == 2
}
if n % 3 == 0 {
return n == 3
}
var p = 5
while p * p <= n {
if n % p == 0 {
return false
}
p += 2
if n % p == 0 {
return false
}
p += 4
}
return true
}
func isRhonda(base: Int, num: Int) -> Bool {
return digitProduct(base: base, num: num) == base * primeFactorSum(num)
}
let limit = 15
for base in 2...36 {
if isPrime(base) {
continue
}
print("First \(limit) Rhonda numbers to base \(base):")
let numbers = Array((1...).lazy.filter{ isRhonda(base: base, num: $0) }.prefix(limit))
print("In base 10:", terminator: "")
for n in numbers {
print(" \(n)", terminator: "")
}
print("\nIn base \(base):", terminator: "")
for n in numbers {
print(" \(String(n, radix: base))", terminator: "")
}
print("\n")
}
|
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.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#Quackery
|
Quackery
|
[ lookandsay ] is encode ( $ --> $ )
[ $ "" 0 rot
witheach
[ dup
char 0 char 9 1+
within iff
[ char 0 -
swap 10 * + ]
else
[ swap of join
0 ] ]
drop ] is decode ( $ --> $ )
$ "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
dup echo$ cr
encode
dup echo$ cr
decode
echo$ cr
|
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 input contained in each file listed on its command line, or (if no filenames are passed thereon) acting as a filter on its "standard input."
(A number of UNIX scripting languages and utilities, such as awk and sed either default to processing files in this way or have command line switches or modules to easily implement these wrapper semantics, e.g., Perl and Python).
The rot-13 encoding is commonly known from the early days of Usenet "Netnews" as a way of obfuscating text to prevent casual reading of spoiler or potentially offensive material.
Many news reader and mail user agent programs have built-in rot-13 encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions.
The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position (wrapping around from z to a as necessary).
Thus the letters abc become nop and so on.
Technically rot-13 is a "mono-alphabetic substitution cipher" with a trivial "key".
A proper implementation should work on upper and lower case letters, preserve case, and pass all non-alphabetic characters
in the input stream through without alteration.
Related tasks
Caesar cipher
Substitution Cipher
Vigenère Cipher/Cryptanalysis
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:-Encode( "The Quick Brown Fox Jumped Over The Lazy Dog!", encoding = rot13 );
"Gur Dhvpx Oebja Sbk Whzcrq Bire Gur Ynml Qbt!"
|
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 numerals:
1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
2008 is written as 2000=MM, 8=VIII; or MMVIII
1666 uses each Roman symbol in descending order: MDCLXVI
|
#Java
|
Java
|
public class RN {
enum Numeral {
I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000);
int weight;
Numeral(int weight) {
this.weight = weight;
}
};
public static String roman(long n) {
if( n <= 0) {
throw new IllegalArgumentException();
}
StringBuilder buf = new StringBuilder();
final Numeral[] values = Numeral.values();
for (int i = values.length - 1; i >= 0; i--) {
while (n >= values[i].weight) {
buf.append(values[i]);
n -= values[i].weight;
}
}
return buf.toString();
}
public static void test(long n) {
System.out.println(n + " = " + roman(n));
}
public static void main(String[] args) {
test(1999);
test(25);
test(944);
test(0);
}
}
|
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 decimal digit and skipping any 0s (zeroes).
1990 is rendered as MCMXC (1000 = M, 900 = CM, 90 = XC) and
2008 is rendered as MMVIII (2000 = MM, 8 = VIII).
The Roman numeral for 1666, MDCLXVI, uses each letter in descending order.
|
#Logo
|
Logo
|
; Roman numeral decoder
; First, some useful substring utilities
to starts_with? :string :prefix
if empty? :prefix [output "true]
if empty? :string [output "false]
if not equal? first :string first :prefix [output "false]
output starts_with? butfirst :string butfirst :prefix
end
to remove_prefix :string :prefix
if or empty? :prefix not starts_with? :string :prefix [output :string]
output remove_prefix butfirst :string butfirst :prefix
end
; Our list of Roman numeral values
make "values [[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]]
; Function to do the work
to from_roman :str
local "n make "n 0
foreach :values [
local "s make "s first ?
local "v make "v last ?
while [starts_with? :str :s] [
make "n sum n :v
make "str remove_prefix :str :s
]
]
output :n
end
foreach [MCMXC MDCLXVI MMVIII] [print (sentence (word ? "|: |) from_roman ?)]
bye
|
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:
Rock beats scissors
Scissors beat paper
Paper beats rock
If both players choose the same thing, there is no winner for that round.
For this task, the computer will be one of the players.
The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.
Extra credit
Support additional choices additional weapons.
|
#SuperCollider
|
SuperCollider
|
// play it in the REPL, evaluating line by line
a = RockPaperScissors.new;
a.next(Scissors);
a.next(Scissors);
a.next(Scissors);
a.next(Paper);
|
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 recently. You can find this out by searching the chat logs. The logs are publicly available at http://tclers.tk/conferences/tcl/. One log file corresponds to the messages from one day in Germany's current time zone. Each chat log file has the name YYYY-MM-DD.tcl where YYYY is the year, MM is the month and DD the day. The logs store one message per line. The messages themselves are human-readable and their internal structure doesn't matter.
Retrieve the chat logs from the last 10 days via HTTP. Find the lines that include a particular substring and print them in the following format:
<log file URL>
------
<matching line 1>
<matching line 2>
...
<matching line N>
------
The substring will be given to your program as a command line argument.
You need to account for the possible time zone difference between the client running your program and the chat log writer on the server to not miss any mentions. (For example, if you generated the log file URLs naively based on the local date, you could miss mentions if it was already April 5th for the logger but only April 4th for the client.) What this means in practice is that you should either generate the URLs in the time zone Europe/Berlin or, if your language can not do that, add an extra day (today + 1) to the range of dates you check, but then make sure to not print parts of a "not found" page by accident if a log file doesn't exist yet.
The code should be contained in a single-file script, with no "project" or "dependency" file (e.g., no requirements.txt for Python). It should only use a given programming language's standard library to accomplish this task and not rely on the user having installed any third-party packages.
If your language does not have an HTTP client in the standard library, you can speak raw HTTP 1.0 to the server. If it can't parse command line arguments in a standalone script, read the string to look for from the standard input.
|
#Phix
|
Phix
|
include builtins\libcurl.e
atom curl = NULL
function download(string url)
if curl=NULL then
curl_global_init()
curl = curl_easy_init()
end if
curl_easy_setopt(curl, CURLOPT_URL, url)
object res = curl_easy_perform_ex(curl)
if integer(res) then
printf(1,"libcurl error %d (%s)\n",{res,curl_easy_strerror(res)})
return ""
end if
return res
end function
function grep(string needle, haystack)
sequence lines = split(haystack,"\n"),
res = {}
for i=1 to length(lines) do
if match(needle,lines[i]) then
res = append(res,lines[i])
end if
end for
if res={} then res = {"no occurences"} end if
return res
end function
include builtins\timedate.e
function gen_url(integer i, string timezone)
timedate td = set_timezone(date(),timezone)
td = adjust_timedate(td,timedelta(days:=i))
return format_timedate(td,"'http://tclers.tk/conferences/tcl/'YYYY-MM-DD'.tcl'")
end function
sequence cl = command_line()
string needle = "github"
integer days = 10
if length(cl)>=3 then
needle := cl[3]
if length(cl)>=4 then
days := to_integer(cl[4])
if days=0 or length(cl)>=5 then ?9/0 end if
end if
end if
for i=-days to 0 do
string url := gen_url(i, "CEST"),
contents = download(url)
if contents="" then exit end if
?url
printf(1,"%s\n",join(grep(needle,contents),"\n"))
end for
|
http://rosettacode.org/wiki/Rhonda_numbers
|
Rhonda numbers
|
A positive integer n is said to be a Rhonda number to base b if the product of the base b digits of n is equal to b times the sum of n's prime factors.
These numbers were named by Kevin Brown after an acquaintance of his whose residence number was 25662, a member of the base 10 numbers with this property.
25662 is a Rhonda number to base-10. The prime factorization is 2 × 3 × 7 × 13 × 47; the product of its base-10 digits is equal to the base times the sum of its prime factors:
2 × 5 × 6 × 6 × 2 = 720 = 10 × (2 + 3 + 7 + 13 + 47)
Rhonda numbers only exist in bases that are not a prime.
Rhonda numbers to base 10 always contain at least 1 digit 5 and always contain at least 1 even digit.
Task
For the non-prime bases b from 2 through 16 , find and display here, on this page, at least the first 10 Rhonda numbers to base b. Display the found numbers at least in base 10.
Stretch
Extend out to base 36.
See also
Wolfram Mathworld - Rhonda numbers
Numbers Aplenty - Rhonda numbers
OEIS:A100968 - Integers n that are Rhonda numbers to base 4
OEIS:A100969 - Integers n that are Rhonda numbers to base 6
OEIS:A100970 - Integers n that are Rhonda numbers to base 8
OEIS:A100973 - Integers n that are Rhonda numbers to base 9
OEIS:A099542 - Rhonda numbers to base 10
OEIS:A100971 - Integers n that are Rhonda numbers to base 12
OEIS:A100972 - Integers n that are Rhonda numbers to base 14
OEIS:A100974 - Integers n that are Rhonda numbers to base 15
OEIS:A100975 - Integers n that are Rhonda numbers to base 16
OEIS:A255735 - Integers n that are Rhonda numbers to base 18
OEIS:A255732 - Rhonda numbers in vigesimal number system (base 20)
OEIS:A255736 - Integers that are Rhonda numbers to base 30
Related Task: Smith numbers
|
#Wren
|
Wren
|
import "./math" for Math, Int, Nums
import "./fmt" for Fmt, Conv
for (b in 2..36) {
if (Int.isPrime(b)) continue
var count = 0
var rhonda = []
var n = 1
while (count < 15) {
var digits = Int.digits(n, b)
if (!digits.contains(0)) {
if (b != 10 || (digits.contains(5) && digits.any { |d| d % 2 == 0 })) {
var calc1 = Nums.prod(digits)
var calc2 = b * Nums.sum(Int.primeFactors(n))
if (calc1 == calc2) {
rhonda.add(n)
count = count + 1
}
}
}
n = n + 1
}
if (rhonda.count > 0) {
System.print("\nFirst 15 Rhonda numbers in base %(b):")
var rhonda2 = rhonda.map { |r| r.toString }.toList
var rhonda3 = rhonda.map { |r| Conv.Itoa(r, b) }.toList
var maxLen2 = Nums.max(rhonda2.map { |r| r.count })
var maxLen3 = Nums.max(rhonda3.map { |r| r.count })
var maxLen = Math.max(maxLen2, maxLen3) + 1
Fmt.print("In base 10: $*s", maxLen, rhonda2)
Fmt.print("In base $-2d: $*s", b, maxLen, rhonda3)
}
}
|
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.
The output can be anything, as long as you can recreate the input with it.
Example
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Output: 12W1B12W3B24W1B14W
Note: the encoding step in the above example is the same as a step of the Look-and-say sequence.
|
#R
|
R
|
runlengthencoding <- function(x)
{
splitx <- unlist(strsplit(input, ""))
rlex <- rle(splitx)
paste(with(rlex, as.vector(rbind(lengths, values))), collapse="")
}
input <- "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
runlengthencoding(input)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.