task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Rot-13
|
Rot-13
|
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of 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
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
Rot13[s_] := StringReplace[
s,
# -> RotateLeft[#, 13] & @* CharacterRange @@ # &[
{"a", "z"}, {"A", "Z"}
] // Thread
]
Rot13["Hello World!"]
Rot13[%]
|
http://rosettacode.org/wiki/Roman_numerals/Encode
|
Roman numerals/Encode
|
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman 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
|
#JavaScript
|
JavaScript
|
var roman = {
map: [
1000, 'M', 900, 'CM', 500, 'D', 400, 'CD', 100, 'C', 90, 'XC',
50, 'L', 40, 'XL', 10, 'X', 9, 'IX', 5, 'V', 4, 'IV', 1, 'I',
],
int_to_roman: function(n) {
var value = '';
for (var idx = 0; n > 0 && idx < this.map.length; idx += 2) {
while (n >= this.map[idx]) {
value += this.map[idx + 1];
n -= this.map[idx];
}
}
return value;
}
}
roman.int_to_roman(1999); // "MCMXCIX"
|
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.
|
#Lua
|
Lua
|
function ToNumeral( roman )
local Num = { ["M"] = 1000, ["D"] = 500, ["C"] = 100, ["L"] = 50, ["X"] = 10, ["V"] = 5, ["I"] = 1 }
local numeral = 0
local i = 1
local strlen = string.len(roman)
while i < strlen do
local z1, z2 = Num[ string.sub(roman,i,i) ], Num[ string.sub(roman,i+1,i+1) ]
if z1 < z2 then
numeral = numeral + ( z2 - z1 )
i = i + 2
else
numeral = numeral + z1
i = i + 1
end
end
if i <= strlen then numeral = numeral + Num[ string.sub(roman,i,i) ] end
return numeral
end
print( ToNumeral( "MCMXC" ) )
print( ToNumeral( "MMVIII" ) )
print( ToNumeral( "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.
|
#Swift
|
Swift
|
enum Choice: CaseIterable {
case rock
case paper
case scissors
case lizard
case spock
}
extension Choice {
var weaknesses: Set<Choice> {
switch self {
case .rock:
return [.paper, .spock]
case .paper:
return [.scissors, .lizard]
case .scissors:
return [.rock, .spock]
case .lizard:
return [.rock, .scissors]
case .spock:
return [.paper, .lizard]
}
}
}
struct Game {
private(set) var history: [(Choice, Choice)] = []
private(set) var p1Score: Int = 0
private(set) var p2Score: Int = 0
mutating func play(_ p1Choice: Choice, against p2Choice: Choice) {
history.append((p1Choice, p2Choice))
if p2Choice.weaknesses.contains(p1Choice) {
p1Score += 1
} else if p1Choice.weaknesses.contains(p2Choice) {
p2Score += 1
}
}
}
func aiChoice(for game: Game) -> Choice {
if let weightedWeekness = game.history.flatMap({ $0.0.weaknesses }).randomElement() {
return weightedWeekness
} else {
// If history is empty, return random Choice
return Choice.allCases.randomElement()!
}
}
var game = Game()
print("Type your choice to play a round, or 'q' to quit")
loop: while true {
let choice: Choice
switch readLine().map({ $0.lowercased() }) {
case "r", "rock":
choice = .rock
case "p", "paper":
choice = .paper
case "scissors":
choice = .scissors
case "l", "lizard":
choice = .lizard
case "spock":
choice = .spock
case "q", "quit", "exit":
break loop
case "s":
print("Do you mean Spock, or scissors?")
continue
default:
print("Unknown choice. Type 'q' to quit")
continue
}
let p2Choice = aiChoice(for: game)
print("You played \(choice) against \(p2Choice)")
game.play(choice, against: p2Choice)
print("Current score: \(game.p1Score) : \(game.p2Score)")
}
|
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.
|
#Tcl
|
Tcl
|
package require Tcl 8.5
### Choices are represented by integers, which are indices into this list:
### Rock, Paper, Scissors
### Normally, idiomatic Tcl code uses names for these sorts of things, but it
### turns out that using integers simplifies the move-comparison logic.
# How to ask for a move from the human player
proc getHumanMove {} {
while 1 {
puts -nonewline "Your move? \[R\]ock, \[P\]aper, \[S\]cissors: "
flush stdout
gets stdin line
if {[eof stdin]} {
puts "\nBye!"
exit
}
set len [string length $line]
foreach play {0 1 2} name {"rock" "paper" "scissors"} {
# Do a prefix comparison
if {$len && [string equal -nocase -length $len $line $name]} {
return $play
}
}
puts "Sorry, I don't understand that. Try again please."
}
}
# How to ask for a move from the machine player
proc getMachineMove {} {
global states
set choice [expr {int(rand() * [::tcl::mathop::+ {*}$states 3])}]
foreach play {1 2 0} count $states {
if {[incr sum [expr {$count+1}]] > $choice} {
puts "I play \"[lindex {Rock Paper Scissors} $play]\""
return $play
}
}
}
# Initialize some state variables
set states {0 0 0}
set humanWins 0
set machineWins 0
# The main game loop
while 1 {
# Get the moves for this round
set machineMove [getMachineMove]
set humanMove [getHumanMove]
# Report on what happened
if {$humanMove == $machineMove} {
puts "A draw!"
} elseif {($humanMove+1)%3 == $machineMove} {
puts "I win!"
incr machineWins
} else {
puts "You win!"
incr humanWins
}
puts "Cumulative scores: $humanWins to you, $machineWins to me"
# Update the state of how the human has played in the past
lset states $humanMove [expr {[lindex $states $humanMove] + 1}]
}
|
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.
|
#Python
|
Python
|
#! /usr/bin/env python3
import datetime
import re
import urllib.request
import sys
def get(url):
with urllib.request.urlopen(url) as response:
html = response.read().decode('utf-8')
if re.match(r'<!Doctype HTML[\s\S]*<Title>URL Not Found</Title>', html):
return None
return html
def main():
template = 'http://tclers.tk/conferences/tcl/%Y-%m-%d.tcl'
today = datetime.datetime.utcnow()
back = 10
needle = sys.argv[1]
# Since Python does not come standard with time zone definitions, add an
# extra day to account for the possible difference between the local and the
# server time.
for i in range(-back, 2):
day = today + datetime.timedelta(days=i)
url = day.strftime(template)
haystack = get(url)
if haystack:
mentions = [x for x in haystack.split('\n') if needle in x]
if mentions:
print('{}\n------\n{}\n------\n'
.format(url, '\n'.join(mentions)))
main()
|
http://rosettacode.org/wiki/Run-length_encoding
|
Run-length encoding
|
Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression.
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.
|
#Racket
|
Racket
|
#lang racket
(define (encode str)
(regexp-replace* #px"(.)\\1*" str (λ (m c) (~a (string-length m) c))))
(define (decode str)
(regexp-replace* #px"([0-9]+)(.)" str (λ (m n c) (make-string (string->number n) (string-ref c 0)))))
|
http://rosettacode.org/wiki/Rot-13
|
Rot-13
|
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of 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
|
#MATLAB
|
MATLAB
|
function r=rot13(s)
if ischar(s)
r=s; % preallocation and copy of non-letters
for i=1:size(s,1)
for j=1:size(s,2)
if isletter(s(i,j))
if s(i,j)>=97 % lower case
base = 97;
else % upper case
base = 65;
end
r(i,j)=char(mod(s(i,j)-base+13,26)+base);
end
end
end
else
error('Argument must be a CHAR')
end
end
|
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
|
#jq
|
jq
|
def to_roman_numeral:
def romans:
[100000, "\u2188"],
[90000, "ↂ\u2188"],
[50000, "\u2187"],
[40000, "ↂ\u2187"],
[10000, "ↂ"],
[9000, "Mↂ"],
[5000, "ↁ"],
[4000, "Mↁ"],
[1000, "M"],
[900, "CM"],
[500, "D"],
[400, "CD"],
[100, "C"],
[90, "XC"],
[50, "L"],
[40, "XL"],
[10, "X"],
[9, "IX"],
[5, "V"],
[4, "IV"],
[1, "I"] ;
if . < 1 or . > 399999
then "to_roman_numeral: \(.) is out of range" | error
else reduce romans as [$i, $r] ({n: .};
until (.n < $i;
.res += $r
| .n = .n - $i ) )
| .res
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.
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module RomanNumbers {
flush ' empty current stack
gosub Initialize
document Doc$
while not empty
read rom$
print rom$;"=";RomanEval$(rom$)
Doc$=rom$+"="+RomanEval$(rom$)+{
}
end while
Clipboard Doc$
end
Initialize:
function RomanEval$(rom$) {
Flush
="invalid"
if filter$(rom$,"MDCLXVI")<>"" Then Exit
\\ "Y" is in top of stack
Push "CM", "MD", "Q"
Push "CD", "MD","W"
Push "XC", "DL", "E"
Push "XL", "X","R"
Push "IX","V","T"
Push "IV","I","Y"
\\ stack flush to doublerom
doublerom=[]
\\ "M" is in top of stack
Data "M", 1000, "Q",900
Data "D", 500,"W", 400
Data "C",100,"E",90
Data "L",50,"R", 40
Data "X", 10, "T", 9
Data "V", 5, "Y", 4, "I",1
\\ stack flush to singlerom
singlerom=[]
acc=0
value=0
count=0
stack doublerom {
if empty then exit
read rep$,exclude$,cc$
i=instr(rom$,cc$)
if i >0 then
tmp$=mid$(rom$,i+2)
L=Len(tmp$)
if L>0 then if Len(filter$(tmp$, exclude$))<>L then rom$="A": exit
if Instr(rom$,mid$(rom$,i,1))<i then rom$="A": exit
insert i,2 rom$=rep$ ' replace at pos i with rep$ and place a space to i+1
end if
loop
}
rom$=filter$(rom$," ") ' remove spaces if exist
stack singlerom {
if empty then exit
read cc$, value
count=0
while left$(rom$,1)=cc$
insert 1, 1 rom$=""
count++
acc+=value
end while
if count>3 then exit
loop
}
if len(rom$)>0 or count>3 Else
=Str$(acc,1033)
end if
}
data "MMMCMXCIX", "LXXIIX", "MMXVII", "LXXIX", "CXCIX","MCMXCIX","MMMDCCCLXXXVIII"
data "CMXI","M","MCDXLIV","CCCC","IXV", "XLIXL","LXXIIX","IVM"
data "XXXIX", "XXXX", "XIXX","IVI", "XLIX","XCIX","XCIV","XLVIII"
return
}
RomanNumbers
|
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.
|
#TI-83_BASIC
|
TI-83 BASIC
|
PROGRAM:RPS
:{0,0,0}→L1
:{0,0,0}→L2
:Lbl ST
:Disp "R/P/S"
:Disp "1/2/3"
:Lbl EC
:Input A
:If A>3 or A<1
:Then
:Goto NO
:End
:randInt(1,3+L1(1)+L1(2)+L1(3)→C
:If C≤1+L1(1)
:Then
:2→B
:Goto NS
:End
:If C>2+L1(2)
:Then
:1→B
:Else
:3→B
:End
:Lbl NS
:L1(A)+1→L1(A)
:If A=B
:Then
:Disp "TIE GAME"
:L2(3)+1→L2(3)
:Goto TG
:End
:If (A=1 and B=2) or (A=2 and B=3) or (A=3 and B=1)
:Then
:Disp "I WIN"
:L2(1)+1→L2(1)
:Else
:Disp "YOU WIN"
:L2(2)+1→L2(2)
:End
:Lbl TG
:Disp "PLAY AGAIN?"
:Input Str1
:If Str1="YES"
:Then
:ClrHome
:Goto ST
:Else
:Goto EN
:End
:Lbl NO
:ClrHome
:Pause "PICK 1,2, or 3"
:ClrHome
:Goto EC
:Lbl EN
:ClrHome
:Disp "I WON:"
:Disp L2(1)
:Disp "YOU WON:"
:Disp L2(2)
:Disp "WE TIED:"
:Disp L2(3)
:Disp "BYE"
|
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.
|
#Racket
|
Racket
|
#lang racket
(require net/url)
(require racket/date)
;; generate archive url from specified number of days in the past
(define (generate-url days-ago)
(putenv "TZ" "Europe/Berlin") ; this works for Linux
(let* [(today (current-date))
(past (seconds->date (- (date->seconds today) (* days-ago 60 60 24))))
(date-str (string-append
(~r (date-year past) #:min-width 4 #:pad-string "0") ; 4 digit year
"-"
(~r (date-month past) #:min-width 2 #:pad-string "0") ; 2 digit month
"-"
(~r (date-day past) #:min-width 2 #:pad-string "0"))) ; 2 digit day
(url (string-append "http://tclers.tk/conferences/tcl/" date-str ".tcl"))]
url))
;; retrieve content of url as a list of strings
(define (get-content-of-url url-string)
(let [(st (open-output-string))]
(copy-port (get-pure-port (string->url url-string)
#:redirections 100)
st)
(string-split (get-output-string st) "\n"))) ; divide on line breaks
;; from a list of strings, return a list of those containing the search string
(define (get-matches lines search-string)
(define (internal-get-matches lines search-string results)
(cond
((empty? lines) results)
(else (internal-get-matches (cdr lines)
search-string
(if (string-contains? (car lines) search-string)
(append results (list (car lines)))
results)))))
(internal-get-matches lines search-string (list)))
;; display last 10 days worth of archives that contain matches to the search string
(define (display-matches-for-last-10-days search-string)
;; get archives from 9 days ago until today
(for/list ([i (range 9 -1 -1)])
(let* ([url (generate-url i)]
[matches (get-matches (get-content-of-url url) search-string)])
(cond [(not (empty? matches))
(begin
(display url)(newline)
(display "------\n")
(for/list ([line matches]) (display line)(newline))
(display "------\n"))]))))
;; use the first command line argument as the search string
;; display usage info if no search string is provided
(cond ((= 0 (vector-length (current-command-line-arguments))) (display "USAGE: chat_history <search term>\n"))
(else (display-matches-for-last-10-days (vector-ref (current-command-line-arguments) 0))))
|
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.
|
#Raku
|
Raku
|
sub encode($str) { $str.subst(/(.) $0*/, { $/.chars ~ $0 }, :g) }
sub decode($str) { $str.subst(/(\d+) (.)/, { $1 x $0 }, :g) }
my $e = encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW');
say $e;
say decode($e);
|
http://rosettacode.org/wiki/RIPEMD-160
|
RIPEMD-160
|
RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code”.
You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
|
#Ada
|
Ada
|
with Ada.Text_IO;
with CryptAda.Pragmatics;
with CryptAda.Digests.Message_Digests.RIPEMD_160;
with CryptAda.Digests.Hashes;
with CryptAda.Utils.Format;
procedure RC_RIPEMD_160 is
use CryptAda.Pragmatics;
use CryptAda.Digests.Message_Digests;
use CryptAda.Digests;
function To_Byte_Array (Item : String) return Byte_Array is
Result : Byte_Array (Item'Range);
begin
for I in Result'Range loop
Result (I) := Byte (Character'Pos (Item (I)));
end loop;
return Result;
end To_Byte_Array;
Text : constant String := "Rosetta Code";
Bytes : constant Byte_Array := To_Byte_Array (Text);
Handle : constant Message_Digest_Handle := RIPEMD_160.Get_Message_Digest_Handle;
Pointer : constant Message_Digest_Ptr := Get_Message_Digest_Ptr (Handle);
Hash : Hashes.Hash;
begin
Digest_Start (Pointer);
Digest_Update (Pointer, Bytes);
Digest_End (Pointer, Hash);
Ada.Text_IO.Put_Line
("""" & Text & """: " & CryptAda.Utils.Format.To_Hex_String (Hashes.Get_Bytes (Hash)));
end RC_RIPEMD_160;
|
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
|
Respond to an unknown method call
|
Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#AutoHotkey
|
AutoHotkey
|
class example
{
foo()
{
Msgbox Called example.foo()
}
__Call(method, params*)
{
funcRef := Func(funcName := this.__class "." method)
if !IsObject(funcRef)
{
str := "Called undefined method " funcName "() with these parameters:"
for k,v in params
str .= "`n" v
Msgbox %str%
}
else
{
return funcRef.(this, params*)
}
}
}
ex := new example
ex.foo()
ex.bar(1,2)
|
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
|
#Maxima
|
Maxima
|
rot13(a) := simplode(map(ascii, map(lambda([n],
if (n >= 65 and n <= 77) or (n >= 97 and n <= 109) then n + 13
elseif (n >= 78 and n <= 90) or (n >= 110 and n <= 122) then n - 13
else n), map(cint, sexplode(a)))))$
lowercase: "abcdefghijklmnopqrstuvwxyz"$
uppercase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"$
rot13(lowercase);
"nopqrstuvwxyzabcdefghijklm"
rot13(uppercase);
"NOPQRSTUVWXYZABCDEFGHIJKLM"
rot13("The quick brown fox jumps over the lazy dog");
"Gur dhvpx oebja sbk whzcf bire gur ynml qbt"
rot13(%);
"The quick brown fox jumps over the lazy dog"
|
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
|
#Jsish
|
Jsish
|
/* Roman numerals, in Jsish */
var Roman = {
ord: ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'],
val: [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
fromRoman: function(roman:string):number {
var n = 0;
var re = /IV|IX|I|V|XC|XL|X|L|CD|CM|C|D|M/g;
var matches = roman.match(re);
if (!matches) return NaN;
for (var hit of matches) n += this.val[this.ord.indexOf(hit)];
return n;
},
toRoman: function(n:number):string {
var roman = '';
var idx = 0;
while (n > 0) {
while (n >= this.val[idx]) {
roman += this.ord[idx];
n -= this.val[idx];
}
idx++;
}
return roman;
}
};
provide('Roman', 1);
if (Interp.conf('unitTest')) {
; Roman.fromRoman('VIII');
; Roman.fromRoman('MMMDIV');
; Roman.fromRoman('CDIV');
; Roman.fromRoman('MDCLXVI');
; Roman.fromRoman('not');
; Roman.toRoman(8);
; Roman.toRoman(3504);
; Roman.toRoman(404);
; Roman.toRoman(1666);
}
/*
=!EXPECTSTART!=
Roman.fromRoman('VIII') ==> 8
Roman.fromRoman('MMMDIV') ==> 3504
Roman.fromRoman('CDIV') ==> 404
Roman.fromRoman('MDCLXVI') ==> 1666
Roman.fromRoman('not') ==> NaN
Roman.toRoman(8) ==> VIII
Roman.toRoman(3504) ==> MMMDIV
Roman.toRoman(404) ==> CDIV
Roman.toRoman(1666) ==> MDCLXVI
=!EXPECTEND!=
*/
|
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.
|
#Maple
|
Maple
|
f := n -> convert(n, arabic):
seq(printf("%a\n", f(i)), i in [MCMXC, MMVIII, MDCLXVI]);
|
http://rosettacode.org/wiki/Rock-paper-scissors
|
Rock-paper-scissors
|
Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
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.
|
#TorqueScript
|
TorqueScript
|
while(isobject(RockPaperScissors))
RockPaperScissors.delete();
new scriptObject(RockPaperScissors);
function RockPaperScissors::startGame(%this)
{
%this.idle = true;
echo("Starting rock paper scissors, please type choose(\"choice\"); to proceed!");
}
function RockPaperScissors::endGame(%this)
{
%this.idle = true;
}
function RockPaperScissors::main(%this)
{
%this.idle = 0;
if(getRandom(1,2) == 1)
{
%result = %this.getChoiceByUserFrequency();
}
else
{
%c[0] = "rock";
%c[1] = "paper";
%c[2] = "scissors";
%result = %c[getRandom(0,2)];
}
%userChoice = %this.current;
%winner = thisVSthat(%userChoice,%result);
if(%winner == 0)
{
echo("You both chose "@%userChoice@", tie!");
}
else
if(%winner == 1)
{
echo("You chose "@%userChoice@" computer chose "@%result@", you win!");
}
else
if(%winner == 2)
{
echo("You chose "@%userChoice@" computer chose "@%result@", you lose!");
}
%this.idle = true;
}
function RockPaperScissors::getChoiceByUserFrequency(%this)
{
%weakness["rock"] = "paper";
%weakness["paper"] = "Scissors";
%weakness["scissors"] = "rock";
%a[0] = %this.choice["rock"];
%a[1] = %this.choice["paper"];
%a[2] = %this.choice["Scissors"];
%b[0] = "rock";
%b[1] = "paper";
%b[2] = "scissors";
for(%i=0;%i<3;%i++)
{
%curr = %a[%i];
if(%temp $= "")
{
%temp = %curr;
%tempi = %i;
}
else
if(%curr > %temp)
{
%temp = %curr;
%tempi = %i;
}
}
return %weakness[%b[%tempi]];
}
function choose(%this)
{
%rps = rockPaperScissors;
if(!%rps.idle)
{
return 0;
}
else
if(%this !$= "rock" && %this !$= "paper" && %this !$= "scissors")
{
return 0;
}
%rps.choice[%this]++;
%rps.current = %this;
%rps.main();
return %this;
}
function thisVSthat(%this,%that)
{
if(%this !$= "rock" && %this !$= "paper" && %this !$= "scissors")
{
return 0;
}
else
if(%that !$= "rock" && %that !$= "paper" && %that !$= "scissors")
{
return 0;
}
%weakness["rock"] = "paper";
%weakness["paper"] = "Scissors";
%weakness["scissors"] = "rock";
if(%weakness[%this] $= %that)
{
%result = 2;
}
else
if(%weakness[%that] $= %this)
{
%result = 1;
}
else
%result = 0;
return %result;
}
|
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.
|
#Raku
|
Raku
|
my $needle = @*ARGS.shift // '';
my @haystack;
# 10 days before today, Zulu time
my $begin = DateTime.new(time).utc.earlier(:10days);
say " Executed at: ", DateTime.new(time).utc;
say "Begin searching from: $begin";
# Today - 10 days through today
for $begin.Date .. DateTime.now.utc.Date -> $date {
# connect to server, use a raw socket
my $http = IO::Socket::INET.new(:host('tclers.tk'), :port(80));
# request file
$http.print: "GET /conferences/tcl/{$date}.tcl HTTP/1.0\n\n";
# retrieve file
my @page = $http.lines;
# remove header
@page.splice(0, 8);
# concatenate multi-line entries to a single line
while @page {
if @page[0].substr(0, 13) ~~ m/^'m '\d\d\d\d'-'\d\d'-'\d\d'T'/ {
@haystack.push: @page.shift;
}
else {
@haystack.tail ~= '' ~ @page.shift;
}
}
# close socket
$http.close;
}
# ignore times before 10 days ago
@haystack.shift while @haystack[0].substr(2, 22) lt $begin.Str;
# print the first and last line of the haystack
say "First and last lines of the haystack:";
.say for |@haystack[0, *-1];
say "Needle: ", $needle;
say '-' x 79;
# find and print needle lines
.say if .contains( $needle ) for @haystack;
|
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.
|
#REXX
|
REXX
|
/*REXX program encodes and displays a string by using a run─length encoding scheme. */
parse arg input . /*normally, input would be in a file. */
default= 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'
if input=='' | input=="," then input= default /*Not specified? Then use the default.*/
encode= RLE(input) ; say ' input=' input /*encode input string; display input. */
say 'encoded=' encode /* display run─len*/
decode= RLD(encode); say 'decoded=' decode /*decode the run─len; display decode.*/
if decode==input then say 'OK'; else say "¬ OK" /*display yay or nay (success/failure).*/
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say; say "***error*** input data isn't alphabetic:" c; say; exit 13
/*──────────────────────────────────────────────────────────────────────────────────────*/
RLE: procedure; parse arg x; $= /*$: is the output string (so far). */
Lx= length(x) /*get length of the plain text string. */
do j=1 by 0 to Lx; c= substr(x, j, 1) /*obtain a character from plain text. */
if \datatype(c, 'M') then call err /*Character not a letter? Issue error.*/
r= 0 /*R: is NOT the number of characters. */
do k=j+1 to Lx while substr(x, k, 1)==c /*while characters ≡ C */
r= r + 1 /*bump the replication count for a char*/
end /*k*/
j= j + r + 1 /*increment (add to) the DO loop index.*/
if r==0 then $= $ || c /*don't use R if it is equal to zero.*/
else $= $ || r || c /*add character to the encoded string. */
end /*j*/; return $ /*return the encoded string to caller. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
RLD: procedure; parse arg x; $= /*$: is the output string (so far). */
Lx= length(x) /*get the length of the encoded string.*/
do j=1 by 0 to Lx; c= substr(x, j, 1) /*obtain a character from run encoding.*/
if \datatype(c, 'W') then do; $= $ || c; j= j + 1; iterate /*j*/
end /* [↑] a loner char, add it to output.*/
#= 1 /* [↓] W: use a Whole number*/
do k=j+1 to Lx while datatype(substr(x,k,1), 'w') /*while numeric*/
#= # + 1 /*bump the count of the numeric chars. */
end /*k*/
n= substr(x, j, #) + 1 /*#: the length of encoded character. */
$= $ || copies( substr(x, k, 1), n) /*N: is now the number of characters. */
j= j + # + 1 /*increment the DO loop index by D+1. */
end /*j*/; return $ /*return the decoded string to caller. */
|
http://rosettacode.org/wiki/RIPEMD-160
|
RIPEMD-160
|
RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code”.
You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
|
#C
|
C
|
#ifndef RMDsize
#define RMDsize 160
#endif
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#if RMDsize == 128
#include "rmd128.h"
#include "rmd128.c" /* Added to remove errors during compilation */
#elif RMDsize == 160
#include "rmd160.h"
#include "rmd160.c" /* Added to remove errors during compilation */
#endif
|
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
|
Respond to an unknown method call
|
Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#Brat
|
Brat
|
example = object.new
example.no_method = { meth_name, *args |
p "#{meth_name} was called with these arguments: #{args}"
}
example.this_does_not_exist "at all" #Prints "this_does_not_exist was called with these arguments: [at all]"
|
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
|
Respond to an unknown method call
|
Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#C.23
|
C#
|
using System;
using System.Dynamic;
class Example : DynamicObject
{
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
result = null;
Console.WriteLine("This is {0}.", binder.Name);
return true;
}
}
class Program
{
static void Main(string[] args)
{
dynamic ex = new Example();
ex.Foo();
ex.Bar();
}
}
|
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
|
#Mercury
|
Mercury
|
:- module rot13.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module string, set, list, char, int.
:- type transition == {character, character}.
:- type transitions == set(transition).
:- type rot_kind
---> encrypt
; decrypt.
:- pred build_transition(int::in, rot_kind::in, int::in, int::in, character::in,
transitions::in, transitions::out) is det.
build_transition(Offset, Kd, Lb, Ub, Ch, St, Rs) :-
(
Kd = encrypt,
Diff = to_int(Ch) + Offset
;
Kd = decrypt,
Diff = to_int(Ch) - Offset
),
(if (Diff >= (Ub + 0x01))
then Ct = {Ch, det_from_int(Lb + (Diff - Ub) - 0x01) `with_type` char}
else if (Diff =< (Lb - 0x01))
then Ct = {Ch, det_from_int(Ub - (Lb - Diff) + 0x01) `with_type` char}
else Ct = {Ch, det_from_int(Diff) `with_type` char}),
union(St, make_singleton_set(Ct), Rs).
:- pred generate_alpha_transition(int::in, rot_kind::in, transitions::out) is det.
generate_alpha_transition(N, Kd, Ts) :-
Offset = N mod 0x1A,
to_char_list("abcdefghijklmnopqrstuvwxyz", Lower),
to_char_list("ABCDEFGHIJKLMNOPQRSTUVWXYZ", Upper),
foldl(build_transition(Offset, Kd, 0x61, 0x7A), Lower, init, Ts0),
foldl(build_transition(Offset, Kd, 0x41, 0x5A), Upper, Ts0, Ts).
:- pred rot(transitions::in, string::in, string::out) is det.
rot(Ts, Base, Result) :-
to_char_list(Base, Fragment),
map((pred(Ch::in, Rs::out) is det :-
promise_equivalent_solutions [Rs]
(if member({Ch, Nx}, Ts)
then Rs = Nx
else Rs = Ch)
), Fragment, Result0),
from_char_list(Result0, Result).
:- pred invoke_line(transitions::in, string::in, text_input_stream::in, io::di, io::uo) is det.
invoke_line(Ts, File, Stream, !IO) :-
read_line_as_string(Stream, Line, !IO),
(
Line = ok(Base),
rot(Ts, Base, Rot),
write_string(Rot, !IO),
invoke_line(Ts, File, Stream, !IO)
;
Line = error(_),
format("Can't read correctly the file %s.\n", [s(File)], !IO)
;
Line = eof
).
:- pred handle_files(transitions::in, list(string)::in, io::di, io::uo) is det.
handle_files(_, [], !IO).
handle_files(Ts, [Head|Tail], !IO) :-
open_input(Head, Result, !IO),
(
Result = ok(Stream),
invoke_line(Ts, Head, Stream, !IO),
close_input(Stream, !IO)
;
Result = error(_),
format("Can't open the file %s.\n", [s(Head)], !IO)
),
handle_files(Ts, Tail, !IO).
main(!IO) :-
generate_alpha_transition(0x0D, encrypt, Table),
command_line_arguments(Args, !IO),
(
Args = [_|_],
handle_files(Table, Args, !IO)
;
Args = [],
invoke_line(Table, "<stdin>", stdin_stream, !IO)
).
:- end_module rot13.
|
http://rosettacode.org/wiki/Roman_numerals/Encode
|
Roman numerals/Encode
|
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman 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
|
#Julia
|
Julia
|
using Printf
function romanencode(n::Integer)
if n < 1 || n > 4999 throw(DomainError()) end
DR = [["I", "X", "C", "M"] ["V", "L", "D", "MMM"]]
rnum = ""
for (omag, d) in enumerate(digits(n))
if d == 0
omr = ""
elseif d < 4
omr = DR[omag, 1] ^ d
elseif d == 4
omr = DR[omag, 1] * DR[omag, 2]
elseif d == 5
omr = DR[omag, 2]
elseif d < 9
omr = DR[omag, 2] * DR[omag, 1] ^ (d - 5)
else
omr = DR[omag, 1] * DR[omag + 1, 1]
end
rnum = omr * rnum
end
return rnum
end
testcases = [1990, 2008, 1668]
append!(testcases, rand(1:4999, 12))
testcases = unique(testcases)
println("Test romanencode, arabic => roman:")
for n in testcases
@printf("%-4i => %s\n", n, romanencode(n))
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.
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
FromRomanNumeral["MMCDV"]
|
http://rosettacode.org/wiki/Rock-paper-scissors
|
Rock-paper-scissors
|
Task
Implement the classic children's game Rock-paper-scissors, as well as a simple predictive AI (artificial intelligence) player.
Rock Paper Scissors is a two player game.
Each player chooses one of rock, paper or scissors, without knowing the other player's choice.
The winner is decided by a set of rules:
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.
|
#uBasic.2F4tH
|
uBasic/4tH
|
20 LET P=0: LET Q=0: LET Z=0
30 INPUT "Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? ", A
40 IF A>3 THEN GOTO 400
50 IF A=3 THEN LET A=4
60 IF A<1 THEN GOTO 400
70 C=RND(3) : LET D=4: FOR B=1 TO C+1 : LET D = D+D : NEXT : GOTO (A+D)*10
90 Z=Z+1 : PRINT "We both chose 'rock'. It's a draw." : GOTO 30
100 P=P+1 : PRINT "You chose 'paper', I chose 'rock'. You win.." : GOTO 30
120 Q=Q+1 : PRINT "You chose 'scissors', I chose 'rock'. I win!" : GOTO 30
170 Q=Q+1 : PRINT "You chose 'rock', I chose 'paper'. I win!" : GOTO 30
180 Z=Z+1 : PRINT "We both chose 'paper'. It's a draw." : GOTO 30
200 P=P+1 : PRINT "You chose 'scissors', I chose 'paper'. You win.." : GOTO 30
330 P=P+1 : PRINT "You chose 'rock', I chose 'scissors'. You win.." : GOTO 30
340 Q=Q+1 : PRINT "You chose 'paper', I chose 'scissors'. I win!" : GOTO 30
360 Z=Z+1 : PRINT "We both chose 'scissors'. It's a draw." : GOTO 30
400 PRINT "There were ";Z;" draws. I lost ";P;" times, you lost ";Q;" times." : 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.
|
#UNIX_Shell
|
UNIX Shell
|
#!/bin/bash
choices=(rock paper scissors)
# comparison function, works like Perl
# winner x y = 2 if y beats x, 1 if x beats 1, 0 if it's a tie
winner() {
local left="$1" right="$2"
echo $(( (3 + left - right) % 3 ))
}
human_counts=(1 1 1)
human_count=3
computer_counts=(0 0 0)
games=0 human=0 computer=0
PS3="What do you throw? "
while true; do
select choice in rock paper scissors quit; do
if [ -z "$choice" ]; then choice="$REPLY"; fi
if [ "$choice" = "quit" ]; then
break 2
fi
for (( h=0; h<${#choices[@]}; ++h )); do
if [ "${choices[h]}" = "$choice" ]; then
break
fi
done
if (( h < 3 )); then
break
fi
echo "Unrecognized choice. Try again!"
done
let n=RANDOM%human_count
for (( c=0; c<${#human_counts[@]}; ++c )); do
let n-=${human_counts[c]}
if (( n < 0 )); then
break
fi
done
let computer_counts[c]+=1
echo
echo "You chose ${choices[h]^^}"
echo "I chose ${choices[c]^^}"
w="$(winner "$c" "$h")"
case "$w" in
2) echo "YOU WIN!"; let human+=1;;
0) echo "TIE!";;
1) echo "I WIN!"; let computer+=1;;
*) echo "winner returned weird result '$w'";;
esac
echo
let games+=1
(( human_counts[(h+1)%3]+=1, human_count+=1 ))
done
echo
echo "We played $games games. You won $human, and I won $computer."
for (( i=0; i<3; ++i )); do
echo "You picked ${choices[i]} $(( human_counts[ (i+1)%3 ] - 1 )) times."
echo "I picked ${choices[i]} $(( computer_counts[i] )) times."
done
|
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.
|
#Ruby
|
Ruby
|
#! /usr/bin/env ruby
require 'net/http'
require 'time'
def gen_url(i)
day = Time.now + i*60*60*24
# Set the time zone in which to format the time, per
# https://coderwall.com/p/c7l82a/create-a-time-in-a-specific-timezone-in-ruby
old_tz = ENV['TZ']
ENV['TZ'] = 'Europe/Berlin'
url = day.strftime('http://tclers.tk/conferences/tcl/%Y-%m-%d.tcl')
ENV['TZ'] = old_tz
url
end
def main
back = 10
needle = ARGV[0]
(-back..0).each do |i|
url = gen_url(i)
haystack = Net::HTTP.get(URI(url)).split("\n")
mentions = haystack.select { |x| x.include? needle }
if !mentions.empty?
puts "#{url}\n------\n#{mentions.join("\n")}\n------\n"
end
end
end
main
|
http://rosettacode.org/wiki/Run-length_encoding
|
Run-length encoding
|
Run-length encoding
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Given a string containing uppercase characters (A-Z), compress repeated 'runs' of the same character by storing the length of that run, and provide a function to reverse the compression.
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.
|
#Ring
|
Ring
|
# Project : Run-length encoding
load "stdlib.ring"
test = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
num = 0
nr = 0
decode = newlist(7,2)
for n = 1 to len(test) - 1
if test[n] = test[n+1]
num = num + 1
else
nr = nr + 1
decode[nr][1] = (num + 1)
decode[nr][2] = test[n]
see "" + (num + 1) + test[n]
num = 0
ok
next
see "" + (num + 1) + test[n]
see nl
nr = nr + 1
decode[nr][1] = (num + 1)
decode[nr][2] = test[n]
for n = 1 to len(decode)
dec = copy(decode[n][2], decode[n][1])
see dec
next
|
http://rosettacode.org/wiki/RIPEMD-160
|
RIPEMD-160
|
RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code”.
You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
|
#C.23
|
C#
|
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main(string[] args)
{
string text = "Rosetta Code";
byte[] bytes = Encoding.ASCII.GetBytes(text);
RIPEMD160 myRIPEMD160 = RIPEMD160Managed.Create();
byte[] hashValue = myRIPEMD160.ComputeHash(bytes);
var hexdigest = BitConverter.ToString(hashValue).Replace("-", "").ToLower();
Console.WriteLine(hexdigest);
Console.ReadLine();
}
}
|
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
|
Respond to an unknown method call
|
Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#C.2B.2B
|
C++
|
class animal {
public:
virtual void bark() // concrete virtual, not pure
{
throw "implement me: do not know how to bark";
}
};
class elephant : public animal // does not implement bark()
{
};
int main()
{
elephant e;
e.bark(); // throws exception
}
|
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
|
Respond to an unknown method call
|
Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#Cach.C3.A9_ObjectScript
|
Caché ObjectScript
|
Class DynamicDispatch.Example Extends %RegisteredObject
{
Method Foo()
{
Write "This is foo", !
}
Method Bar()
{
Write "This is bar", !
}
Method %DispatchMethod(Method As %String, Args...)
{
Write "Tried to handle unknown method '"_Method_"'"
For i=1:1:$Get(Args) {
Write ", " If i=1 Write "with arguments: "
Write "'"_Args(i)_"'"
}
Write !
}
ClassMethod Test()
{
Set obj=##class(DynamicDispatch.Example).%New()
Do obj.Foo()
Do obj.Bar()
Do obj.Grill()
Do obj.Ding("Dong", 11)
}
}
|
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
|
#MiniScript
|
MiniScript
|
rot13 = function(s)
chars = s.values
for i in chars.indexes
c = chars[i]
if c >= "a" and c <= "z" then chars[i] = char(97 + (code(c)-97+13)%26)
if c >= "A" and c <= "Z" then chars[i] = char(65 + (code(c)-65+13)%26)
end for
return chars.join("")
end function
print rot13("Hello world!")
print rot13("Uryyb jbeyq!")
|
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
|
#Kotlin
|
Kotlin
|
val romanNumerals = mapOf(
1000 to "M",
900 to "CM",
500 to "D",
400 to "CD",
100 to "C",
90 to "XC",
50 to "L",
40 to "XL",
10 to "X",
9 to "IX",
5 to "V",
4 to "IV",
1 to "I"
)
fun encode(number: Int): String? {
if (number > 5000 || number < 1) {
return null
}
var num = number
var result = ""
for ((multiple, numeral) in romanNumerals.entries) {
while (num >= multiple) {
num -= multiple
result += numeral
}
}
return result
}
fun main(args: Array<String>) {
println(encode(1990))
println(encode(1666))
println(encode(2008))
}
|
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.
|
#MATLAB
|
MATLAB
|
function x = rom2dec(s)
% ROM2DEC converts Roman numbers to decimal
% store Roman digits values: I=1, V=5, X=10, L=50, C=100, D=500, M=1000
digitsValues = [0 0 100 500 0 0 0 0 1 0 0 50 1000 0 0 0 0 0 0 0 0 5 0 10 0 0];
% convert Roman number to array of values
values = digitsValues(s-'A'+1);
% change sign if next value is bigger
x = sum(values .* [sign(diff(-values)+eps),1]);
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.
|
#Wee_Basic
|
Wee Basic
|
let entered=0
let keycode=0
let rcounter=1
print 1 "Enter R for rock, P for paper, or S for scissors. (not case sensitive)"
while entered=0
input human$
if human=$="r"
let human$="rock"
let entered=1
elseif human=$="R"
let human$="rock"
let entered=1
elseif human=$="p"
let human$="paper"
let entered=1
elseif human=$="P"
let human$="paper"
let entered=1
elseif human=$="s"
let human$="scissors"
let entered=1
elseif human=$="S"
let human$="scissors"
let entered=1
elseif entered=0
print 1 "That choice is invalid."
endif
wend
print 1 "Press any key so the computer can make its choice."
while keycode=0
let rcounter=rcounter+1
let keycode=key()
if rcounter=4
let rcounter=1
endif
wend
if rcounter=1
let cpu$="rock"
elseif rcounter=2
let cpu$="paper"
elseif rcounter=3
let cpu$="scissors"
endif
print 1 "You chose"+human$+"."
print 1 "The computer chose"+cpu$+"."
if human$=cpu$
print 1 "You tied."
endif
if human$="rock"
if cpu$="paper"
print 1 "Paper covers rock, so you lose."
endif
if cpu$="scissors"
print 1 "Rock blunts scissors, so you win."
endif
endif
if human$="paper"
if cpu$="rock"
print 1 "Paper covers rock, so you win."
endif
if cpu$="scissors"
print 1 "Scissors cut paper, so you lose."
endif
endif
if human$="scissors"
if cpu$="rock"
print 1 "Rock blunts scissors, so you lose."
endif
if cpu$="paper"
print 1 "Scissors cut paper, so you win."
endif
endif
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.
|
#Wren
|
Wren
|
import "random" for Random
import "/str" for Str
import "/ioutil" for Input
var choices = "rpsq"
var rand = Random.new()
var pWins = 0 // player wins
var cWins = 0 // computer wins
var draws = 0 // neither wins
var games = 0 // games played
var pFreqs = [0, 0, 0] // player frequencies for each choice (rps)
var printScore = Fn.new {
System.print("Wins: You %(pWins), Computer %(cWins), Neither %(draws)\n")
}
var getComputerChoice = Fn.new {
// make a completely random choice until 3 games have been played
if (games < 3) return choices[rand.int(3)]
var num = rand.int(games)
return (num < pFreqs[0]) ? "p" :
(num < pFreqs[0] + pFreqs[1]) ? "s" : "r"
}
System.print("Enter: (r)ock, (p)aper, (s)cissors or (q)uit\n")
while (true) {
printScore.call()
var pChoice = Str.lower(Input.option("Your choice r/p/s/q : ", "rpsqRPSQ"))
if (pChoice == "q") {
System.print("OK, quitting")
return
}
var cChoice = getComputerChoice.call()
System.print("Computer's choice : %(cChoice)")
if (pChoice == "r" && cChoice == "s") {
System.print("Rock breaks scissors - You win!")
pWins = pWins + 1
} else if (pChoice == "p" && cChoice == "r") {
System.print("Paper covers rock - You win!")
pWins = pWins + 1
} else if (pChoice == "s" && cChoice == "p") {
System.print("Scissors cut paper - You win!")
pWins = pWins + 1
} else if (pChoice == "s" && cChoice == "r") {
System.print("Rock breaks scissors - Computer wins!")
cWins = cWins + 1
} else if (pChoice == "r" && cChoice == "p") {
System.print("Paper covers rock - Computer wins!")
cWins = cWins + 1
} else if (pChoice == "p" && cChoice == "s") {
System.print("Scissors cut paper - Computer wins!")
cWins = cWins + 1
} else {
System.print("It's a draw!")
draws = draws + 1
}
var pf = pFreqs[choices.indexOf(pChoice)]
pFreqs[choices.indexOf(pChoice)] = pf + 1
games = games + 1
System.print()
}
|
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.
|
#Scala
|
Scala
|
import java.net.Socket
import java.net.URL
import java.time
import java.time.format
import java.time.ZoneId
import java.util.Scanner
import scala.collection.JavaConverters._
def get(rawUrl: String): List[String] = {
val url = new URL(rawUrl)
val port = if (url.getPort > -1) url.getPort else 80
val sock = new Socket(url.getHost, port)
sock.getOutputStream.write(
s"GET /${url.getPath()} HTTP/1.0\n\n".getBytes("UTF-8")
)
new Scanner(sock.getInputStream).useDelimiter("\n").asScala.toList
}
def genUrl(n: Long) = {
val date = java.time.ZonedDateTime
.now(ZoneId.of("Europe/Berlin"))
.plusDays(n)
.format(java.time.format.DateTimeFormatter.ISO_LOCAL_DATE)
s"http://tclers.tk/conferences/tcl/$date.tcl"
}
val back = 10
val literal = args(0)
for (i <- -back to 0) {
val url = genUrl(i)
print(get(url).filter(_.contains(literal)) match {
case List() => ""
case x => s"$url\n------\n${x.mkString("\n")}\n------\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.
|
#Ruby
|
Ruby
|
# run_encode("aaabbbbc") #=> [["a", 3], ["b", 4], ["c", 1]]
def run_encode(string)
string
.chars
.chunk{|i| i}
.map {|kind, array| [kind, array.length]}
end
# run_decode([["a", 3], ["b", 4], ["c", 1]]) #=> "aaabbbbc"
def run_decode(char_counts)
char_counts
.map{|char, count| char * count}
.join
end
|
http://rosettacode.org/wiki/RIPEMD-160
|
RIPEMD-160
|
RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code”.
You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
|
#Clojure
|
Clojure
|
(use 'pandect.core)
(ripemd160 "Rosetta Code")
|
http://rosettacode.org/wiki/RIPEMD-160
|
RIPEMD-160
|
RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code”.
You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
|
#Common_Lisp
|
Common Lisp
|
(ql:quickload 'ironclad)
(defun string-to-ripemd-160 (str)
"Return the RIPEMD-160 digest of the given ASCII string."
(ironclad:byte-array-to-hex-string
(ironclad:digest-sequence :ripemd-160
(ironclad:ascii-string-to-byte-array str)))
(string-to-ripemd-160 "Rosetta Code")
|
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
|
Respond to an unknown method call
|
Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#Common_Lisp
|
Common Lisp
|
(defgeneric do-something (thing)
(:documentation "Do something to thing."))
(defmethod no-applicable-method ((method (eql #'do-something)) &rest args)
(format nil "No method for ~w on ~w." method args))
(defmethod do-something ((thing (eql 3)))
(format nil "Do something to ~w." thing))
|
http://rosettacode.org/wiki/Repunit_primes
|
Repunit primes
|
Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In base two, the repunits 11, 111, 11111, 1111111, etc. are prime. (These correspond to the Mersenne primes.)
In base three: 111, 1111111, 1111111111111, etc.
Repunit primes, by definition, are also circular primes.
Any repunit in any base having a composite number of digits is necessarily composite. Only repunits (in any base) having a prime number of digits might be prime.
Rather than expanding the repunit out as a giant list of 1s or converting to base 10, it is common to just list the number of 1s in the repunit; effectively the digit count. The base two repunit primes listed above would be represented as: 2, 3, 5, 7, etc.
Many of these sequences exist on OEIS, though they aren't specifically listed as "repunit prime digits" sequences.
Some bases have very few repunit primes. Bases 4, 8, and likely 16 have only one. Base 9 has none at all. Bases above 16 may have repunit primes as well... but this task is getting large enough already.
Task
For bases 2 through 16, Find and show, here on this page, the repunit primes as digit counts, up to a limit of 1000.
Stretch
Increase the limit to 2700 (or as high as you have patience for.)
See also
Wikipedia: Repunit primes
OEIS:A000043 - Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime (base 2)
OEIS:A028491 - Numbers k such that (3^k - 1)/2 is prime (base 3)
OEIS:A004061 - Numbers n such that (5^n - 1)/4 is prime (base 5)
OEIS:A004062 - Numbers n such that (6^n - 1)/5 is prime (base 6)
OEIS:A004063 - Numbers k such that (7^k - 1)/6 is prime (base 7)
OEIS:A004023 - Indices of prime repunits: numbers n such that 11...111 (with n 1's) = (10^n - 1)/9 is prime (base 10)
OEIS:A005808 - Numbers k such that (11^k - 1)/10 is prime (base 11)
OEIS:A004064 - Numbers n such that (12^n - 1)/11 is prime (base 12)
OEIS:A016054 - Numbers n such that (13^n - 1)/12 is prime (base 13)
OEIS:A006032 - Numbers k such that (14^k - 1)/13 is prime (base 14)
OEIS:A006033 - Numbers n such that (15^n - 1)/14 is prime (base 15)
Related task: Circular primes
|
#C.2B.2B
|
C++
|
#include <future>
#include <iomanip>
#include <iostream>
#include <vector>
#include <gmpxx.h>
#include <primesieve.hpp>
std::vector<uint64_t> repunit_primes(uint32_t base,
const std::vector<uint64_t>& primes) {
std::vector<uint64_t> result;
for (uint64_t prime : primes) {
mpz_class repunit(std::string(prime, '1'), base);
if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0)
result.push_back(prime);
}
return result;
}
int main() {
std::vector<uint64_t> primes;
const uint64_t limit = 2700;
primesieve::generate_primes(limit, &primes);
std::vector<std::future<std::vector<uint64_t>>> futures;
for (uint32_t base = 2; base <= 36; ++base) {
futures.push_back(std::async(repunit_primes, base, primes));
}
std::cout << "Repunit prime digits (up to " << limit << ") in:\n";
for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) {
std::cout << "Base " << std::setw(2) << base << ':';
for (auto digits : futures[i].get())
std::cout << ' ' << digits;
std::cout << '\n';
}
}
|
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
|
#Mirah
|
Mirah
|
def rot13 (value:string)
result = ""
d = ' '.toCharArray[0]
value.toCharArray.each do |c|
testChar = Character.toLowerCase(c)
if testChar <= 'm'.toCharArray[0] && testChar >= 'a'.toCharArray[0] then
d = char(c + 13)
end
if testChar <= 'z'.toCharArray[0] && testChar >= 'n'.toCharArray[0] then
d = char(c - 13)
end
result += d
end
result
end
puts rot13("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
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
|
#Lasso
|
Lasso
|
define br => '\r'
// encode roman
define encodeRoman(num::integer)::string => {
local(ref = array('M'=1000, 'CM'=900, 'D'=500, 'CD'=400, 'C'=100, 'XC'=90, 'L'=50, 'XL'=40, 'X'=10, 'IX'=9, 'V'=5, 'IV'=4, 'I'=1))
local(out = string)
with i in #ref do => {
while(#num >= #i->second) => {
#out->append(#i->first)
#num -= #i->second
}
}
return #out
}
'1990 in roman is '+encodeRoman(1990)
br
'2008 in roman is '+encodeRoman(2008)
br
'1666 in roman is '+encodeRoman(1666)
|
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.
|
#Mercury
|
Mercury
|
:- module test_roman.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module char.
:- import_module exception.
:- import_module int.
:- import_module list.
:- import_module string.
:- type conversion_error ---> not_a_roman_number.
:- func build_int(list(char), int, int) = int.
:- func from_roman(string) = int.
:- pred roman_to_int(char::in, int::out) is semidet.
from_roman(Roman) = Decimal :-
List = reverse(to_char_list(Roman)),
Decimal = build_int(List, 0, 0).
build_int([], LastValue, Accumulator) = LastValue + Accumulator.
build_int([Digit|Rest], LastValue, Accumulator) = Sum :-
( roman_to_int(Digit, Value) ->
( Value < LastValue ->
Sum = build_int(Rest, Value, Accumulator - LastValue)
; Sum = build_int(Rest, Value, Accumulator + LastValue) )
; throw(not_a_roman_number) ).
roman_to_int('I', 1).
roman_to_int('V', 5).
roman_to_int('X', 10).
roman_to_int('L', 50).
roman_to_int('C', 100).
roman_to_int('D', 500).
roman_to_int('M', 1000).
main(!IO) :-
command_line_arguments(Args, !IO),
foldl((pred(Arg::in, !.IO::di, !:IO::uo) is det :-
format("%s => %d\n", [s(Arg), i(from_roman(Arg))], !IO)),
Args, !IO).
:- end_module test_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.
|
#Yabasic
|
Yabasic
|
REM Yabasic 2.763 version
WINNER = 1 : ACTION = 2 : LOSSER = 3
dim word$(10, 3)
for n = 0 to 9
read word$(n, WINNER), word$(n, ACTION), word$(n, LOSSER)
next n
repeat
clear screen
computerChoice$ = word$(ran(10), WINNER)
print "'Rock, Paper, Scissors, Lizard, Spock!' rules are:\n"
for n = 0 to 9
SimonSay(n)
next n
print "\nType your choice letter:"
print "(R)ock, (P)aper, (S)cissors, (L)izard, Spoc(K), (Q)uit\n"
k$ = upper$(inkey$)
if k$ = "Q" break
switch k$
case "R": humanChoice$ = "Rock" : break
case "P": humanChoice$ = "Paper" : break
case "S": humanChoice$ = "Scissors" : break
case "L": humanChoice$ = "Lizard" : break
case "K": humanChoice$ = "Spock" : break
end switch
print "Player chose ", humanChoice$, " and Computer chose ", computerChoice$
for n = 0 to 9
if word$(n, WINNER) = humanChoice$ and word$(n, LOSSER) = computerChoice$ then
SimonSay(n)
print "Winner was Player"
wp = wp + 1
break
elseif word$(n, WINNER) = computerChoice$ and word$(n, LOSSER) = humanChoice$ then
SimonSay(n)
print "Winner was Computer"
wc = wc + 1
break
end if
next n
if n = 10 then
print "Ouch!"
end if
punctuation()
print "\nPress any key to continue"
inkey$
until(k$ = "Q")
punctuation()
if wp > wc then
print "Player win"
elseif wc > wp then
print "Computer win"
else
print "Tie"
end if
end
sub SimonSay(n)
print word$(n, WINNER), " ", word$(n, ACTION), " ", word$(n, LOSSER)
end sub
sub punctuation()
print "\nPlayer = ", wp, "\tComputer = ", wc, "\n"
end sub
data "Scissors","cuts","Paper"
data "Paper","covers","Rock"
data "Rock","crushes","Lizard"
data "Lizard","poisons","Spock"
data "Spock","smashes","Scissors"
data "Scissors","decapites","Lizard"
data "Lizard","eats","Paper"
data "Paper","disproves","Spock"
data "Spock","vaporizes","Rock"
data "Rock","blunts","Scissors"
|
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.
|
#Smalltalk
|
Smalltalk
|
CommandLineHandler subclass: #ChatHistorySearchCommandLineHandler
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'RosettaCode'!
!ChatHistorySearchCommandLineHandler methodsFor: 'activation' stamp: 'EduardoPadoan 1/27/2019 15:18'!
activate
self searchHistoryFor: self arguments first.
self quit! !
!ChatHistorySearchCommandLineHandler methodsFor: 'commands' stamp: 'EduardoPadoan 1/27/2019 17:01'!
searchHistoryFor: aString
| today startDate |
"XXX Doesn't account for DST"
today := DateAndTime now offset: 1 hours.
startDate := today - 10 days.
startDate to: today by: 1 days do: [ :targetDate |
| url response |
url := String streamContents: [ :aStream |
aStream nextPutAll: 'http://tclers.tk/conferences/tcl/'.
targetDate printYMDOn: aStream.
aStream nextPutAll: '.tcl'.
].
response := ZnEasy get: url.
response contents asString linesDo: [ :line |
(line asLowercase includesSubstring: aString asLowercase) ifTrue: [
self stdout print: line; lf.
]
]
]! !
"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "!
ChatHistorySearchCommandLineHandler class
instanceVariableNames: ''!
!ChatHistorySearchCommandLineHandler class methodsFor: 'accessing' stamp: 'EduardoPadoan 1/27/2019 14:53'!
description
^ 'Look for a pattern in the TCL chat history'! !
!ChatHistorySearchCommandLineHandler class methodsFor: 'accessing' stamp: 'EduardoPadoan 1/27/2019 14:50'!
commandName
^ 'searchHistory'! !
|
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.
|
#Tcl
|
Tcl
|
#! /usr/bin/env tclsh
package require http
proc get url {
set r [::http::geturl $url]
set content [::http::data $r]
::http::cleanup $r
return $content
}
proc grep {needle haystack} {
lsearch -all \
-inline \
-glob \
[split $haystack \n] \
*[string map {* \\* ? \\? \\ \\\\ [ \\[ ] \\]} $needle]*
}
proc main argv {
lassign $argv needle
set urlTemplate http://tclers.tk/conferences/tcl/%Y-%m-%d.tcl
set back 10
set now [clock seconds]
for {set i -$back} {$i <= 0} {incr i} {
set date [clock add $now $i days]
set url [clock format $date \
-format $urlTemplate \
-timezone :Europe/Berlin]
set found [grep $needle [get $url]]
if {$found ne {}} {
puts $url\n------\n[join $found \n]\n------\n
}
}
}
main $argv
|
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.
|
#Run_BASIC
|
Run BASIC
|
string$ = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
beg = 1
i = 1
[loop]
s$ = mid$(string$,beg,1)
while mid$(string$,i,1) = s$
i = i + 1
wend
press$ = press$ ; i-beg;s$
beg = i
if i < len(string$) then goto [loop]
print "Compressed:";press$
beg = 1
i = 1
[expand]
while mid$(press$,i,1) <= "9"
i = i + 1
wend
for j = 1 to val(mid$(press$,beg, i - beg))
expand$ = expand$ + mid$(press$,i,1)
next j
i = i + 1
beg = i
if i < len(press$) then goto [expand]
print " Expanded:";expand$
|
http://rosettacode.org/wiki/RIPEMD-160
|
RIPEMD-160
|
RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code”.
You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
|
#D
|
D
|
void main() {
import std.stdio, std.digest.ripemd;
writefln("%(%02x%)", "Rosetta Code".ripemd160Of);
}
|
http://rosettacode.org/wiki/RIPEMD-160
|
RIPEMD-160
|
RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code”.
You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
|
#Delphi
|
Delphi
|
program RIPEMD160;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
DCPripemd160;
function HashRipemd160(const Input: Ansistring): TArray<byte>;
var
Hasher: TDCP_ripemd160;
begin
Hasher := TDCP_ripemd160.Create(nil);
try
Hasher.Init;
Hasher.UpdateStr(Input);
SetLength(Result, Hasher.HashSize div 8);
Hasher.final(Result[0]);
finally
Hasher.Free;
end;
end;
begin
for var b in HashRipemd160('Rosetta Code') do
begin
write(b.ToHexString(2));
end;
readln;
end.
|
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
|
Respond to an unknown method call
|
Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#D
|
D
|
import std.stdio;
struct Catcher {
void foo() { writeln("This is foo"); }
void bar() { writeln("This is bar"); }
void opDispatch(string name, ArgsTypes...)(ArgsTypes args) {
writef("Tried to handle unknown method '%s'", name);
if (ArgsTypes.length) {
write(", with arguments: ");
foreach (arg; args)
write(arg, " ");
}
writeln();
}
}
void main() {
Catcher ca;
ca.foo();
ca.bar();
ca.grill();
ca.ding("dong", 11);
}
|
http://rosettacode.org/wiki/Reverse_words_in_a_string
|
Reverse words in a string
|
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified.
You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.
Some strings have no tokens, so an empty string (or one just containing spaces) would be the result.
Display the strings in order (1st, 2nd, 3rd, ···), and one string per line.
(You can consider the ten strings as ten lines, and the tokens as words.)
Input data
(ten lines within the box)
line
╔════════════════════════════════════════╗
1 ║ ---------- Ice and Fire ------------ ║
2 ║ ║ ◄─── a blank line here.
3 ║ fire, in end will world the say Some ║
4 ║ ice. in say Some ║
5 ║ desire of tasted I've what From ║
6 ║ fire. favor who those with hold I ║
7 ║ ║ ◄─── a blank line here.
8 ║ ... elided paragraph last ... ║
9 ║ ║ ◄─── a blank line here.
10 ║ Frost Robert ----------------------- ║
╚════════════════════════════════════════╝
Cf.
Phrase reversals
|
#11l
|
11l
|
V text =
‘---------- Ice and Fire ------------
fire, in end will world the say Some
ice. in say Some
desire of tasted I've what From
fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------’
L(line) text.split("\n")
print(reversed(line.split(‘ ’)).join(‘ ’))
|
http://rosettacode.org/wiki/Repunit_primes
|
Repunit primes
|
Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In base two, the repunits 11, 111, 11111, 1111111, etc. are prime. (These correspond to the Mersenne primes.)
In base three: 111, 1111111, 1111111111111, etc.
Repunit primes, by definition, are also circular primes.
Any repunit in any base having a composite number of digits is necessarily composite. Only repunits (in any base) having a prime number of digits might be prime.
Rather than expanding the repunit out as a giant list of 1s or converting to base 10, it is common to just list the number of 1s in the repunit; effectively the digit count. The base two repunit primes listed above would be represented as: 2, 3, 5, 7, etc.
Many of these sequences exist on OEIS, though they aren't specifically listed as "repunit prime digits" sequences.
Some bases have very few repunit primes. Bases 4, 8, and likely 16 have only one. Base 9 has none at all. Bases above 16 may have repunit primes as well... but this task is getting large enough already.
Task
For bases 2 through 16, Find and show, here on this page, the repunit primes as digit counts, up to a limit of 1000.
Stretch
Increase the limit to 2700 (or as high as you have patience for.)
See also
Wikipedia: Repunit primes
OEIS:A000043 - Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime (base 2)
OEIS:A028491 - Numbers k such that (3^k - 1)/2 is prime (base 3)
OEIS:A004061 - Numbers n such that (5^n - 1)/4 is prime (base 5)
OEIS:A004062 - Numbers n such that (6^n - 1)/5 is prime (base 6)
OEIS:A004063 - Numbers k such that (7^k - 1)/6 is prime (base 7)
OEIS:A004023 - Indices of prime repunits: numbers n such that 11...111 (with n 1's) = (10^n - 1)/9 is prime (base 10)
OEIS:A005808 - Numbers k such that (11^k - 1)/10 is prime (base 11)
OEIS:A004064 - Numbers n such that (12^n - 1)/11 is prime (base 12)
OEIS:A016054 - Numbers n such that (13^n - 1)/12 is prime (base 13)
OEIS:A006032 - Numbers k such that (14^k - 1)/13 is prime (base 14)
OEIS:A006033 - Numbers n such that (15^n - 1)/14 is prime (base 15)
Related task: Circular primes
|
#F.23
|
F#
|
// Repunit primes. Nigel Galloway: January 24th., 2022
let rUnitP(b:int)=let b=bigint b in primes32()|>Seq.takeWhile((>)1000)|>Seq.map(fun n->(n,((b**n)-1I)/(b-1I)))|>Seq.filter(fun(_,n)->Open.Numeric.Primes.MillerRabin.IsProbablePrime &n)|>Seq.map fst
[2..16]|>List.iter(fun n->printf $"Base %d{n}: "; rUnitP(n)|>Seq.iter(printf "%d "); printfn "")
|
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
|
#ML
|
ML
|
fun rot13char c =
if c >= #"a" andalso c <= #"m" orelse c >= #"A" andalso c <= #"M" then
chr (ord c + 13)
else if c >= #"n" andalso c <= #"z" orelse c >= #"N" andalso c <= #"Z" then
chr (ord c - 13)
else
c
val rot13 = String.map rot13char
|
http://rosettacode.org/wiki/Roman_numerals/Encode
|
Roman numerals/Encode
|
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman 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
|
#LaTeX
|
LaTeX
|
\documentclass{minimal}
\newcounter{currentyear}
\setcounter{currentyear}{\year}
\begin{document}
Anno Domini \Roman{currentyear}
\end{document}
|
http://rosettacode.org/wiki/Roman_numerals/Decode
|
Roman numerals/Decode
|
Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost 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.
|
#Modula-2
|
Modula-2
|
MODULE RomanNumerals;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
FROM Strings IMPORT Length;
(* Convert given Roman numeral to binary *)
PROCEDURE DecodeRoman(s: ARRAY OF CHAR): CARDINAL;
VAR i, d, len, acc: CARDINAL;
PROCEDURE Digit(d: CHAR): CARDINAL;
BEGIN
CASE CHR( BITSET(ORD(d)) + BITSET{5} ) OF (* lowercase *)
'm': RETURN 1000;
| 'd': RETURN 500;
| 'c': RETURN 100;
| 'l': RETURN 50;
| 'x': RETURN 10;
| 'v': RETURN 5;
| 'i': RETURN 1;
ELSE
RETURN 0;
END;
END Digit;
BEGIN
len := Length(s);
acc := 0;
FOR i := 0 TO len-1 DO
d := Digit(s[i]);
IF d=0 THEN RETURN 0; END;
IF (i # len-1) AND (d < Digit(s[i+1])) THEN
acc := acc - d;
ELSE
acc := acc + d;
END;
END;
RETURN acc;
END DecodeRoman;
PROCEDURE Show(s: ARRAY OF CHAR);
BEGIN
WriteString(s);
WriteString(": ");
WriteCard(DecodeRoman(s), 0);
WriteLn();
END Show;
BEGIN
Show("MCMXC");
Show("MDCLXVI");
Show("mmvii");
Show("mmxxi");
END RomanNumerals.
|
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.
|
#Wren
|
Wren
|
/* retrieve_and_search_chat_history.wren */
import "./date" for Date
var CURLOPT_URL = 10002
var CURLOPT_FOLLOWLOCATION = 52
var CURLOPT_WRITEFUNCTION = 20011
var CURLOPT_WRITEDATA = 10001
class C {
foreign static searchStr
foreign static utcNow // format will be yyyy-mm-dd hh:MM:ss
}
foreign class Buffer {
construct new() {} // C will allocate buffer of a suitable size
foreign value // returns buffer contents as a string
}
foreign class Curl {
construct easyInit() {}
foreign easySetOpt(opt, param)
foreign easyPerform()
foreign easyCleanup()
}
var curl = Curl.easyInit()
var getContent = Fn.new { |url|
var buffer = Buffer.new()
curl.easySetOpt(CURLOPT_URL, url)
curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1)
curl.easySetOpt(CURLOPT_WRITEFUNCTION, 0) // write function to be supplied by C
curl.easySetOpt(CURLOPT_WRITEDATA, buffer)
curl.easyPerform()
return buffer.value
}
var baseUrl = "http://tclers.tk/conferences/tcl/"
var searchStr = C.searchStr
var now = C.utcNow
var d = Date.parse(now)
d = d.adjustTime("CET") // adjust to German time
var fmt = "mmmm| |d| |yyyy| |H|:|MM|am| |zz|"
System.print("It's %(d.format(fmt)) just now in Germany.")
System.print("Searching for '%(searchStr)' in the TCL Chatroom logs for the last 10 days:\n")
for (i in 0..9) {
var date = d.toString.split(" ")[0]
var url = baseUrl + date + ".tcl"
var underline = "-" * url.count
var content = getContent.call(url)
var lines = content.split("\n")
System.print("%(url)")
System.print(underline)
for (line in lines) {
if (line.indexOf(searchStr) >= 0) System.print(line)
}
System.print(underline + "\n")
d = d.addDays(-1)
}
curl.easyCleanup()
|
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.
|
#Rust
|
Rust
|
fn encode(s: &str) -> String {
s.chars()
// wrap all values in Option::Some
.map(Some)
// add an Option::None onto the iterator to clean the pipeline at the end
.chain(std::iter::once(None))
.scan((0usize, '\0'), |(n, c), elem| match elem {
Some(elem) if *n == 0 || *c == elem => {
// the run continues or starts here
*n += 1;
*c = elem;
// this will not have an effect on the final string because it is empty
Some(String::new())
}
Some(elem) => {
// the run ends here
let run = format!("{}{}", n, c);
*n = 1;
*c = elem;
Some(run)
}
None => {
// the string ends here
Some(format!("{}{}", n, c))
}
})
// concatenate together all subresults
.collect()
}
fn decode(s: &str) -> String {
s.chars()
.fold((0usize, String::new()), |(n, text), c| {
if c.is_ascii_digit() {
// some simple number parsing
(
n * 10 + c.to_digit(10).expect("invalid encoding") as usize,
text,
)
} else {
// this must be the character that is repeated
(0, text + &format!("{}", c.to_string().repeat(n)))
}
})
.1
}
fn main() {
let text = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
let encoded = encode(text);
let decoded = decode(&encoded);
println!("original: {}\n encoded: {}\n decoded: {}", text, encoded, decoded);
assert_eq!(text, decoded);
}
|
http://rosettacode.org/wiki/RIPEMD-160
|
RIPEMD-160
|
RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code”.
You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
|
#Factor
|
Factor
|
USING: checksums checksums.ripemd io math.parser ;
"Rosetta Code" ripemd-160 checksum-bytes bytes>hex-string print
|
http://rosettacode.org/wiki/RIPEMD-160
|
RIPEMD-160
|
RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code”.
You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
|
#FreeBASIC
|
FreeBASIC
|
' version 22-10-2016
' compile with: fbc -s console
Function RIPEMD_160(message As String) As String
#Macro ROtate_left(x, n)
(x Shl n Or x Shr (32 - n))
#EndMacro
#Macro f1(x, y, z)
(x Xor y Xor z) ' (0 <= j <= 15)
#EndMacro
#Macro f2(x, y, z)
((x And y) Or ((Not x) And z)) ' (16 <= j <= 31)
#EndMacro
#Macro f3(x, y, z)
((x Or (Not y)) Xor z) ''(32 <= j <= 47)
#EndMacro
#Macro f4(x, y, z)
((x And z) Or (y And (Not z))) ''(48 <= j <= 63)
#EndMacro
#Macro f5(x, y, z)
(x Xor (y Or (Not z))) ''(64 <= j <= 79)
#EndMacro
Dim As UInteger<32> K(1 To 5), K1(1 To 5)
K(1) = &H00000000 ' (0 <= j <= 15)
K(2) = &H5A827999 ' (16 <= j <= 31)
K(3) = &H6ED9EBA1 ' (32 <= j <= 47)
K(4) = &H8F1BBCDC ' (48 <= j <= 63)
K(5) = &HA953FD4E ' (64 <= j <= 79)
K1(1) = &H50A28BE6 ' (0 <= j <= 15)
K1(2) = &H5C4DD124 ' (16 <= j <= 31)
K1(3) = &H6D703EF3 ' (32 <= j <= 47)
K1(4) = &H7A6D76E9 ' (48 <= j <= 63)
K1(5) = &H00000000 ' (64 <= j <= 79)
Dim As UByte r(16 To ...) = _
{ 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, _
3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, _
1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, _
4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 }
Dim As UByte r1(0 To ...) = _
{ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, _
6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, _
15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, _
8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, _
12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 }
Dim As UByte s(0 To ...) = _
{ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, _
7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, _
11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, _
11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, _
9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 }
Dim As UByte s1(0 To ...) = _
{ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, _
9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, _
9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, _
15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, _
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 }
Dim As UInteger<32> h0 = &H67452301
Dim As UInteger<32> h1 = &HEFCDAB89
Dim As UInteger<32> h2 = &H98BADCFE
Dim As UInteger<32> h3 = &H10325476
Dim As UInteger<32> h4 = &HC3D2E1F0
Dim As Long i, j
Dim As ULongInt l = Len(message)
' set the first bit after the message to 1
message = message + Chr(1 Shl 7)
' add one char to the length
Dim As ULong padding = 64 - ((l +1) Mod (512 \ 8)) ' 512 \ 8 = 64 char.
' check if we have enough room for inserting the length
If padding < 8 Then padding = padding + 64
message = message + String(padding, Chr(0)) ' adjust length
Dim As ULong l1 = Len(message) ' new length
l = l * 8 ' orignal length in bits
' create ubyte ptr to point to l ( = length in bits)
Dim As UByte Ptr ub_ptr = Cast(UByte Ptr, @l)
For i = 0 To 7 'copy length of message to the last 8 bytes
message[l1 -8 + i] = ub_ptr[i]
Next
Dim As UInteger<32> A, B, C, D, E, A1, B1, C1, D1, E1, T, T1
For i = 0 To (l1 -1) \ 64 ' split into 64 byte block
' x point to 16 * 4byte block inside the string message
Dim As UInteger<32> Ptr X = Cast(UInteger<32> Ptr, @message[i*64])
A = h0 : B = h1 : C = h2 : D = h3 : E = h4
A1 = h0 : B1 = h1 : C1 = h2 : D1 = h3 : E1 = h4
For j = 0 To 79
Select Case As Const j
Case 0 To 15
T = A + f1(B, C, D) + X[j] '+ K(1)
T = ROtate_Left(T, s(j)) + E
T1 = A1 + f5(B1, C1, D1) + X[r1(j)] + K1(1)
T1 = ROtate_Left(T1, s1(j)) + E1
Case 16 To 31
T = A + f2(B, C, D) + X[r(j)] + K(2)
T = ROtate_Left(T, s(j)) + E
T1 = A1 + f4(B1, C1, D1) + X[r1(j)] + K1(2)
T1 = ROtate_Left(T1, s1(j)) + E1
Case 32 To 47
T = A + f3(B, C, D) + X[r(j)] + K(3)
T = ROtate_Left(T, s(j)) + E
T1 = A1 + f3(B1, C1, D1) + X[r1(j)] + K1(3)
T1 = ROtate_Left(T1, s1(j)) + E1
Case 48 To 63
T = A + f4(B, C, D) + X[r(j)] + K(4)
T = ROtate_Left(T, s(j)) + E
T1 = A1 + f2(B1, C1, D1) + X[r1(j)] + K1(4)
T1 = ROtate_Left(T1, s1(j)) + E1
Case 64 To 79
T = A + f5(B, C, D) + X[r(j)] + K(5)
T = ROtate_Left(T, s(j)) + E
T1 = A1 + f1(B1, C1, D1) + X[r1(j)] '+ K1(5)
T1 = ROtate_Left(T1, s1(j)) + E1
End Select
A = E : E = D : D = ROtate_Left(C, 10) : C = B : B = T
A1 = E1 : E1 = D1 : D1 = ROtate_left(C1, 10) : C1 = B1 : B1 = T1
Next
T = h1 + C + D1
h1 = h2 + D + E1
h2 = h3 + E + A1
h3 = h4 + A + B1
h4 = h0 + B + C1
h0 = T
Next
Dim As String answer
' convert h0, h1, h2, h3 and h4 in hex, then add, low order first
Dim As String hs1 = Hex(h0, 8)
For i = 7 To 1 Step -2 : answer += Mid(hs1, i, 2) : Next
hs1 = Hex(h1, 8)
For i = 7 To 1 Step -2 : answer += Mid(hs1, i, 2) : Next
hs1 = Hex(h2, 8)
For i = 7 To 1 Step -2 : answer += Mid(hs1, i, 2) : Next
hs1 = Hex(h3, 8)
For i = 7 To 1 Step -2 : answer += Mid(hs1, i, 2) : Next
hs1 = Hex(h4, 8)
For i = 7 To 1 Step -2 : answer += Mid(hs1, i, 2) : Next
Return LCase(answer)
End Function
' ------=< MAIN >=------
Dim As String test = "Rosetta Code"
Print
Print test; " => "; RIPEMD_160(test)
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End
|
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
|
Respond to an unknown method call
|
Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#D.C3.A9j.C3.A0_Vu
|
Déjà Vu
|
}
labda:
print "One!"
:one
labda:
print "Two!"
:two
local :obj {
labda:
print "Nope, doesn't exist."
set-default obj
obj!one
obj!two
obj!three
|
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
|
Respond to an unknown method call
|
Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#E
|
E
|
def example {
to foo() { println("this is foo") }
to bar() { println("this is bar") }
match [verb, args] {
println(`got unrecognized message $verb`)
if (args.size() > 0) {
println(`it had arguments: $args`)
}
}
}
|
http://rosettacode.org/wiki/Reverse_words_in_a_string
|
Reverse words in a string
|
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified.
You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.
Some strings have no tokens, so an empty string (or one just containing spaces) would be the result.
Display the strings in order (1st, 2nd, 3rd, ···), and one string per line.
(You can consider the ten strings as ten lines, and the tokens as words.)
Input data
(ten lines within the box)
line
╔════════════════════════════════════════╗
1 ║ ---------- Ice and Fire ------------ ║
2 ║ ║ ◄─── a blank line here.
3 ║ fire, in end will world the say Some ║
4 ║ ice. in say Some ║
5 ║ desire of tasted I've what From ║
6 ║ fire. favor who those with hold I ║
7 ║ ║ ◄─── a blank line here.
8 ║ ... elided paragraph last ... ║
9 ║ ║ ◄─── a blank line here.
10 ║ Frost Robert ----------------------- ║
╚════════════════════════════════════════╝
Cf.
Phrase reversals
|
#Action.21
|
Action!
|
PROC Reverse(CHAR ARRAY src,dst)
BYTE i,j,k,beg,end
i=1 j=src(0)
WHILE j>0
DO
WHILE j>0 AND src(j)=$20
DO j==-1 OD
IF j=0 THEN
EXIT
ELSE
end=j
FI
WHILE j>0 AND src(j)#$20
DO j==-1 OD
beg=j+1
IF i>1 THEN
dst(i)=$20 i==+1
FI
FOR k=beg TO end
DO
dst(i)=src(k) i==+1
OD
OD
dst(0)=i-1
RETURN
PROC Test(CHAR ARRAY src)
CHAR ARRAY dst(40)
Reverse(src,dst)
PrintE(dst)
RETURN
PROC Main()
Test("---------- Ice and Fire ------------")
Test("")
Test("fire, in end will world the say Some")
Test("ice. in say Some")
Test("desire of tasted I've what From")
Test("fire. favor who those with hold I")
Test("")
Test("... elided paragraph last ...")
Test("")
Test("Frost Robert -----------------------")
RETURN
|
http://rosettacode.org/wiki/Repunit_primes
|
Repunit primes
|
Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In base two, the repunits 11, 111, 11111, 1111111, etc. are prime. (These correspond to the Mersenne primes.)
In base three: 111, 1111111, 1111111111111, etc.
Repunit primes, by definition, are also circular primes.
Any repunit in any base having a composite number of digits is necessarily composite. Only repunits (in any base) having a prime number of digits might be prime.
Rather than expanding the repunit out as a giant list of 1s or converting to base 10, it is common to just list the number of 1s in the repunit; effectively the digit count. The base two repunit primes listed above would be represented as: 2, 3, 5, 7, etc.
Many of these sequences exist on OEIS, though they aren't specifically listed as "repunit prime digits" sequences.
Some bases have very few repunit primes. Bases 4, 8, and likely 16 have only one. Base 9 has none at all. Bases above 16 may have repunit primes as well... but this task is getting large enough already.
Task
For bases 2 through 16, Find and show, here on this page, the repunit primes as digit counts, up to a limit of 1000.
Stretch
Increase the limit to 2700 (or as high as you have patience for.)
See also
Wikipedia: Repunit primes
OEIS:A000043 - Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime (base 2)
OEIS:A028491 - Numbers k such that (3^k - 1)/2 is prime (base 3)
OEIS:A004061 - Numbers n such that (5^n - 1)/4 is prime (base 5)
OEIS:A004062 - Numbers n such that (6^n - 1)/5 is prime (base 6)
OEIS:A004063 - Numbers k such that (7^k - 1)/6 is prime (base 7)
OEIS:A004023 - Indices of prime repunits: numbers n such that 11...111 (with n 1's) = (10^n - 1)/9 is prime (base 10)
OEIS:A005808 - Numbers k such that (11^k - 1)/10 is prime (base 11)
OEIS:A004064 - Numbers n such that (12^n - 1)/11 is prime (base 12)
OEIS:A016054 - Numbers n such that (13^n - 1)/12 is prime (base 13)
OEIS:A006032 - Numbers k such that (14^k - 1)/13 is prime (base 14)
OEIS:A006033 - Numbers n such that (15^n - 1)/14 is prime (base 15)
Related task: Circular primes
|
#Go
|
Go
|
package main
import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
"strings"
)
func main() {
limit := 2700
primes := rcu.Primes(limit)
s := new(big.Int)
for b := 2; b <= 36; b++ {
var rPrimes []int
for _, p := range primes {
s.SetString(strings.Repeat("1", p), b)
if s.ProbablyPrime(15) {
rPrimes = append(rPrimes, p)
}
}
fmt.Printf("Base %2d: %v\n", b, rPrimes)
}
}
|
http://rosettacode.org/wiki/Repunit_primes
|
Repunit primes
|
Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In base two, the repunits 11, 111, 11111, 1111111, etc. are prime. (These correspond to the Mersenne primes.)
In base three: 111, 1111111, 1111111111111, etc.
Repunit primes, by definition, are also circular primes.
Any repunit in any base having a composite number of digits is necessarily composite. Only repunits (in any base) having a prime number of digits might be prime.
Rather than expanding the repunit out as a giant list of 1s or converting to base 10, it is common to just list the number of 1s in the repunit; effectively the digit count. The base two repunit primes listed above would be represented as: 2, 3, 5, 7, etc.
Many of these sequences exist on OEIS, though they aren't specifically listed as "repunit prime digits" sequences.
Some bases have very few repunit primes. Bases 4, 8, and likely 16 have only one. Base 9 has none at all. Bases above 16 may have repunit primes as well... but this task is getting large enough already.
Task
For bases 2 through 16, Find and show, here on this page, the repunit primes as digit counts, up to a limit of 1000.
Stretch
Increase the limit to 2700 (or as high as you have patience for.)
See also
Wikipedia: Repunit primes
OEIS:A000043 - Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime (base 2)
OEIS:A028491 - Numbers k such that (3^k - 1)/2 is prime (base 3)
OEIS:A004061 - Numbers n such that (5^n - 1)/4 is prime (base 5)
OEIS:A004062 - Numbers n such that (6^n - 1)/5 is prime (base 6)
OEIS:A004063 - Numbers k such that (7^k - 1)/6 is prime (base 7)
OEIS:A004023 - Indices of prime repunits: numbers n such that 11...111 (with n 1's) = (10^n - 1)/9 is prime (base 10)
OEIS:A005808 - Numbers k such that (11^k - 1)/10 is prime (base 11)
OEIS:A004064 - Numbers n such that (12^n - 1)/11 is prime (base 12)
OEIS:A016054 - Numbers n such that (13^n - 1)/12 is prime (base 13)
OEIS:A006032 - Numbers k such that (14^k - 1)/13 is prime (base 14)
OEIS:A006033 - Numbers n such that (15^n - 1)/14 is prime (base 15)
Related task: Circular primes
|
#Julia
|
Julia
|
using Primes
repunitprimeinbase(n, base) = isprime(evalpoly(BigInt(base), [1 for _ in 1:n]))
for b in 2:40
println(rpad("Base $b:", 9), filter(n -> repunitprimeinbase(n, b), 1:2700))
end
|
http://rosettacode.org/wiki/Repunit_primes
|
Repunit primes
|
Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In base two, the repunits 11, 111, 11111, 1111111, etc. are prime. (These correspond to the Mersenne primes.)
In base three: 111, 1111111, 1111111111111, etc.
Repunit primes, by definition, are also circular primes.
Any repunit in any base having a composite number of digits is necessarily composite. Only repunits (in any base) having a prime number of digits might be prime.
Rather than expanding the repunit out as a giant list of 1s or converting to base 10, it is common to just list the number of 1s in the repunit; effectively the digit count. The base two repunit primes listed above would be represented as: 2, 3, 5, 7, etc.
Many of these sequences exist on OEIS, though they aren't specifically listed as "repunit prime digits" sequences.
Some bases have very few repunit primes. Bases 4, 8, and likely 16 have only one. Base 9 has none at all. Bases above 16 may have repunit primes as well... but this task is getting large enough already.
Task
For bases 2 through 16, Find and show, here on this page, the repunit primes as digit counts, up to a limit of 1000.
Stretch
Increase the limit to 2700 (or as high as you have patience for.)
See also
Wikipedia: Repunit primes
OEIS:A000043 - Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime (base 2)
OEIS:A028491 - Numbers k such that (3^k - 1)/2 is prime (base 3)
OEIS:A004061 - Numbers n such that (5^n - 1)/4 is prime (base 5)
OEIS:A004062 - Numbers n such that (6^n - 1)/5 is prime (base 6)
OEIS:A004063 - Numbers k such that (7^k - 1)/6 is prime (base 7)
OEIS:A004023 - Indices of prime repunits: numbers n such that 11...111 (with n 1's) = (10^n - 1)/9 is prime (base 10)
OEIS:A005808 - Numbers k such that (11^k - 1)/10 is prime (base 11)
OEIS:A004064 - Numbers n such that (12^n - 1)/11 is prime (base 12)
OEIS:A016054 - Numbers n such that (13^n - 1)/12 is prime (base 13)
OEIS:A006032 - Numbers k such that (14^k - 1)/13 is prime (base 14)
OEIS:A006033 - Numbers n such that (15^n - 1)/14 is prime (base 15)
Related task: Circular primes
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
ClearAll[RepUnitPrimeQ]
RepUnitPrimeQ[b_][n_] := PrimeQ[FromDigits[ConstantArray[1, n], b]]
ClearAll[RepUnitPrimeQ]
RepUnitPrimeQ[b_][n_] := PrimeQ[FromDigits[ConstantArray[1, n], b]]
Do[
Print["Base ", b, ": ", Select[Range[2700], RepUnitPrimeQ[b]]]
,
{b, 2, 16}
]
|
http://rosettacode.org/wiki/Repunit_primes
|
Repunit primes
|
Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In base two, the repunits 11, 111, 11111, 1111111, etc. are prime. (These correspond to the Mersenne primes.)
In base three: 111, 1111111, 1111111111111, etc.
Repunit primes, by definition, are also circular primes.
Any repunit in any base having a composite number of digits is necessarily composite. Only repunits (in any base) having a prime number of digits might be prime.
Rather than expanding the repunit out as a giant list of 1s or converting to base 10, it is common to just list the number of 1s in the repunit; effectively the digit count. The base two repunit primes listed above would be represented as: 2, 3, 5, 7, etc.
Many of these sequences exist on OEIS, though they aren't specifically listed as "repunit prime digits" sequences.
Some bases have very few repunit primes. Bases 4, 8, and likely 16 have only one. Base 9 has none at all. Bases above 16 may have repunit primes as well... but this task is getting large enough already.
Task
For bases 2 through 16, Find and show, here on this page, the repunit primes as digit counts, up to a limit of 1000.
Stretch
Increase the limit to 2700 (or as high as you have patience for.)
See also
Wikipedia: Repunit primes
OEIS:A000043 - Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime (base 2)
OEIS:A028491 - Numbers k such that (3^k - 1)/2 is prime (base 3)
OEIS:A004061 - Numbers n such that (5^n - 1)/4 is prime (base 5)
OEIS:A004062 - Numbers n such that (6^n - 1)/5 is prime (base 6)
OEIS:A004063 - Numbers k such that (7^k - 1)/6 is prime (base 7)
OEIS:A004023 - Indices of prime repunits: numbers n such that 11...111 (with n 1's) = (10^n - 1)/9 is prime (base 10)
OEIS:A005808 - Numbers k such that (11^k - 1)/10 is prime (base 11)
OEIS:A004064 - Numbers n such that (12^n - 1)/11 is prime (base 12)
OEIS:A016054 - Numbers n such that (13^n - 1)/12 is prime (base 13)
OEIS:A006032 - Numbers k such that (14^k - 1)/13 is prime (base 14)
OEIS:A006033 - Numbers n such that (15^n - 1)/14 is prime (base 15)
Related task: Circular primes
|
#Perl
|
Perl
|
use strict;
use warnings;
use ntheory <is_prime fromdigits>;
my $limit = 1000;
print "Repunit prime digits (up to $limit) in:\n";
for my $base (2..16) {
printf "Base %2d: %s\n", $base, join ' ', grep { is_prime $_ and is_prime fromdigits(('1'x$_), $base) and " $_" } 1..$limit
}
|
http://rosettacode.org/wiki/Rot-13
|
Rot-13
|
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of 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
|
#MMIX
|
MMIX
|
// main registers
p IS $255 % text pointer
c GREG % char
cc GREG % uppercase copy of c
u GREG % all purpose
LOC Data_Segment
GREG @
Test BYTE "dit is een bericht voor de keizer",#a,0
LOC #100
Main LDA p,Test
TRAP 0,Fputs,StdOut % show text to encrypt
LDA p,Test % points to text to encrypt
JMP 4F
// do in place text encryption
% REPEAT
2H ADD cc,c,0 % copy char
SUB cc,cc,' ' % make uppercase
CMP u,cc,'A'
BN u,3F % IF c < 'A' OR c > 'Z' THEN next char
CMP u,cc,'Z'
BP u,3F
CMP u,cc,'N' % ELSE
BN u,1F % IF c < 'N' THEN encrypt 'up'
SUB c,c,26 % ELSE char ready for encrypt 'down'
1H INCL c,13 % encrypt char
STBU c,p % replace char with encrypted char
3H INCL p,1 % move to next char
4H LDBU c,p % get next char
PBNZ c,2B % UNTIL EOT
// print result
LDA p,Test
TRAP 0,Fputs,StdOut % show encrypted text
TRAP 0,Halt,0
|
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
|
#Liberty_BASIC
|
Liberty BASIC
|
dim arabic( 12)
for i =0 to 12
read k
arabic( i) =k
next i
data 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
dim roman$( 12)
for i =0 to 12
read k$
roman$( i) =k$
next i
data "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
print 2009, toRoman$( 2009)
print 1666, toRoman$( 1666)
print 3888, toRoman$( 3888)
end
function toRoman$( value)
i =0
result$ =""
for i = 0 to 12
while value >=arabic( i)
result$ = result$ + roman$( i)
value = value - arabic( i)
wend
next i
toRoman$ =result$
end function
|
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.
|
#Nanoquery
|
Nanoquery
|
def decodeSingle(letter)
if letter = "M"
return 1000
else if letter = "D"
return 500
else if letter = "C"
return 100
else if letter = "L"
return 50
else if letter = "X"
return 10
else if letter = "V"
return 5
else if letter = "I"
return 1
else
return 0
end
end
def decode(roman)
result = 0
uRoman = roman.toUpperCase()
for (i = 0) (i < len(uRoman) - 1) (i += 1)
if decodeSingle(uRoman[i]) < decodeSingle(uRoman[i + 1])
result -= decodeSingle(uRoman[i])
else
result += decodeSingle(uRoman[i])
end
end
result += decodeSingle(uRoman[len(uRoman) - 1])
return result
end
println decode("MCMXC")
println decode("MMVIII")
println decode("MDCLXVI")
|
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.
|
#zkl
|
zkl
|
#<<<#
http://tclers.tk/conferences/tcl/:
2017-04-03.tcl 30610 bytes Apr 03, 2017 21:55:37
2017-04-04.tcl 67996 bytes Apr 04, 2017 21:57:01
...
Contents (eg 2017-01-19.tcl):
m 2017-01-19T23:01:02Z ijchain {*** Johannes13__ leaves}
m 2017-01-19T23:15:37Z ijchain {*** fahadash leaves}
m 2017-01-19T23:27:00Z ijchain {*** Buster leaves}
...
#<<<#
var [const] CURL=Import.lib("zklCurl")(); // libCurl instance
template:="http://tclers.tk/conferences/tcl/%4d-%02d-%02d.tcl";
ymd :=Time.Clock.UTC[0,3]; // now, (y,m,d)
back :=10; // days in the past
needle :=vm.nthArg(0); // search string
foreach d in ([-back+1..0]){ // we want day -9,-8,-7..0 (today)
date :=Time.Date.subYMD(ymd, 0,0,-d); // date minus days
url :=template.fmt(date.xplode());
haystack:=CURL.get(url); // (request bytes, header length)
haystack=haystack[0].del(0,haystack[1]); // remove HTML header
mentions:=haystack.filter("find",needle); // search lines
if(mentions) println("%s\n------\n%s------\n".fmt(url,mentions.text));
}
|
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.
|
#Scala
|
Scala
|
def encode(s: String) = (1 until s.size).foldLeft((1, s(0), new StringBuilder)) {
case ((len, c, sb), index) if c != s(index) => sb.append(len); sb.append(c); (1, s(index), sb)
case ((len, c, sb), _) => (len + 1, c, sb)
} match {
case (len, c, sb) => sb.append(len); sb.append(c); sb.toString
}
def decode(s: String) = {
val sb = new StringBuilder
val Code = """(\d+)([A-Z])""".r
for (Code(len, c) <- Code findAllIn s) sb.append(c * len.toInt)
sb.toString
}
|
http://rosettacode.org/wiki/RIPEMD-160
|
RIPEMD-160
|
RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code”.
You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
|
#Go
|
Go
|
package main
import (
"golang.org/x/crypto/ripemd160"
"fmt"
)
func main() {
h := ripemd160.New()
h.Write([]byte("Rosetta Code"))
fmt.Printf("%x\n", h.Sum(nil))
}
|
http://rosettacode.org/wiki/RIPEMD-160
|
RIPEMD-160
|
RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code”.
You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
|
#Haskell
|
Haskell
|
import Data.Char (ord)
import Crypto.Hash.RIPEMD160 (hash)
import Data.ByteString (unpack, pack)
import Text.Printf (printf)
main = putStrLn $ -- output to terminal
concatMap (printf "%02x") $ -- to hex string
unpack $ -- to array of Word8
hash $ -- RIPEMD-160 hash to ByteString
pack $ -- to ByteString
map (fromIntegral.ord) -- to array of Word8
"Rosetta Code"
|
http://rosettacode.org/wiki/Resistor_mesh
|
Resistor mesh
|
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
|
#11l
|
11l
|
-V DIFF_THRESHOLD = 1e-40
T.enum Fixed
FREE
A
B
T Node
Float voltage
Fixed fixed
F (v = 0.0, f = Fixed.FREE)
.voltage = v
.fixed = f
F set_boundary(&m)
m[1][1] = Node( 1.0, Fixed.A)
m[6][7] = Node(-1.0, Fixed.B)
F calc_difference(m, &d)
V h = m.len
V w = m[0].len
V total = 0.0
L(i) 0 .< h
L(j) 0 .< w
V v = 0.0
V n = 0
I i != 0 {v += m[i - 1][j].voltage; n++}
I j != 0 {v += m[i][j - 1].voltage; n++}
I i < h-1 {v += m[i + 1][j].voltage; n++}
I j < w-1 {v += m[i][j + 1].voltage; n++}
v = m[i][j].voltage - v / n
d[i][j].voltage = v
I m[i][j].fixed == FREE
total += v ^ 2
R total
F iter(&m)
V h = m.len
V w = m[0].len
V difference = [[Node()] * w] * h
L
set_boundary(&m)
I calc_difference(m, &difference) < :DIFF_THRESHOLD
L.break
L(di) difference
V i = L.index
L(dij) di
V j = L.index
m[i][j].voltage -= dij.voltage
V cur = [0.0] * 3
L(di) difference
V i = L.index
L(dij) di
V j = L.index
cur[Int(m[i][j].fixed)] += (dij.voltage *
(Int(i != 0) + Int(j != 0) + (i < h - 1) + (j < w - 1)))
R (cur[Int(Fixed.A)] - cur[Int(Fixed.B)]) / 2.0
V w = 10
V h = 10
V mesh = [[Node()] * w] * h
print(‘R = #.16’.format(2 / iter(&mesh)))
|
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
|
Respond to an unknown method call
|
Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#Elena
|
Elena
|
import extensions;
class Example
{
generic()
{
// __received is an built-in variable containing the incoming message name
console.printLine(__received," was invoked")
}
generic(x)
{
console.printLine(__received,"(",x,") was invoked")
}
generic(x,y)
{
console.printLine(__received,"(",x,",",y,") was invoked")
}
}
public program()
{
var o := new Example();
o.foo();
o.bar(1);
o.someMethod(1,2)
}
|
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
|
Respond to an unknown method call
|
Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#Fancy
|
Fancy
|
class CatchThemAll {
def foo {
"foo received" println
}
def bar {
"bar received" println
}
def unknown_message: msg with_params: params {
"message: " ++ msg print
"arguments: " ++ (params join: ", ") println
}
}
a = CatchThemAll new
a foo
a bar
a we_can_do_it
a they_can_too: "eat" and: "walk"
|
http://rosettacode.org/wiki/Reverse_words_in_a_string
|
Reverse words in a string
|
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified.
You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.
Some strings have no tokens, so an empty string (or one just containing spaces) would be the result.
Display the strings in order (1st, 2nd, 3rd, ···), and one string per line.
(You can consider the ten strings as ten lines, and the tokens as words.)
Input data
(ten lines within the box)
line
╔════════════════════════════════════════╗
1 ║ ---------- Ice and Fire ------------ ║
2 ║ ║ ◄─── a blank line here.
3 ║ fire, in end will world the say Some ║
4 ║ ice. in say Some ║
5 ║ desire of tasted I've what From ║
6 ║ fire. favor who those with hold I ║
7 ║ ║ ◄─── a blank line here.
8 ║ ... elided paragraph last ... ║
9 ║ ║ ◄─── a blank line here.
10 ║ Frost Robert ----------------------- ║
╚════════════════════════════════════════╝
Cf.
Phrase reversals
|
#Ada
|
Ada
|
package Simple_Parse is
-- a very simplistic parser, useful to split a string into words
function Next_Word(S: String; Point: in out Positive)
return String;
-- a "word" is a sequence of non-space characters
-- if S(Point .. S'Last) holds at least one word W
-- then Next_Word increments Point by len(W) and returns W.
-- else Next_Word sets Point to S'Last+1 and returns ""
end Simple_Parse;
|
http://rosettacode.org/wiki/Reverse_words_in_a_string
|
Reverse words in a string
|
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified.
You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.
Some strings have no tokens, so an empty string (or one just containing spaces) would be the result.
Display the strings in order (1st, 2nd, 3rd, ···), and one string per line.
(You can consider the ten strings as ten lines, and the tokens as words.)
Input data
(ten lines within the box)
line
╔════════════════════════════════════════╗
1 ║ ---------- Ice and Fire ------------ ║
2 ║ ║ ◄─── a blank line here.
3 ║ fire, in end will world the say Some ║
4 ║ ice. in say Some ║
5 ║ desire of tasted I've what From ║
6 ║ fire. favor who those with hold I ║
7 ║ ║ ◄─── a blank line here.
8 ║ ... elided paragraph last ... ║
9 ║ ║ ◄─── a blank line here.
10 ║ Frost Robert ----------------------- ║
╚════════════════════════════════════════╝
Cf.
Phrase reversals
|
#Aime
|
Aime
|
integer j;
list l, x;
text s, t;
l = list("---------- Ice and Fire ------------",
"",
"fire, in end will world the say Some",
"ice. in say Some",
"desire of tasted I've what From",
"fire. favor who those with hold I",
"",
"... elided paragraph last ...",
"",
"Frost Robert -----------------------");
for (, t in l) {
file().b_affix(t).list(x, 0);
for (j, s in x.reverse) {
o_space(sign(j));
o_text(s);
}
o_newline();
}
|
http://rosettacode.org/wiki/Repunit_primes
|
Repunit primes
|
Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In base two, the repunits 11, 111, 11111, 1111111, etc. are prime. (These correspond to the Mersenne primes.)
In base three: 111, 1111111, 1111111111111, etc.
Repunit primes, by definition, are also circular primes.
Any repunit in any base having a composite number of digits is necessarily composite. Only repunits (in any base) having a prime number of digits might be prime.
Rather than expanding the repunit out as a giant list of 1s or converting to base 10, it is common to just list the number of 1s in the repunit; effectively the digit count. The base two repunit primes listed above would be represented as: 2, 3, 5, 7, etc.
Many of these sequences exist on OEIS, though they aren't specifically listed as "repunit prime digits" sequences.
Some bases have very few repunit primes. Bases 4, 8, and likely 16 have only one. Base 9 has none at all. Bases above 16 may have repunit primes as well... but this task is getting large enough already.
Task
For bases 2 through 16, Find and show, here on this page, the repunit primes as digit counts, up to a limit of 1000.
Stretch
Increase the limit to 2700 (or as high as you have patience for.)
See also
Wikipedia: Repunit primes
OEIS:A000043 - Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime (base 2)
OEIS:A028491 - Numbers k such that (3^k - 1)/2 is prime (base 3)
OEIS:A004061 - Numbers n such that (5^n - 1)/4 is prime (base 5)
OEIS:A004062 - Numbers n such that (6^n - 1)/5 is prime (base 6)
OEIS:A004063 - Numbers k such that (7^k - 1)/6 is prime (base 7)
OEIS:A004023 - Indices of prime repunits: numbers n such that 11...111 (with n 1's) = (10^n - 1)/9 is prime (base 10)
OEIS:A005808 - Numbers k such that (11^k - 1)/10 is prime (base 11)
OEIS:A004064 - Numbers n such that (12^n - 1)/11 is prime (base 12)
OEIS:A016054 - Numbers n such that (13^n - 1)/12 is prime (base 13)
OEIS:A006032 - Numbers k such that (14^k - 1)/13 is prime (base 14)
OEIS:A006033 - Numbers n such that (15^n - 1)/14 is prime (base 15)
Related task: Circular primes
|
#Phix
|
Phix
|
with javascript_semantics
include mpfr.e
procedure repunit(mpz z, integer n, base=10)
mpz_set_si(z,0)
for i=1 to n do
mpz_mul_si(z,z,base)
mpz_add_si(z,z,1)
end for
end procedure
atom t0 = time()
constant {limit,blimit} = iff(platform()=JS?{400,16} -- 8.8s
:{1000,16}) -- 50.3s
-- :{1000,36}) -- 4 min 20s
-- :{2700,16}) -- 28 min 35s
-- :{2700,36}) -- >patience
sequence primes = get_primes_le(limit)
mpz z = mpz_init()
for base=2 to blimit do
sequence rprimes = {}
for i=1 to length(primes) do
integer p = primes[i]
repunit(z,p,base)
if mpz_prime(z) then
rprimes = append(rprimes,sprint(p))
end if
end for
printf(1,"Base %2d: %s\n", {base, join(rprimes)})
end for
?elapsed(time()-t0)
|
http://rosettacode.org/wiki/Repunit_primes
|
Repunit primes
|
Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In base two, the repunits 11, 111, 11111, 1111111, etc. are prime. (These correspond to the Mersenne primes.)
In base three: 111, 1111111, 1111111111111, etc.
Repunit primes, by definition, are also circular primes.
Any repunit in any base having a composite number of digits is necessarily composite. Only repunits (in any base) having a prime number of digits might be prime.
Rather than expanding the repunit out as a giant list of 1s or converting to base 10, it is common to just list the number of 1s in the repunit; effectively the digit count. The base two repunit primes listed above would be represented as: 2, 3, 5, 7, etc.
Many of these sequences exist on OEIS, though they aren't specifically listed as "repunit prime digits" sequences.
Some bases have very few repunit primes. Bases 4, 8, and likely 16 have only one. Base 9 has none at all. Bases above 16 may have repunit primes as well... but this task is getting large enough already.
Task
For bases 2 through 16, Find and show, here on this page, the repunit primes as digit counts, up to a limit of 1000.
Stretch
Increase the limit to 2700 (or as high as you have patience for.)
See also
Wikipedia: Repunit primes
OEIS:A000043 - Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime (base 2)
OEIS:A028491 - Numbers k such that (3^k - 1)/2 is prime (base 3)
OEIS:A004061 - Numbers n such that (5^n - 1)/4 is prime (base 5)
OEIS:A004062 - Numbers n such that (6^n - 1)/5 is prime (base 6)
OEIS:A004063 - Numbers k such that (7^k - 1)/6 is prime (base 7)
OEIS:A004023 - Indices of prime repunits: numbers n such that 11...111 (with n 1's) = (10^n - 1)/9 is prime (base 10)
OEIS:A005808 - Numbers k such that (11^k - 1)/10 is prime (base 11)
OEIS:A004064 - Numbers n such that (12^n - 1)/11 is prime (base 12)
OEIS:A016054 - Numbers n such that (13^n - 1)/12 is prime (base 13)
OEIS:A006032 - Numbers k such that (14^k - 1)/13 is prime (base 14)
OEIS:A006033 - Numbers n such that (15^n - 1)/14 is prime (base 15)
Related task: Circular primes
|
#Python
|
Python
|
from sympy import isprime
for b in range(2, 17):
print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])
|
http://rosettacode.org/wiki/Rot-13
|
Rot-13
|
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of 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
|
#Modula-2
|
Modula-2
|
MODULE Rot13;
FROM STextIO IMPORT
ReadString, WriteString, WriteLn;
FROM Strings IMPORT
Length;
TYPE
MyString = ARRAY [0..80] OF CHAR;
VAR
S, T : MyString;
PROCEDURE Rot13(S : ARRAY OF CHAR; VAR T : ARRAY OF CHAR);
VAR
I, J : CARDINAL;
BEGIN
FOR I := 0 TO Length(S) - 1
DO
J := ORD(S[I]);
IF ((J >= 65) AND (J <= 90)) THEN
J := (J - 52) % 26 + 65;
IF ((J >= 97) AND (J <= 122)) THEN
J := (J - 84) % 26 + 97;
T[I] := CHR(J);
END;
END Rot13;
BEGIN
WHILE NOT Eof
DO
ReadString(S);
SkipLine;
WriteLn;
Rot13(S, T);
WriteString(T);
WriteLn;
END;
END Rot13.
|
http://rosettacode.org/wiki/Roman_numerals/Encode
|
Roman numerals/Encode
|
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman 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
|
#LiveCode
|
LiveCode
|
function toRoman intNum
local roman,numArabic
put "M,CM,D,CD,C,XC,L,XL,X,IX,V,IV,I" into romans
put "1000,900,500,400,100,90,50,40,10,9,5,4,1" into arabics
put intNum into numArabic
repeat with n = 1 to the number of items of romans
put numArabic div item n of arabics into nums
if nums > 0 then
put repeatChar(item n of romans,nums) after roman
add -(nums * item n of arabics) to numArabic
end if
end repeat
return roman
end toRoman
function repeatChar c n
local cc
repeat n times
put c after cc
end repeat
return cc
end repeatChar
|
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.
|
#NetRexx
|
NetRexx
|
/* NetRexx */
options replace format comments java crossref savelog symbols binary
/* 1990 2008 1666 */
years = Rexx('MCMXC MMVIII MDCLXVI')
loop y_ = 1 to years.words
Say years.word(y_).right(10) || ':' decode(years.word(y_))
end y_
return
method decode(arg) public static returns int signals IllegalArgumentException
parse arg.upper roman .
if roman.verify('MDCLXVI') \= 0 then signal IllegalArgumentException
-- always insert the value of the least significant numeral
decnum = rchar(roman.substr(roman.length, 1))
loop d_ = 1 to roman.length - 1
if rchar(roman.substr(d_, 1)) < rchar(roman.substr(d_ + 1, 1)) then do
-- Handle cases where numerals are not in descending order
-- subtract the value of the numeral
decnum = decnum - rchar(roman.substr(d_, 1))
end
else do
-- Normal case
-- add the value of the numeral
decnum = decnum + rchar(roman.substr(d_, 1))
end
end d_
return decnum
method rchar(arg) public static returns int
parse arg.upper ch +1 .
select case ch
when 'M' then digit = 1000
when 'D' then digit = 500
when 'C' then digit = 100
when 'L' then digit = 50
when 'X' then digit = 10
when 'V' then digit = 5
when 'I' then digit = 1
otherwise digit = 0
end
return digit
|
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.
|
#Scheme
|
Scheme
|
(define (run-length-decode v)
(apply string-append (map (lambda (p) (make-string (car p) (cdr p))) v)))
(define (run-length-encode s)
(let ((n (string-length s)))
(let loop ((i (- n 2)) (c (string-ref s (- n 1))) (k 1) (v '()))
(if (negative? i) (cons (cons k c) v)
(let ((x (string-ref s i)))
(if (char=? c x) (loop (- i 1) c (+ k 1) v)
(loop (- i 1) x 1 (cons (cons k c) v))))))))
(run-length-encode "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW")
; ((12 . #\W) (1 . #\B) (12 . #\W) (3 . #\B) (24 . #\W) (1 . #\B) (14 . #\W))
(run-length-decode '((12 . #\W) (1 . #\B) (12 . #\W) (3 . #\B) (24 . #\W) (1 . #\B) (14 . #\W)))
; "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
|
http://rosettacode.org/wiki/Return_multiple_values
|
Return multiple values
|
Task
Show how to return more than one value from a function.
|
#11l
|
11l
|
F addsub(x, y)
R (x + y, x - y)
V (summ, difference) = addsub(33, 12)
print(‘33 + 12 = ’summ)
print(‘33 - 12 = ’difference)
|
http://rosettacode.org/wiki/RIPEMD-160
|
RIPEMD-160
|
RIPEMD-160 is another hash function; it computes a 160-bit message digest.
There is a RIPEMD-160 home page, with test vectors and pseudocode for RIPEMD-160.
For padding the message, RIPEMD-160 acts like MD4 (RFC 1320).
Find the RIPEMD-160 message digest of a string of octets.
Use the ASCII encoded string “Rosetta Code”.
You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language.
|
#Java
|
Java
|
import org.bouncycastle.crypto.digests.RIPEMD160Digest;
import org.bouncycastle.util.encoders.Hex;
public class RosettaRIPEMD160
{
public static void main (String[] argv) throws Exception
{
byte[] r = "Rosetta Code".getBytes("US-ASCII");
RIPEMD160Digest d = new RIPEMD160Digest();
d.update (r, 0, r.length);
byte[] o = new byte[d.getDigestSize()];
d.doFinal (o, 0);
Hex.encode (o, System.out);
System.out.println();
}
}
|
http://rosettacode.org/wiki/Resistor_mesh
|
Resistor mesh
|
Task
Given 10×10 grid nodes (as shown in the image) interconnected by 1Ω resistors as shown,
find the resistance between points A and B.
See also
(humor, nerd sniping) xkcd.com cartoon
|
#Ada
|
Ada
|
with Ada.Text_IO; use Ada.Text_IO;
procedure ResistMesh is
H, W : constant Positive := 10;
rowA, colA : constant Positive := 2; -- row/col indexed from 1
rowB : constant Positive := 7;
colB : constant Positive := 8;
type Ntype is (A, B, Free);
type Vtype is digits 15;
type Node is record
volt : Vtype := 0.0;
name : Ntype := Free;
end record;
type NodeMesh is array (Positive range <>, Positive range <>) of Node;
package IIO is new Ada.Text_IO.Float_IO (Vtype);
mesh, dmesh : NodeMesh (1 .. H, 1 .. W);
curA, curB, diff : Vtype;
procedure set_AB (mesh : in out NodeMesh) is begin
mesh (rowA, colA).volt := 1.0; mesh (rowA, colA).name := A;
mesh (rowB, colB).volt := -1.0; mesh (rowB, colB).name := B;
end set_AB;
function sides (i : Positive; j : Positive) return Vtype is
s : Integer := 0;
begin
if i /= 1 and i /= H then s := s + 2; else s := s + 1; end if;
if j /= 1 and j /= W then s := s + 2; else s := s + 1; end if;
return Vtype (s);
end sides;
procedure calc_diff (mesh : NodeMesh; dmesh : out NodeMesh;
total : out Vtype) is
n : Natural;
v : Vtype := 0.0;
begin
total := 0.0;
for i in Positive range 1 .. H loop
for j in Positive range 1 .. W loop
n := 0; v := 0.0;
if i /= 1 then v := v + mesh (i - 1, j).volt; n := n + 1; end if;
if j /= 1 then v := v + mesh (i, j - 1).volt; n := n + 1; end if;
if i < H then v := v + mesh (i + 1, j).volt; n := n + 1; end if;
if j < W then v := v + mesh (i, j + 1).volt; n := n + 1; end if;
v := mesh (i, j).volt - v / Vtype (n);
dmesh (i, j).volt := v;
if mesh (i, j).name = Free then total := total + v ** 2; end if;
end loop;
end loop;
end calc_diff;
begin
loop
set_AB (mesh);
calc_diff (mesh, dmesh, diff);
exit when diff < 1.0e-40;
for i in Positive range 1 .. H loop
for j in Positive range 1 .. W loop
mesh (i, j).volt := mesh (i, j).volt - dmesh (i, j).volt;
end loop;
end loop;
end loop;
curA := dmesh (rowA, colA).volt * sides (rowA, colA);
curB := dmesh (rowB, colB).volt * sides (rowB, colB);
diff := 4.0 / (curA - curB);
IIO.Put (diff, Exp => 0); New_Line;
end ResistMesh;
|
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
|
Respond to an unknown method call
|
Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#Fantom
|
Fantom
|
class A
{
public Void doit (Int n)
{
echo ("known function called on $n")
}
// override the 'trap' method, which catches dynamic invocations of methods
override Obj? trap(Str name, Obj?[]? args := null)
{
try
{
return super.trap(name, args)
}
catch (UnknownSlotErr err)
{
echo ("In trap, you called: " + name + " with args " + args.join(","))
return null
}
}
}
class Main
{
public static Void main ()
{
a := A()
// note the dynamic dispatch
a->doit (1)
a->methodName (1, 2, 3)
}
}
|
http://rosettacode.org/wiki/Respond_to_an_unknown_method_call
|
Respond to an unknown method call
|
Task
Demonstrate how to make the object respond (sensibly/usefully) to an invocation of a method on it that it does not support through its class definitions.
Note that this is not the same as just invoking a defined method whose name is given dynamically; the method named at the point of invocation must not be defined.
This task is intended only for object systems that use a dynamic dispatch mechanism without static checking.
Related task
Send an unknown method call.
|
#Forth
|
Forth
|
include FMS-SI.f
include FMS-SILib.f
var x \ instantiate a class var object named x
x add: \ => "aborted: message not understood"
|
http://rosettacode.org/wiki/Reverse_words_in_a_string
|
Reverse words in a string
|
Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified.
You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.
Some strings have no tokens, so an empty string (or one just containing spaces) would be the result.
Display the strings in order (1st, 2nd, 3rd, ···), and one string per line.
(You can consider the ten strings as ten lines, and the tokens as words.)
Input data
(ten lines within the box)
line
╔════════════════════════════════════════╗
1 ║ ---------- Ice and Fire ------------ ║
2 ║ ║ ◄─── a blank line here.
3 ║ fire, in end will world the say Some ║
4 ║ ice. in say Some ║
5 ║ desire of tasted I've what From ║
6 ║ fire. favor who those with hold I ║
7 ║ ║ ◄─── a blank line here.
8 ║ ... elided paragraph last ... ║
9 ║ ║ ◄─── a blank line here.
10 ║ Frost Robert ----------------------- ║
╚════════════════════════════════════════╝
Cf.
Phrase reversals
|
#ALGOL_68
|
ALGOL 68
|
# returns original phrase with the order of the words reversed #
# a word is a sequence of non-blank characters #
PROC reverse word order = ( STRING original phrase )STRING:
BEGIN
STRING words reversed := "";
STRING separator := "";
INT start pos := LWB original phrase;
WHILE
# skip leading spaces #
WHILE IF start pos <= UPB original phrase
THEN original phrase[ start pos ] = " "
ELSE FALSE
FI
DO start pos +:= 1
OD;
start pos <= UPB original phrase
DO
# have another word, find it #
INT end pos := start pos;
WHILE IF end pos <= UPB original phrase
THEN original phrase[ end pos ] /= " "
ELSE FALSE
FI
DO end pos +:= 1
OD;
( original phrase[ start pos : end pos - 1 ] + separator ) +=: words reversed;
separator := " ";
start pos := end pos + 1
OD;
words reversed
END # reverse word order # ;
# reverse the words in the lines as per the task #
print( ( reverse word order ( "--------- Ice and Fire ------------ " ), newline ) );
print( ( reverse word order ( " " ), newline ) );
print( ( reverse word order ( "fire, in end will world the say Some" ), newline ) );
print( ( reverse word order ( "ice. in say Some " ), newline ) );
print( ( reverse word order ( "desire of tasted I've what From " ), newline ) );
print( ( reverse word order ( "fire. favor who those with hold I " ), newline ) );
print( ( reverse word order ( " " ), newline ) );
print( ( reverse word order ( "... elided paragraph last ... " ), newline ) );
print( ( reverse word order ( " " ), newline ) );
print( ( reverse word order ( "Frost Robert -----------------------" ), newline ) )
|
http://rosettacode.org/wiki/Repunit_primes
|
Repunit primes
|
Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In base two, the repunits 11, 111, 11111, 1111111, etc. are prime. (These correspond to the Mersenne primes.)
In base three: 111, 1111111, 1111111111111, etc.
Repunit primes, by definition, are also circular primes.
Any repunit in any base having a composite number of digits is necessarily composite. Only repunits (in any base) having a prime number of digits might be prime.
Rather than expanding the repunit out as a giant list of 1s or converting to base 10, it is common to just list the number of 1s in the repunit; effectively the digit count. The base two repunit primes listed above would be represented as: 2, 3, 5, 7, etc.
Many of these sequences exist on OEIS, though they aren't specifically listed as "repunit prime digits" sequences.
Some bases have very few repunit primes. Bases 4, 8, and likely 16 have only one. Base 9 has none at all. Bases above 16 may have repunit primes as well... but this task is getting large enough already.
Task
For bases 2 through 16, Find and show, here on this page, the repunit primes as digit counts, up to a limit of 1000.
Stretch
Increase the limit to 2700 (or as high as you have patience for.)
See also
Wikipedia: Repunit primes
OEIS:A000043 - Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime (base 2)
OEIS:A028491 - Numbers k such that (3^k - 1)/2 is prime (base 3)
OEIS:A004061 - Numbers n such that (5^n - 1)/4 is prime (base 5)
OEIS:A004062 - Numbers n such that (6^n - 1)/5 is prime (base 6)
OEIS:A004063 - Numbers k such that (7^k - 1)/6 is prime (base 7)
OEIS:A004023 - Indices of prime repunits: numbers n such that 11...111 (with n 1's) = (10^n - 1)/9 is prime (base 10)
OEIS:A005808 - Numbers k such that (11^k - 1)/10 is prime (base 11)
OEIS:A004064 - Numbers n such that (12^n - 1)/11 is prime (base 12)
OEIS:A016054 - Numbers n such that (13^n - 1)/12 is prime (base 13)
OEIS:A006032 - Numbers k such that (14^k - 1)/13 is prime (base 14)
OEIS:A006033 - Numbers n such that (15^n - 1)/14 is prime (base 15)
Related task: Circular primes
|
#Raku
|
Raku
|
my $limit = 2700;
say "Repunit prime digits (up to $limit) in:";
.put for (2..16).hyper(:1batch).map: -> $base {
$base.fmt("Base %2d: ") ~ (1..$limit).grep(&is-prime).grep( (1 x *).parse-base($base).is-prime )
}
|
http://rosettacode.org/wiki/Repunit_primes
|
Repunit primes
|
Repunit is a portmanteau of the words "repetition" and "unit", with unit being "unit value"... or in laymans terms, 1. So 1, 11, 111, 1111 & 11111 are all repunits.
Every standard integer base has repunits since every base has the digit 1. This task involves finding the repunits in different bases that are prime.
In base two, the repunits 11, 111, 11111, 1111111, etc. are prime. (These correspond to the Mersenne primes.)
In base three: 111, 1111111, 1111111111111, etc.
Repunit primes, by definition, are also circular primes.
Any repunit in any base having a composite number of digits is necessarily composite. Only repunits (in any base) having a prime number of digits might be prime.
Rather than expanding the repunit out as a giant list of 1s or converting to base 10, it is common to just list the number of 1s in the repunit; effectively the digit count. The base two repunit primes listed above would be represented as: 2, 3, 5, 7, etc.
Many of these sequences exist on OEIS, though they aren't specifically listed as "repunit prime digits" sequences.
Some bases have very few repunit primes. Bases 4, 8, and likely 16 have only one. Base 9 has none at all. Bases above 16 may have repunit primes as well... but this task is getting large enough already.
Task
For bases 2 through 16, Find and show, here on this page, the repunit primes as digit counts, up to a limit of 1000.
Stretch
Increase the limit to 2700 (or as high as you have patience for.)
See also
Wikipedia: Repunit primes
OEIS:A000043 - Mersenne exponents: primes p such that 2^p - 1 is prime. Then 2^p - 1 is called a Mersenne prime (base 2)
OEIS:A028491 - Numbers k such that (3^k - 1)/2 is prime (base 3)
OEIS:A004061 - Numbers n such that (5^n - 1)/4 is prime (base 5)
OEIS:A004062 - Numbers n such that (6^n - 1)/5 is prime (base 6)
OEIS:A004063 - Numbers k such that (7^k - 1)/6 is prime (base 7)
OEIS:A004023 - Indices of prime repunits: numbers n such that 11...111 (with n 1's) = (10^n - 1)/9 is prime (base 10)
OEIS:A005808 - Numbers k such that (11^k - 1)/10 is prime (base 11)
OEIS:A004064 - Numbers n such that (12^n - 1)/11 is prime (base 12)
OEIS:A016054 - Numbers n such that (13^n - 1)/12 is prime (base 13)
OEIS:A006032 - Numbers k such that (14^k - 1)/13 is prime (base 14)
OEIS:A006033 - Numbers n such that (15^n - 1)/14 is prime (base 15)
Related task: Circular primes
|
#Scheme
|
Scheme
|
; Test whether any integer is a probable prime.
(define prime<probably>?
(lambda (n)
; Fast modular exponentiation.
(define modexpt
(lambda (b e m)
(cond
((zero? e) 1)
((even? e) (modexpt (mod (* b b) m) (div e 2) m))
((odd? e) (mod (* b (modexpt b (- e 1) m)) m)))))
; Return multiple values s, d such that d is odd and 2^s * d = n.
(define split
(lambda (n)
(let recur ((s 0) (d n))
(if (odd? d)
(values s d)
(recur (+ s 1) (div d 2))))))
; Test whether the number a proves that n is composite.
(define composite-witness?
(lambda (n a)
(let*-values (((s d) (split (- n 1)))
((x) (modexpt a d n)))
(and (not (= x 1))
(not (= x (- n 1)))
(let try ((r (- s 1)))
(set! x (modexpt x 2 n))
(or (zero? r)
(= x 1)
(and (not (= x (- n 1)))
(try (- r 1)))))))))
; Test whether n > 2 is a Miller-Rabin pseudoprime, k trials.
(define pseudoprime?
(lambda (n k)
(or (zero? k)
(let ((a (+ 2 (random (- n 2)))))
(and (not (composite-witness? n a))
(pseudoprime? n (- k 1)))))))
; Compute and return Probable Primality using the Miller-Rabin algorithm.
(and (> n 1)
(or (= n 2)
(and (odd? n)
(pseudoprime? n 50))))))
|
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
|
#Modula-3
|
Modula-3
|
MODULE Rot13 EXPORTS Main;
IMPORT Stdio, Rd, Wr;
VAR c: CHAR;
<*FATAL ANY*>
BEGIN
WHILE NOT Rd.EOF(Stdio.stdin) DO
c := Rd.GetChar(Stdio.stdin);
IF c >= 'A' AND c <= 'M' OR c >= 'a' AND c <= 'm' THEN
c := VAL(ORD((ORD(c) + 13)), CHAR);
ELSIF c >= 'N' AND c <= 'Z' OR c >= 'n' AND c <= 'z' THEN
c := VAL(ORD((ORD(c) - 13)), CHAR);
END;
Wr.PutChar(Stdio.stdout, c);
END;
END Rot13.
|
http://rosettacode.org/wiki/Roman_numerals/Encode
|
Roman numerals/Encode
|
Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman 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
|
#Logo
|
Logo
|
make "roman.rules [
[1000 M] [900 CM] [500 D] [400 CD]
[ 100 C] [ 90 XC] [ 50 L] [ 40 XL]
[ 10 X] [ 9 IX] [ 5 V] [ 4 IV]
[ 1 I]
]
to roman :n [:rules :roman.rules] [:acc "||]
if empty? :rules [output :acc]
if :n < first first :rules [output (roman :n bf :rules :acc)]
output (roman :n - first first :rules :rules word :acc last first :rules)
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.
|
#Nim
|
Nim
|
import tables
let rdecode = {'M': 1000, 'D': 500, 'C': 100, 'L': 50, 'X': 10, 'V': 5, 'I': 1}.toTable
proc decode(roman: string): int =
for i in 0 ..< roman.high:
let (rd, rd1) = (rdecode[roman[i]], rdecode[roman[i+1]])
result += (if rd < rd1: -rd else: rd)
result += rdecode[roman[roman.high]]
for r in ["MCMXC", "MMVIII", "MDCLXVI"]:
echo r, " ", decode(r)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.