task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #Pike | Pike | import String;
int main(){
write(int2roman(2009) + "\n");
write(int2roman(1666) + "\n");
write(int2roman(1337) + "\n");
} |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Run_BASIC | Run BASIC | print "MCMXCIX = "; romToDec( "MCMXCIX") '1999
print "MDCLXVI = "; romToDec( "MDCLXVI") '1666
print "XXV = "; romToDec( "XXV") '25
print "CMLIV = "; romToDec( "CMLIV") '954
print "MMXI = "; romToDec( "MMXI") '2011
function romToDec(roman$)
for i = len(roman$) to 1 step -1
x$ = mid$(roman$, ... |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #Brat | Brat | p "ha" * 5 #Prints "hahahahaha" |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #Burlesque | Burlesque |
blsq ) 'h5?*
"hhhhh"
blsq ) "ha"5.*\[
"hahahahaha"
|
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #F.23 | F# | let addSub x y = x + y, x - y
let sum, diff = addSub 33 12
printfn "33 + 12 = %d" sum
printfn "33 - 12 = %d" diff |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Factor | Factor | USING: io kernel math prettyprint ;
IN: script
: */ ( x y -- x*y x/y )
[ * ] [ / ] 2bi ;
15 3 */
[ "15 * 3 = " write . ]
[ "15 / 3 = " write . ] bi* |
http://rosettacode.org/wiki/Remove_duplicate_elements | Remove duplicate elements |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #AppleScript | AppleScript | unique({1, 2, 3, "a", "b", "c", 2, 3, 4, "b", "c", "d"})
on unique(x)
set R to {}
repeat with i in x
if i is not in R then set end of R to i's contents
end repeat
return R
end unique |
http://rosettacode.org/wiki/Recaman%27s_sequence | Recaman's sequence | The Recamán's sequence generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated.
If the conditions don't hold then a(n) = a(n-1) + n.
Task
Generate and show here the... | #ALGOL_W | ALGOL W | begin
% calculate Recaman's sequence values %
% a hash table element - holds n, A(n) and a link to the next element with the %
% same hash value %
record AValue ( integer eN, eAn ; referen... |
http://rosettacode.org/wiki/Recaman%27s_sequence | Recaman's sequence | The Recamán's sequence generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated.
If the conditions don't hold then a(n) = a(n-1) + n.
Task
Generate and show here the... | #APL | APL | recaman←{⎕IO←0
genNext←{
R←⍵[N-1]-N←≢⍵
(R<0)∨(R∊⍵):⍵,⍵[N-1]+N
⍵,⍵[N-1]-N
}
⎕←'First 15: '
⎕←reca←(genNext⍣14),0
⎕←'First repetition: '
⎕←⊃⌽reca←genNext⍣{⍺≢∪⍺}⊢reca
⎕←'Length of sequence containing [0..1000]:'
⎕←≢reca←genNext⍣{(⍳1001)∧.∊⊂⍺}⊢reca
} |
http://rosettacode.org/wiki/Remove_lines_from_a_file | Remove lines from a file | Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th... | #AWK | AWK |
# syntax: GAWK -f REMOVE_LINES_FROM_A_FILE.AWK
# show files after lines are removed:
# GAWK "FNR==1{print(FILENAME)};{print(FNR,$0)}" TEST1 TEST2 TEST3
BEGIN {
build_test_data()
remove_lines("TEST0",1,1)
remove_lines("TEST1",3,4)
remove_lines("TEST2",9,3)
remove_lines("TEST3",11,1)
exit(erro... |
http://rosettacode.org/wiki/Record_sound | Record sound | Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs migh... | #Diego | Diego | begin_funct({wav}, Record sound);
set_decision(linger);
find_thing()_first()_microphone()_bitrate(16)_tech(PCM)_samplerate(signed16, unsigned16)_rangefrom(8000, Hz)_rangeto(44100, Hz)_export(.wav)
? with_found()_microphone()_label(mic);
: err_funct[]_err(Sorry, no one has a microphone!);
... |
http://rosettacode.org/wiki/Record_sound | Record sound | Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs migh... | #GUISS | GUISS | Start,Programs,Accessories,Sound Recorder,Button:Record |
http://rosettacode.org/wiki/Record_sound | Record sound | Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs migh... | #Julia | Julia |
using PortAudio, LibSndFile
stream = PortAudioStream("Microphone (USB Microphone)", 1, 0) # 44100 samples/sec
buf = read(stream, 441000)
save("recorded10sec.wav", buf)
|
http://rosettacode.org/wiki/Record_sound | Record sound | Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs migh... | #Kotlin | Kotlin | // version 1.1.3
import java.io.File
import javax.sound.sampled.*
const val RECORD_TIME = 20000L // twenty seconds say
fun main(args: Array<String>) {
val wavFile = File("RecordAudio.wav")
val fileType = AudioFileFormat.Type.WAVE
val format = AudioFormat(16000.0f, 16, 2, true, true)
val info = Dat... |
http://rosettacode.org/wiki/Read_entire_file | Read entire file | Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case... | #11l | 11l | File(filename).read() |
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #Lingo | Lingo | -- parent script "MyClass"
on foo (me)
put "foo"
end
on bar (me)
put "bar"
end |
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #Lua | Lua | function helloWorld()
print "Hello World"
end
-- Will list all functions in the given table, but does not recurse into nexted tables
function printFunctions(t)
local s={}
local n=0
for k in pairs(t) do
n=n+1 s[n]=k
end
table.sort(s)
for k,v in ipairs(s) do
f = t[v]
... |
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #Nanoquery | Nanoquery | // create a class with methods that will be listed
class Methods
def static method1()
return "this is a static method. it will not be printed"
end
def method2()
return "this is not a static method"
end
def operator=(other)
// operator methods are listed by both their defined name and
// by their internal... |
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #Phix | Phix | class c nullable
integer int = 1
public atom atm = 2.3
string str = "4point5"
sequence seq
public:
object obj = {"an object"}
c child
private function foo();
public procedure bar();
end class
c c_instance = new()
include builtins\structs.e as structs
function nulls(object s) return... |
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #PHP | PHP | <?
class Foo {
}
$obj = new Foo();
$obj->bar = 42;
$obj->baz = true;
var_dump(get_object_vars($obj));
?> |
http://rosettacode.org/wiki/Rep-string | Rep-string | Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For e... | #Crystal | Crystal | def rep(s : String) : Int32
x = s.size // 2
while x > 0
return x if s.starts_with? s[x..]
x -= 1
end
0
end
def main
%w(
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1
).each do |s|
n = rep s
puts n > 0 ?... |
http://rosettacode.org/wiki/Regular_expressions | Regular expressions |
Task
match a string against a regular expression
substitute part of a string using a regular expression
| #Delphi | Delphi |
program Regular_expressions;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.RegularExpressions;
const
CPP_IF = '\s*if\s*\(\s*(?<COND>.*)\s*\)\s*\{\s*return\s+(?<RETURN>.+);\s*\}';
PASCAL_IF = 'If ${COND} then result:= ${RETURN};';
var
RegularExpression: TRegEx;
str: string;
begin
s... |
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
... | #Applesoft_BASIC | Applesoft BASIC | 10 A$ = "THE FIVE BOXING WIZARDS JUMP QUICKLY"
20 GOSUB 100REVERSE
30 PRINT R$
40 END
100 REMREVERSE A$
110 R$ = ""
120 FOR I = 1 TO LEN(A$)
130 R$ = MID$(A$, I, 1) + R$
140 NEXT I
150 RETURN |
http://rosettacode.org/wiki/Repeat | Repeat | Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| #Isabelle | Isabelle | theory Scratch
imports Main
begin
text‹
Given the function we want to execute multiple times is of
type \<^typ>‹unit ⇒ unit›.
›
fun pure_repeat :: "(unit ⇒ unit) ⇒ nat ⇒ unit" where
"pure_repeat _ 0 = ()"
| "pure_repeat f (Suc n) = f (pure_repeat f n)"
text‹
Functions are pure in Isabelle. They don't have side ... |
http://rosettacode.org/wiki/Repeat | Repeat | Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| #J | J |
NB. ^: (J's power conjunction) repeatedly evaluates a verb.
NB. Appending to a vector the sum of the most recent
NB. 2 items can generate the Fibonacci sequence.
(, [: +/ _2&{.) (^:4) 0 1
0 1 1 2 3 5
NB. Repeat an infinite number of times
NB. computes the stable point at convergence
c... |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #Factor | Factor | "" "/" [
[ "input.txt" "output.txt" move-file "docs" "mydocs" move-file ] with-directory
] bi@ |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #Fantom | Fantom |
class Rename
{
public static Void main ()
{
// rename file/dir in current directory
File.rename("input.txt".toUri).rename("output.txt")
File.rename("docs/".toUri).rename("mydocs/")
// rename file/dir in root directory
File.rename("/input.txt".toUri).rename("/output.txt")
File.rename("/docs... |
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
| #XPL0 | XPL0 | code real RlRes=46, RlOut=48;
def S = 10;
proc SetBoundary(MV, MF);
real MV; int MF;
[MF(1,1):= 1; MV(1,1):= 1.0;
MF(6,7):= -1; MV(6,7):= -1.0;
];
func real CalcDiff(MV, MF, DV, W, H);
real MV; int MF; real DV; int W, H;
int I, J, N; real V, Total;
[Total:= 0.0;
for I:= 0 to H-1 do
for J:= 0 to W-1 do
... |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #Frink | Frink |
lines=split["\n",
"""---------- 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 line = lines
println[join[" ", reverse[split[%r/\s... |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #FutureBasic | FutureBasic |
include "NSLog.incl"
CFStringRef frostStr
CFArrayRef frostArr, tempArr
CFMutableStringRef mutStr
NSInteger i, count
frostStr = @"---------- Ice and Fire ------------\n¬
\n¬
fire, in end will world the say Some\n¬
ice. in say Some\n¬
desire of tasted I've what From\n¬
fire. favor who those ... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #PureBasic | PureBasic | Declare.s Rot13(text_to_code.s)
If OpenConsole()
Define txt$
Print("Enter a string to encode: "): txt$=Input()
PrintN("Coded : "+Rot13(txt$))
PrintN("Decoded: "+Rot13(Rot13(txt$)))
Print("Press ENTER to quit."): Input()
CloseConsole()
EndIf
Procedure.s Rot13(s.s)
Protected.i i
Protected.s t, ... |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #PL.2FI | PL/I |
/* From Wiki Fortran */
roman: procedure (n) returns(character (32) varying);
declare n fixed binary nonassignable;
declare (d, m) fixed binary;
declare (r, m_div) character (32) varying;
declare d_dec(13) fixed binary static initial
(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1);
declare... |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Rust | Rust | struct RomanNumeral {
symbol: &'static str,
value: u32
}
const NUMERALS: [RomanNumeral; 13] = [
RomanNumeral {symbol: "M", value: 1000},
RomanNumeral {symbol: "CM", value: 900},
RomanNumeral {symbol: "D", value: 500},
RomanNumeral {symbol: "CD", value: 400},
RomanNumeral {symbol: "C", v... |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * string_repeat( int n, const char * s ) {
size_t slen = strlen(s);
char * dest = malloc(n*slen+1);
int i; char * p;
for ( i=0, p = dest; i < n; ++i, p += slen ) {
memcpy(p, s, slen);
}
*p = '\0';
return dest;
}
int main() {
char ... |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #FALSE | FALSE | [\$@$@*@@/]f: { in: a b, out: a*b a/b }
6 2f;! .` ,. { 3 12 } |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Forth | Forth | : muldiv ( a b -- a*b a/b )
2dup / >r * r> ; |
http://rosettacode.org/wiki/Remove_duplicate_elements | Remove duplicate elements |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Applesoft_BASIC | Applesoft BASIC | 100 DIM L$(15)
110 L$(0) = "NOW"
120 L$(1) = "IS"
130 L$(2) = "THE"
140 L$(3) = "TIME"
150 L$(4) = "FOR"
160 L$(5) = "ALL"
170 L$(6) = "GOOD"
180 L$(7) = "MEN"
190 L$(8) = "TO"
200 L$(9) = "COME"
210 L$(10) = "TO"
220 L$(11) = "THE"
230 L$(12) = "AID"
240 L$(13) = "OF"
250 L$(14) = "THE"
260 L$(15) = "PARTY."
300 N =... |
http://rosettacode.org/wiki/Recaman%27s_sequence | Recaman's sequence | The Recamán's sequence generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated.
If the conditions don't hold then a(n) = a(n-1) + n.
Task
Generate and show here the... | #AppleScript | AppleScript | use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
on run
-- FIRST FIFTEEN RECAMANs ------------------------------------------------------
script term15
on |λ|(i)
15 = (i as integer)
end |λ|
end script
set strFirst15 to unwords(snd(recamanUpto(true, term15)))
... |
http://rosettacode.org/wiki/Remove_lines_from_a_file | Remove lines from a file | Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th... | #BASIC | BASIC |
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
' Remove File Lines V1.1 '
' '
' Developed by A. David Garza Marín in VB-DOS for '
' RosettaCode. November 30, 2016. '
' ... |
http://rosettacode.org/wiki/Record_sound | Record sound | Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs migh... | #Liberty_BASIC | Liberty BASIC |
run "sndrec32.exe"
|
http://rosettacode.org/wiki/Record_sound | Record sound | Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs migh... | #LiveCode | LiveCode | command makeRecording
set the dontUseQT to false -- on windows use true
set the recordFormat to "wave" -- can be wav,aiff, au
set the recordRate to 44.1 -- sample at 44100 Hz
set the recordSampleSize to 16 --default is 8 bit
ask file "Save recording as"
if it is not empty then
answer r... |
http://rosettacode.org/wiki/Record_sound | Record sound | Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs migh... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | SystemDialogInput["RecordSound"] |
http://rosettacode.org/wiki/Record_sound | Record sound | Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs migh... | #Nim | Nim | import osproc, strutils
var name = ""
while name.len == 0:
stdout.write "Enter output file name (without extension): "
name = stdin.readLine().strip()
name.add ".wav"
var rate = 0
while rate notin 2000..19_200:
stdout.write "Enter sampling rate in Hz (2000 to 192000): "
try: rate = parseInt(stdin.readLine()... |
http://rosettacode.org/wiki/Record_sound | Record sound | Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs migh... | #OCaml | OCaml | #load "unix.cma"
let record bytes =
let buf = String.make bytes '\000' in
let ic = open_in "/dev/dsp" in
let chunk = 4096 in
for i = 0 to pred (bytes / chunk) do
ignore (input ic buf (i * chunk) chunk)
done;
close_in ic;
(buf)
let play buf len =
let oc = open_out "/dev/dsp" in
output_string oc... |
http://rosettacode.org/wiki/Read_entire_file | Read entire file | Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case... | #8th | 8th |
"somefile.txt" f:slurp >s
|
http://rosettacode.org/wiki/Read_entire_file | Read entire file | Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case... | #Action.21 | Action! | proc MAIN()
char array STRING
open (1,"D:FILE.TXT",4,0)
inputsd(1,STRING)
close(1)
return
|
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #Nim | Nim | type Foo = object
proc bar(f:Foo) = echo "bar"
var f:Foo
f.bar() |
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface Foo : NSObject
@end
@implementation Foo
- (int)bar:(double)x {
return 42;
}
@end
int main() {
unsigned int methodCount;
Method *methods = class_copyMethodList([Foo class], &methodCount);
for (unsigned int i = 0; i < methodCount; i++) {
... |
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #PicoLisp | PicoLisp |
# The Rectangle class
(class +Rectangle +Shape)
# dx dy
(dm T (X Y DX DY)
(super X Y)
(=: dx DX)
(=: dy DY) )
(dm area> ()
(* (: dx) (: dy)) )
(dm perimeter> ()
(* 2 (+ (: dx) (: dy))) )
(dm draw> ()
(drawRect (: x) (: y) (: dx) (: dy)) ) # Hypothetical function 'drawRect'
|
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #PL.2FI | PL/I |
Get-Date | Get-Member -MemberType Property
|
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #PowerShell | PowerShell |
Get-Date | Get-Member -MemberType Property
|
http://rosettacode.org/wiki/Rep-string | Rep-string | Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For e... | #D | D | import std.stdio, std.string, std.conv, std.range, std.algorithm,
std.ascii, std.typecons;
Nullable!(size_t, 0) repString1(in string s) pure nothrow @safe @nogc
in {
//assert(s.all!isASCII);
assert(s.representation.all!isASCII);
} body {
immutable sr = s.representation;
foreach_reverse (immutab... |
http://rosettacode.org/wiki/Regular_expressions | Regular expressions |
Task
match a string against a regular expression
substitute part of a string using a regular expression
| #Elixir | Elixir |
str = "This is a string"
if str =~ ~r/string$/, do: IO.inspect "str ends with 'string'"
|
http://rosettacode.org/wiki/Regular_expressions | Regular expressions |
Task
match a string against a regular expression
substitute part of a string using a regular expression
| #Emacs_Lisp | Emacs Lisp | (let ((string "I am a string"))
(when (string-match-p "string$" string)
(message "Ends with 'string'"))
(message "%s" (replace-regexp-in-string " a " " another " string))) |
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
... | #Arturo | Arturo | str: "Hello World"
print reverse str |
http://rosettacode.org/wiki/Repeat | Repeat | Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| #Java | Java | import java.util.function.Consumer;
import java.util.stream.IntStream;
public class Repeat {
public static void main(String[] args) {
repeat(3, (x) -> System.out.println("Example " + x));
}
static void repeat (int n, Consumer<Integer> fun) {
IntStream.range(0, n).forEach(i -> fun.accep... |
http://rosettacode.org/wiki/Repeat | Repeat | Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| #jq | jq | def unoptimized_repeat(f; n):
if n <= 0 then empty
else f, repeat(f; n-1)
end; |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #Forth | Forth | s" input.txt" s" output.txt" rename-file throw
s" /input.txt" s" /output.txt" rename-file throw |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #Fortran | Fortran | PROGRAM EX_RENAME
CALL RENAME('input.txt','output.txt')
CALL RENAME('docs','mydocs')
CALL RENAME('/input.txt','/output.txt')
CALL RENAME('/docs','/mydocs')
END |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim result As Long
result = Name("input.txt", "output.txt")
If result <> 0 Then
Print "Renaming file failed"
End If
result = Name("docs", "mydocs")
If result <> 0 Then
Print "Renaming directory failed"
End If
Sleep |
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
| #Yabasic | Yabasic | N=10
NN=N*N
DIM A(NN,NN+1)
NODE=0
FOR ROW=1 TO N
FOR COL=1 TO N
NODE=NODE+1
IF ROW>1 THEN
A(NODE,NODE)=A(NODE,NODE)+1
A(NODE,NODE-N)=-1
END IF
IF ROW<N THEN
A(NODE,NODE)=A(NODE,NODE)+1
A(NODE,NODE+N)=-1
END IF
... |
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
| #zkl | zkl | var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
fcn onGrid(i,j,p,q){ ((0<=i<p) and (0<=j<q)) }
fcn gridResistor(p,q, ai,aj, bi,bj){
n,A := p*q, GSL.Matrix(n,n); // zero filled
foreach i,j in (p,q){
k:=i*q + j;
if(i==ai and j==aj) A[k,k]=1;
else{
c:=0;
if(onGrid(i+1,j, ... |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #Gambas | Gambas | Public Sub Main()
Dim sString As New String[10] 'Array for the input text
Dim sLine As New String[] 'Array of each word in a line
Dim siCount0, siCount1 As Short 'Counters
Dim sOutput, sReverse, sTemp As String... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #Python | Python | >>> u'foo'.encode('rot13')
'sbb'
>>> 'sbb'.decode('rot13')
u'foo' |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #PL.2FSQL | PL/SQL |
/*****************************************************************
* $Author: Atanas Kebedjiev $
*****************************************************************
* Encoding an Arabic numeral to a Roman in the range 1..3999 is much simpler as Oracle provides the conversion formats.
* Please see also the SQL sol... |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Scala | Scala | def fromRoman( r:String ) : Int = {
val arabicNumerals = List("CM"->900,"M"->1000,"CD"->400,"D"->500,"XC"->90,"C"->100,
"XL"->40,"L"->50,"IX"->9,"X"->10,"IV"->4,"V"->5,"I"->1)
var s = r
arabicNumerals.foldLeft(0){ (n,t) => {
val l = s.length; s = s.rep... |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #C.23 | C# | string s = "".PadLeft(5, 'X').Replace("X", "ha"); |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #Fortran | Fortran | module multiple_values
implicit none
type res
integer :: p, m
end type
contains
function addsub(x,y) result(r)
integer :: x, y
type(res) :: r
r%p = x+y
r%m = x-y
end function
end module
program main
use multiple_values
print *, addsub(33, 22)
end program
|
http://rosettacode.org/wiki/Remove_duplicate_elements | Remove duplicate elements |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Arturo | Arturo | arr: [1 2 3 2 1 2 3 4 5 3 2 1]
print unique arr |
http://rosettacode.org/wiki/Recaman%27s_sequence | Recaman's sequence | The Recamán's sequence generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated.
If the conditions don't hold then a(n) = a(n-1) + n.
Task
Generate and show here the... | #Arturo | Arturo | recamanSucc: function [seen, n, r].memoize[
back: r - n
(or? 0 > back contains? seen back)? -> n + r
-> back
]
recamanUntil: function [p][
n: new 1
r: 0
rs: new @[r]
seen: rs
blnNew: true
while [not? do p][
r: recamanSucc seen n r
... |
http://rosettacode.org/wiki/Recaman%27s_sequence | Recaman's sequence | The Recamán's sequence generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated.
If the conditions don't hold then a(n) = a(n-1) + n.
Task
Generate and show here the... | #AWK | AWK |
# syntax: GAWK -f RECAMANS_SEQUENCE.AWK
# converted from Microsoft Small Basic
BEGIN {
found_dup = 0
n = -1
do {
n++
ap = a[n-1] + n
if (a[n-1] <= n) {
a[n] = ap
b[ap] = 1
}
else {
am = a[n-1] - n
if (b[am] == 1) {
a[n] = ap
... |
http://rosettacode.org/wiki/Reduced_row_echelon_form | Reduced row echelon form | Reduced row echelon form
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Show how to compute the reduced row echelon form
(a.k.a. row canonical form) of a matrix.
The matrix can be stored in any datatype that is convenient
(for most languages, this wil... | #11l | 11l | F ToReducedRowEchelonForm(&M)
V lead = 0
V rowCount = M.len
V columnCount = M[0].len
L(r) 0 .< rowCount
I lead >= columnCount
R
V i = r
L M[i][lead] == 0
i++
I i == rowCount
i = r
lead++
I columnCount == lead
R
... |
http://rosettacode.org/wiki/Real_constants_and_functions | Real constants and functions | Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "magnitude")
floor (largest ... | #11l | 11l | math:e // e
math:pi // pi
sqrt(x) // square root
log(x) // natural logarithm
log10(x) // base 10 logarithm
exp(x) // e raised to the power of x
abs(x) // absolute value
floor(x) // floor
ceil(x) // ceiling
x ^ y // exponentiation |
http://rosettacode.org/wiki/Remove_lines_from_a_file | Remove lines from a file | Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th... | #C | C | #include <stdio.h>
#include <stdlib.h> /* for atoi() and malloc() */
#include <string.h> /* for memmove() */
/* Conveniently print to standard error and exit nonzero. */
#define ERROR(fmt, arg) return fprintf(stderr, fmt "\n", arg)
int main(int argc, char **argv)
{
FILE *fp;
char *buf;
size_t sz;
in... |
http://rosettacode.org/wiki/Record_sound | Record sound | Record a monophonic 16-bit PCM sound into either memory space, a file or array.
(This task neglects to specify the sample rate, and whether to use signed samples.
The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate.
Therefore, these programs migh... | #Phix | Phix | --
-- demo\rosetta\Record_sound.exw
-- =============================
--
without js -- (file i/o)
constant wavfile = "capture.wav",
bitspersample = 16,
channels = 2,
samplespersec = 44100,
alignment = bitspersample * channels / 8,
bytespersec = alignment * samplespersec,
... |
http://rosettacode.org/wiki/Read_entire_file | Read entire file | Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case... | #Ada | Ada | with Ada.Directories,
Ada.Direct_IO,
Ada.Text_IO;
procedure Whole_File is
File_Name : String := "whole_file.adb";
File_Size : Natural := Natural (Ada.Directories.Size (File_Name));
subtype File_String is String (1 .. File_Size);
package File_String_IO is new Ada.Direct_IO (File_String);
... |
http://rosettacode.org/wiki/Read_entire_file | Read entire file | Task
Load the entire contents of some text file as a single string variable.
If applicable, discuss: encoding selection, the possibility of memory-mapping.
Of course, in practice one should avoid reading an entire file at once
if the file is large and the task can be accomplished incrementally instead
(in which case... | #ALGOL_68 | ALGOL 68 | MODE BOOK = FLEX[0]FLEX[0]FLEX[0]CHAR; ¢ pages of lines of characters ¢
BOOK book;
FILE book file;
INT errno = open(book file, "book.txt", stand in channel);
get(book file, book) |
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #Perl | Perl | package Nums;
use overload ('<=>' => \&compare);
sub new { my $self = shift; bless [@_] }
sub flip { my @a = @_; 1/$a }
sub double { my @a = @_; 2*$a }
sub compare { my ($a, $b) = @_; abs($a) <=> abs($b) }
my $a = Nums->new(42);
print "$_\n" for %{ref ($a)."::" }); |
http://rosettacode.org/wiki/Reflection/List_methods | Reflection/List methods | Task
The goal is to get the methods of an object, as names, values or both.
Some languages offer dynamic methods, which in general can only be inspected if a class' public API includes a way of listing them.
| #Phix | Phix | enum METHODS, PROPERTIES
sequence all_methods = {}
function method_visitor(object key, object /*data*/, /*user_data*/)
all_methods = append(all_methods,key)
return 1
end function
function get_all_methods(object o)
all_methods = {}
traverse_dict(method_visitor,0,o[METHODS])
return all_methods
end ... |
http://rosettacode.org/wiki/Reflection/List_properties | Reflection/List properties | Task
The goal is to get the properties of an object, as names, values or both.
Some languages support dynamic properties, which in general can only be inspected if a class' public API includes a way of listing them.
| #Python | Python | class Parent(object):
__priv = 'private'
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%s)' % (type(self).__name__, self.name)
def doNothing(self):
pass
import re
class Child(Parent):
# prefix for "private" fields
__rePrivate = re.com... |
http://rosettacode.org/wiki/Rep-string | Rep-string | Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
For e... | #Delphi | Delphi |
program Rep_string;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
const
m = '1001110011'#10 +
'1110111011'#10 +
'0010010010'#10 +
'1010101010'#10 +
'1111111111'#10 +
'0100101101'#10 +
'0100100'#10 +
'101'#10 +
'11'#10 +
'00'#10 +
'... |
http://rosettacode.org/wiki/Regular_expressions | Regular expressions |
Task
match a string against a regular expression
substitute part of a string using a regular expression
| #Erlang | Erlang | match() ->
String = "This is a string",
case re:run(String, "string$") of
{match,_} -> io:format("Ends with 'string'~n");
_ -> ok
end.
substitute() ->
String = "This is a string",
NewString = re:replace(String, " a ", " another ", [{return, list}]),
io:format("~s~n",[NewString]). |
http://rosettacode.org/wiki/Reverse_a_string | Reverse a string | Task
Take a string and reverse it.
For example, "asdf" becomes "fdsa".
Extra credit
Preserve Unicode combining characters.
For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa".
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
... | #AutoHotkey | AutoHotkey | MsgBox % reverse("asdf")
reverse(string)
{
Loop, Parse, string
reversed := A_LoopField . reversed
Return reversed
} |
http://rosettacode.org/wiki/Repeat | Repeat | Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| #Julia | Julia | function sayHi()
println("Hi")
end
function rep(f, n)
for i = 1:n f() end
end
rep(sayHi, 3) |
http://rosettacode.org/wiki/Repeat | Repeat | Task
Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| #Kotlin | Kotlin | // version 1.0.6
fun repeat(n: Int, f: () -> Unit) {
for (i in 1..n) {
f()
println(i)
}
}
fun main(args: Array<String>) {
repeat(5) { print("Example ") }
} |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #Go | Go | package main
import "os"
func main() {
os.Rename("input.txt", "output.txt")
os.Rename("docs", "mydocs")
os.Rename("/input.txt", "/output.txt")
os.Rename("/docs", "/mydocs")
} |
http://rosettacode.org/wiki/Rename_a_file | Rename a file | Task
Rename:
a file called input.txt into output.txt and
a directory called docs into mydocs.
This should be done twice:
once "here", i.e. in the current working directory and once in the filesystem root.
It can be assumed that the user has the rights to do so.
(In unix-type s... | #Groovy | Groovy | ['input.txt':'output.txt', 'docs':'mydocs'].each { src, dst ->
['.', ''].each { dir ->
new File("$dir/$src").renameTo(new File("$dir/$dst"))
}
} |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #Gema | Gema | \L<G> <U>=@{$2} $1 |
http://rosettacode.org/wiki/Reverse_words_in_a_string | Reverse words in a string | Task
Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
Example
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens are any non-space characters separated by spaces (formally, white-space); t... | #Go | Go | package main
import (
"fmt"
"strings"
)
// a number of strings
var n = []string{
"---------- Ice and Fire ------------",
" ",
"fire, in end will world the say Some",
"ice. in say Some ",
"desire of tasted I've what From ",
"fi... |
http://rosettacode.org/wiki/Rot-13 | Rot-13 |
Task
Implement a rot-13 function (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment).
Optionally wrap this function in a utility program (like tr, which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu... | #QB64 | QB64 | INPUT "Enter a string: ", a$
PRINT rot13$(a$)
FUNCTION rot13$ (stg$)
inlist$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
outlist$ = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm"
FOR n = 1 TO LEN(stg$)
letter$ = MID$(stg$, n, 1)
letpos = INSTR(inlist$, letter$)
I... |
http://rosettacode.org/wiki/Roman_numerals/Encode | Roman numerals/Encode | Task
Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero.
In Roman numeral... | #Plain_TeX | Plain TeX | \def\upperroman#1{\uppercase\expandafter{\romannumeral#1}}
Anno Domini \upperroman{\year}
\bye |
http://rosettacode.org/wiki/Roman_numerals/Decode | Roman numerals/Decode | Task
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decima... | #Scheme | Scheme | (use gauche.collection) ;; for fold2
(define (char-val char)
(define i (string-scan "IVXLCDM" char))
(* (expt 10 (div i 2)) (expt 5 (mod i 2))))
(define (decode roman)
(fold2
(lambda (n sum prev-val)
(values ((if (< n prev-val) - +) sum n) (max n prev-val)))
0 0
(map char-val (reverse (strin... |
http://rosettacode.org/wiki/Repeat_a_string | Repeat a string | Take a string and repeat it some number of times.
Example: repeat("ha", 5) => "hahahahaha"
If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").
Other tasks re... | #C.2B.2B | C++ | #include <string>
#include <iostream>
std::string repeat( const std::string &word, int times ) {
std::string result ;
result.reserve(times*word.length()); // avoid repeated reallocation
for ( int a = 0 ; a < times ; a++ )
result += word ;
return result ;
}
int main( ) {
std::cout << repeat( "H... |
http://rosettacode.org/wiki/Return_multiple_values | Return multiple values | Task
Show how to return more than one value from a function.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' One way to return multiple values is to use ByRef parameters for the additional one(s)
Function tryOpenFile (fileName As String, ByRef fileNumber As Integer) As Boolean
Dim result As Integer
fileNumber = FreeFile
result = Open(fileName For Input As # fileNumber)
If result <> 0 Then
... |
http://rosettacode.org/wiki/Remove_duplicate_elements | Remove duplicate elements |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #AutoHotkey | AutoHotkey | a = 1,2,1,4,5,2,15,1,3,4
Sort, a, a, NUD`,
MsgBox % a ; 1,2,3,4,5,15 |
http://rosettacode.org/wiki/Recaman%27s_sequence | Recaman's sequence | The Recamán's sequence generates Natural numbers.
Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated.
If the conditions don't hold then a(n) = a(n-1) + n.
Task
Generate and show here the... | #BASIC | BASIC | 10 DEFINT A-Z: DIM A(100)
20 PRINT "First 15 terms:"
30 FOR N=0 TO 14: GOSUB 100: PRINT A(N);: NEXT
35 PRINT
40 PRINT "First repeated term:"
50 GOSUB 100
55 FOR M=0 TO N-1: IF A(M)=A(N) THEN 70 ELSE NEXT
60 N=N+1: GOTO 50
70 PRINT "A(";N;") =";A(N)
80 END
100 IF N=0 THEN A(0)=0: RETURN
110 X = A(N-1)-N: IF X<0 THEN 160... |
http://rosettacode.org/wiki/Reduced_row_echelon_form | Reduced row echelon form | Reduced row echelon form
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Show how to compute the reduced row echelon form
(a.k.a. row canonical form) of a matrix.
The matrix can be stored in any datatype that is convenient
(for most languages, this wil... | #360_Assembly | 360 Assembly | * reduced row echelon form 27/08/2015
RREF CSECT
USING RREF,R12
LR R12,R15
LA R10,1 lead=1
LA R7,1
LOOPR CH R7,NROWS do r=1 to nrows
BH ELOOPR
CH R10,NCOLS if lead>=ncols
BNL ELOOPR
... |
http://rosettacode.org/wiki/Real_constants_and_functions | Real constants and functions | Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "magnitude")
floor (largest ... | #6502_Assembly | 6502 Assembly | GetAbs: ;assumes value we want to abs() is loaded into accumulator
eor #$ff
clc
adc #1
rts |
http://rosettacode.org/wiki/Real_constants_and_functions | Real constants and functions | Task
Show how to use the following math constants and functions in your language (if not available, note it):
e (base of the natural logarithm)
π
{\displaystyle \pi }
square root
logarithm (any base allowed)
exponential (ex )
absolute value (a.k.a. "magnitude")
floor (largest ... | #ACL2 | ACL2 | (floor 15 2) ;; This is the floor of 15/2
(ceiling 15 2)
(expt 15 2) ;; 15 squared |
http://rosettacode.org/wiki/Remove_lines_from_a_file | Remove lines from a file | Task
Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th... | #C.23 | C# | using System;
using System.IO;
using System.Linq;
public class Rosetta
{
public static void Main() => RemoveLines("foobar.txt", start: 1, count: 2);
static void RemoveLines(string filename, int start, int count = 1) =>
File.WriteAllLines(filename, File.ReadAllLines(filename)
.Where((line... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.