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/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
... | #LFE | LFE |
> (lists:reverse "asdf")
"fdsa"
|
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... | #VBA | VBA | Public Function RepeatStr(aString As String, aNumber As Integer) As String
Dim bString As String, i As Integer
bString = ""
For i = 1 To aNumber
bString = bString & aString
Next i
RepeatStr = bString
End Function
Debug.Print RepeatStr("ha", 5) |
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... | #VBScript | VBScript |
' VBScript has a String() function that can repeat a character a given number of times
' but this only works with single characters (or the 1st char of a string):
WScript.Echo String(10, "123") ' Displays "1111111111"
' To repeat a string of chars, you can use either of the following "hacks"...
WScript.Echo Replace... |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #Batch_File | Batch File |
@echo off
for /f "skip=6 tokens=*" %%i in (file.txt) do (
set line7=%%i
goto break
)
:break
echo Line 7 is: %line7%
pause>nul
|
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #BBC_BASIC | BBC BASIC | filepath$ = @lib$ + "..\licence.txt"
requiredline% = 7
file% = OPENIN(filepath$)
IF file%=0 ERROR 100, "File could not be opened"
FOR i% = 1 TO requiredline%
IF EOF#file% ERROR 100, "File contains too few lines"
INPUT #file%, text$
NEXT
CLOSE #file%
IF... |
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
... | #Red | Red | >> items: [1 "a" "c" 1 3 4 5 "c" 3 4 5]
>> unique items
== [1 "a" "c" 3 4 5] |
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
... | #REXX | REXX | /*REXX program removes any duplicate elements (items) that are in a list (using a hash).*/
$= '2 3 5 7 11 13 17 19 cats 222 -100.2 +11 1.1 +7 7. 7 5 5 3 2 0 4.4 2' /*item list.*/
say 'original list:' $
say right( words($), 17, '─') 'words in the original list.'
z=; @.= ... |
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8 | Read a file character by character/UTF8 | Task
Read a file one character at a time, as opposed to reading the entire file at once.
The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).
The procedure should support the reading of files contain... | #QBasic | QBasic | f = FREEFILE
filename$ = "file.txt"
OPEN filename$ FOR BINARY AS #f
WHILE NOT EOF(f)
char$ = STR$(LOF(f))
GET #f, , char$
PRINT char$;
WEND
CLOSE #f |
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8 | Read a file character by character/UTF8 | Task
Read a file one character at a time, as opposed to reading the entire file at once.
The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).
The procedure should support the reading of files contain... | #Racket | Racket |
#lang racket
; This file contains utf-8 charachters: λ, α, γ ...
(for ([c (in-port read-char (open-input-file "read-file.rkt"))])
(display c))
|
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #JavaScript | JavaScript | function millis() { // Gets current time in milliseconds.
return (new Date()).getTime();
}
/* Executes function 'func' n times, returns array of execution times. */
function benchmark(n, func, args) {
var times = [];
for (var i=0; i<n; i++) {
var m = millis();
func.apply(func, args);
times.push(mill... |
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
... | #Liberty_BASIC | Liberty BASIC | input$ ="abcdefgABCDEFG012345"
print input$
print ReversedStr$( input$)
end
function ReversedStr$(in$)
for i =len(in$) to 1 step -1
ReversedStr$ =ReversedStr$ +mid$( in$, i, 1)
next i
end function |
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... | #Vedit_macro_language | Vedit macro language | Ins_Text("ha", COUNT, 5) |
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... | #Visual_Basic | Visual Basic | Public Function StrRepeat(s As String, n As Integer) As String
Dim r As String, i As Integer
r = ""
For i = 1 To n
r = r & s
Next i
StrRepeat = r
End Function
Debug.Print StrRepeat("ha", 5) |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #C | C | #include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <err.h>
/* following code assumes all file operations succeed. In practice,
* return codes from open, close, fstat, mmap, munmap all need to be
* checked for error.
*/
int read_file_line(const char *pa... |
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
... | #Ring | Ring |
list = ["Now", "is", "the", "time", "for", "all", "good", "men", "to", "come", "to", "the", "aid", "of", "the", "party."]
for i = 1 to len(list)
for j = i + 1 to len(list)
if list[i] = list[j] del(list, j) j-- ok
next
next
for n = 1 to len(list)
see list[n] + " "
next
see nl
|
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
... | #Ruby | Ruby | ary = [1,1,2,1,'redundant',[1,2,3],[1,2,3],'redundant']
p ary.uniq # => [1, 2, "redundant", [1, 2, 3]] |
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8 | Read a file character by character/UTF8 | Task
Read a file one character at a time, as opposed to reading the entire file at once.
The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).
The procedure should support the reading of files contain... | #Raku | Raku | .say while defined $_ = $*IN.getc; |
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8 | Read a file character by character/UTF8 | Task
Read a file one character at a time, as opposed to reading the entire file at once.
The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).
The procedure should support the reading of files contain... | #REXX | REXX | /*REXX program reads and displays a file char by char, returning 'EOF' when done. */
parse arg iFID . /*iFID: is the fileID to be read. */
/* [↓] show the file's contents. */
if iFID\=='' then do j=1 until x=='EOF' ... |
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #Jsish | Jsish | #!/usr/bin/env jsish
"use strict";
/* Rate counter, timer access, in Jsish */
/* System time in milliseconds */
var runs = 0, newMs;
function countJobsIsTheJob() { runs += 1; }
var milliSeconds = strptime();
while ((newMs = strptime()) < (milliSeconds + 1000)) { countJobsIsTheJob(); }
puts(runs, 'runs in', newMs - mi... |
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
... | #Lingo | Lingo | on reverse (str)
res = ""
repeat with i = str.length down to 1
put str.char[i] after res
end repeat
return res
end |
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... | #Visual_Basic_.NET | Visual Basic .NET |
Debug.Print(Replace(Space(5), " ", "Ha"))
|
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... | #Visual_FoxPro | Visual FoxPro | ? REPLICATE("HO", 3) |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #C.23 | C# | using System;
using System.IO;
namespace GetLine
{
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(GetLine(args[0], uint.Parse(args[1])));
}
private static string GetLine(string path, uint line)
{
using (var... |
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
... | #Run_BASIC | Run BASIC | a$ = "2 3 5 7 11 13 17 19 cats 222 -100.2 +11 1.1 +7 7. 7 5 5 3 2 0 4.4 2"
for i = 1 to len(a$)
a1$ = word$(a$,i)
if a1$ = "" then exit for
for i1 = 1 to len(b$)
if a1$ = word$(b$,i1) then [nextWord]
next i1
b$ = b$ + a1$ + " "
[nextWord]
next i
print "Dups:";a$
print "No Dups:";b$ |
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8 | Read a file character by character/UTF8 | Task
Read a file one character at a time, as opposed to reading the entire file at once.
The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).
The procedure should support the reading of files contain... | #Ring | Ring |
fp = fopen("C:\Ring\ReadMe.txt","r")
r = fgetc(fp)
while isstring(r)
r = fgetc(fp)
see r
end
fclose(fp)
|
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8 | Read a file character by character/UTF8 | Task
Read a file one character at a time, as opposed to reading the entire file at once.
The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).
The procedure should support the reading of files contain... | #Ruby | Ruby | File.open('input.txt', 'r:utf-8') do |f|
f.each_char{|c| p c}
end |
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #Julia | Julia | dosomething() = sleep(abs(randn()))
function runNsecondsworthofjobs(N)
times = Vector{Float64}()
totaltime = 0
runcount = 0
while totaltime < N
t = @elapsed(dosomething())
push!(times, t)
totaltime += t
runcount += 1
end
println("Ran job $runcount times, for tot... |
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #Kotlin | Kotlin | // version 1.1.3
typealias Func<T> = (T) -> T
fun cube(n: Int) = n * n * n
fun <T> benchmark(n: Int, func: Func<T>, arg: T): LongArray {
val times = LongArray(n)
for (i in 0 until n) {
val m = System.nanoTime()
func(arg)
times[i] = System.nanoTime() - m
}
return times
} ... |
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
... | #LiveCode | LiveCode | function reverseString S
repeat with i = length(S) down to 1
put char i of S after R
end repeat
return R
end reverseString |
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... | #Vlang | Vlang | // Repeat a string, in V
// Tectonics: v run repeat-a-string.v
module main
import strings
// starts here
pub fn main() {
// A strings module function to repeat strings
println(strings.repeat_string("ha", 5))
// Another strings module function to repeat a byte
// This indexes the string to get the fi... |
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... | #Wart | Wart | def (s * n) :case (string? s)
with outstring
repeat n
pr s
("ha" * 5)
=> "hahahahaha" |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #C.2B.2B | C++ | #include <string>
#include <fstream>
#include <iostream>
int main( ) {
std::cout << "Which file do you want to look at ?\n" ;
std::string input ;
std::getline( std::cin , input ) ;
std::ifstream infile( input.c_str( ) , std::ios::in ) ;
std::string file( input ) ;
std::cout << "Which file line do yo... |
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
... | #Rust | Rust | use std::collections::HashSet;
use std::hash::Hash;
fn remove_duplicate_elements_hashing<T: Hash + Eq>(elements: &mut Vec<T>) {
let set: HashSet<_> = elements.drain(..).collect();
elements.extend(set.into_iter());
}
fn remove_duplicate_elements_sorting<T: Ord>(elements: &mut Vec<T>) {
elements.sort_unst... |
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8 | Read a file character by character/UTF8 | Task
Read a file one character at a time, as opposed to reading the entire file at once.
The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).
The procedure should support the reading of files contain... | #Run_BASIC | Run BASIC | open file.txt" for binary as #f
numChars = 1 ' specify number of characters to read
a$ = input$(#f,numChars) ' read number of characters specified
b$ = input$(#f,1) ' read one character
close #f |
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8 | Read a file character by character/UTF8 | Task
Read a file one character at a time, as opposed to reading the entire file at once.
The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).
The procedure should support the reading of files contain... | #Rust | Rust | use std::{
convert::TryFrom,
fmt::{Debug, Display, Formatter},
io::Read,
};
pub struct ReadUtf8<I: Iterator> {
source: std::iter::Peekable<I>,
}
impl<R: Read> From<R> for ReadUtf8<std::io::Bytes<R>> {
fn from(source: R) -> Self {
ReadUtf8 {
source: source.bytes().peekable(),
... |
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #Liberty_BASIC | Liberty BASIC |
Print "Rate counter"
print "Precision: system clock, ms ";
t0=time$("ms")
while time$("ms")=t0 'busy loop till click ticks
wend
print time$("ms")-t0
print
Print "Run jobs N times, report every time"
Print "After that, report average time"
N=10
t00=time$("ms")
for i = 1 to 10
scan
t0=time$("ms")
'any ... |
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
... | #LLVM | LLVM | ; This is not strictly LLVM, as it uses the C library function "printf".
; LLVM does not provide a way to print values, so the alternative would be
; to just load the string into memory, and that would be boring.
; Additional comments have been inserted, as well as changes made from the output produced by clang such ... |
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... | #Wortel | Wortel | @join "" @rep 5 "ha" ; returns "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... | #Wren | Wren | System.print("ha" * 5) |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #Clojure | Clojure | (defn read-nth-line
"Read line-number from the given text file. The first line has the number 1."
[file line-number]
(with-open [rdr (clojure.java.io/reader file)]
(nth (line-seq rdr) (dec line-number)))) |
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
... | #Scala | Scala | val list = List(1,2,3,4,2,3,4,99)
val l2 = list.distinct
// l2: scala.List[scala.Int] = List(1,2,3,4,99)
val arr = Array(1,2,3,4,2,3,4,99)
val arr2 = arr.distinct
// arr2: Array[Int] = Array(1, 2, 3, 4, 99)
|
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8 | Read a file character by character/UTF8 | Task
Read a file one character at a time, as opposed to reading the entire file at once.
The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).
The procedure should support the reading of files contain... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "utf8.s7i";
const proc: main is func
local
var file: inFile is STD_NULL;
var char: ch is ' ';
begin
OUT := STD_UTF8_OUT;
inFile := openUtf8("readAFileCharacterByCharacterUtf8.in", "r");
if inFile <> STD_NULL then
while hasNext(inFile) do
ch := ... |
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8 | Read a file character by character/UTF8 | Task
Read a file one character at a time, as opposed to reading the entire file at once.
The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).
The procedure should support the reading of files contain... | #Sidef | Sidef | var file = File('input.txt') # the input file contains: "aă€⼥"
var fh = file.open_r # equivalent with: file.open('<:utf8')
fh.each_char { |char|
printf("got character #{char} [U+%04x]\n", char.ord)
} |
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | jobRateCounted[fn_,Y_Integer]:=First[AbsoluteTiming[Do[fn,{Y}]]/Y;
SetAttributes[jobRateCounted,HoldFirst]
jobRatePeriod[fn_,time_]:=Block[{n=0},TimeConstrained[While[True,fn;n++]];n/time];
SetAttributes[jobRatePeriod,HoldFirst] |
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #Nim | Nim | import sugar, std/monotimes, times
type Func[T] = (T) -> T
func cube(n: int): int = n * n * n
proc benchmark[T](n: int; f: Func[T]; arg: T): seq[Duration] =
result.setLen(n)
for i in 0..<n:
let m = getMonoTime()
discard f(arg)
result[i] = getMonoTime() - m
echo "Timings (nanoseconds):"
for time ... |
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
... | #Logo | Logo | print reverse "cat ; tac |
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... | #XPL0 | XPL0 | cod T=12; int I; for I gets 1,5 do T(0,"ha") |
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... | #Yorick | Yorick | array("ha", 5)(sum) |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #Common_Lisp | Common Lisp | (defun read-nth-line (file n &aux (line-number 0))
"Read the nth line from a text file. The first line has the number 1"
(assert (> n 0) (n))
(with-open-file (stream file)
(loop for line = (read-line stream nil nil)
if (and (null line) (< line-number n))
do (error "file ~a is too short, ... |
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
... | #Scheme | Scheme | (define (remove-duplicates l)
(cond ((null? l)
'())
((member (car l) (cdr l))
(remove-duplicates (cdr l)))
(else
(cons (car l) (remove-duplicates (cdr l))))))
(remove-duplicates '(1 2 1 3 2 4 5)) |
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8 | Read a file character by character/UTF8 | Task
Read a file one character at a time, as opposed to reading the entire file at once.
The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).
The procedure should support the reading of files contain... | #Smalltalk | Smalltalk | |utfStream|
utfStream := 'input' asFilename readStream asUTF8EncodedStream.
[utfStream atEnd] whileFalse:[
Transcript showCR:'got char ',utfStream next.
].
utfStream close. |
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8 | Read a file character by character/UTF8 | Task
Read a file one character at a time, as opposed to reading the entire file at once.
The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).
The procedure should support the reading of files contain... | #Tcl | Tcl | set ch [read $channel 1] |
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #OxygenBasic | OxygenBasic |
'========
'TIME API
'========
'http://msdn.microsoft.com/en-us/library/windows/desktop/ms724950(v=vs.85).aspx
extern lib "kernel32.dll"
type SYSTEMTIME
WORD wYear
WORD wMonth
WORD wDayOfWeek
WORD wDay
WORD wHour
WORD wMinute
WORD wSecond
WORD wMilliseconds
end type
void GetSystemTime(SYSTEMTIM... |
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
... | #Lua | Lua | theString = theString:reverse() |
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... | #Z80_Assembly | Z80 Assembly | PrintChar equ &BB5A ;Amstrad CPC BIOS call, prints the ascii code in the accumulator to the screen.
org &8000
ld b,5 ; repeat 5 times
loop:
call PrintImmediate
byte "ha",0
djnz loop
ret ; return to basic
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PrintImmediate:
pop h... |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #D | D |
void main() {
import std.stdio, std.file, std.string;
auto file_lines = readText("input.txt").splitLines();
//file_lines becomes an array of strings, each line is one element
writeln((file_lines.length > 6) ? file_lines[6] : "line not found");
}
|
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
... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
const array integer: data is [] (1, 3, 2, 9, 1, 2, 3, 8, 8, 1, 0, 2);
var set of integer: dataSet is (set of integer).value;
var integer: number is 0;
begin
for number range data do
incl(dataSet, number);
end for;
writeln(dataS... |
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8 | Read a file character by character/UTF8 | Task
Read a file one character at a time, as opposed to reading the entire file at once.
The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).
The procedure should support the reading of files contain... | #Wren | Wren | import "io" for File
File.open("input.txt") { |file|
var offset = 0
var char = "" // stores each byte read till we have a complete UTF encoded character
while(true) {
var b = file.readBytes(1, offset)
if (b == "") return // end of stream
char = char + b
if (char.codePoints[... |
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8 | Read a file character by character/UTF8 | Task
Read a file one character at a time, as opposed to reading the entire file at once.
The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached).
The procedure should support the reading of files contain... | #zkl | zkl | fcn readUTF8c(chr,s=""){ // transform UTF-8 character stream
s+=chr;
try{ s.len(8); return(s) }
catch{ if(s.len()>6) throw(__exception) } // 6 bytes max for UTF-8
return(Void.Again,s); // call me again with s & another character
} |
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #PARI.2FGP | PARI/GP | a=0;
b=0;
for(n=1,20000000,
a=a+gettime();
if(a>60000,print(b);a=0;b=0);
'''code to test'''
b=b+1;
a=a+gettime();
if(a>60000,print(b);a=0;b=0)
) |
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
... | #M2000_Interpreter | M2000 Interpreter |
Module ReverseString {
a$="as⃝df̅"
Print Len(a$), len.disp(a$)
Let i=1, j=Len(a$)
z$=String$(" ",j)
j++
do {
k$=mid$(a$, i, 1)
if i<len(a$) then {
while len.disp(k$+mid$(a$, i+1,1)) =len.disp(k$) {
k$+=mid$(a$, i+1,... |
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... | #zig | zig | const laugh = "ha" ** 5; |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #Delphi | Delphi |
program Read_a_specific_line_from_a_file;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function ReadLine(position: Cardinal; FileName: TFileName): string;
begin
Result := '';
if not FileExists(FileName) then
raise Exception.Create('Error: File does not exist.');
var F: TextFile;
var line: string;
... |
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
... | #SETL | SETL | items := [0,7,6,6,4,9,7,1,2,3,2];
print(unique(items)); |
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #Perl | Perl | use Benchmark;
timethese COUNT,{ 'Job1' => &job1, 'Job2' => &job2 };
sub job1
{
...job1 code...
}
sub job2
{
...job2 code...
} |
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
... | #M4 | M4 | define(`invert',`ifelse(len(`$1'),0,,`invert(substr(`$1',1))'`'substr(`$1',0,1))') |
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... | #zkl | zkl | "ha" * 5 # --> "hahahahaha" |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #Elixir | Elixir |
defmodule LineReader do
def get_line(filename, line) do
File.stream!(filename)
|> Stream.with_index
|> Stream.filter(fn {_value, index} -> index == line-1 end)
|> Enum.at(0)
|> print_line
end
defp print_line({value, _line_number}), do: String.trim(value)
defp print_line(_), do: {:error, "I... |
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
... | #SETL4 | SETL4 |
set = new('set')
* Add all the elements of the array to the set.
add(set,array)
|
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #Phix | Phix | procedure task_to_measure()
sleep(0.1)
end procedure
printf(1,"method 1: calculate reciprocal of elapsed time:\n")
for trial=1 to 3 do
atom t=time()
task_to_measure()
t = time()-t
string r = iff(t?sprintf("%g",1/t):"inf")
printf(1,"rate = %s per second\n",{r})
end for
printf(1,"method 2: cou... |
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
... | #Maclisp | Maclisp | (readlist (reverse (explode "my-string"))) |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #Erlang | Erlang |
-module( read_a_specific_line ).
-export( [from_file/2, task/0] ).
from_file( File, N ) -> line_nr( N, read_a_file_line_by_line:into_list(File) ).
task() ->
Lines = read_a_file_line_by_line:into_list( "read_a_specific_line.erl" ),
Line_7 = line_nr( 7, Lines ),
Line_7.
line_nr( N, Line... |
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
... | #Sidef | Sidef | var ary = [1,1,2,1,'redundant',[1,2,3],[1,2,3],'redundant'];
say ary.uniq.dump;
say ary.last_uniq.dump; |
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #Phixmonti | Phixmonti | 100000 var iterations
2 4 2 tolist
for
msec var a
iterations
for
over 2 power + drop
endfor
msec a - var dif
"take " print dif print " secs" print
" or " print iterations dif / print " sums per second" print nl
endfor |
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
... | #Maple | Maple | > StringTools:-Reverse( "foo" );
"oof" |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #F.23 | F# | open System
open System.IO
[<EntryPoint>]
let main args =
let n = Int32.Parse(args.[1]) - 1
use r = new StreamReader(args.[0])
let lines = Seq.unfold (
fun (reader : StreamReader) ->
if (reader.EndOfStream) then None
else Some(reader.ReadLine()... |
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
... | #Slate | Slate | [|:s| #(1 2 3 4 1 2 3 4) >> s] writingAs: Set.
"==> {"Set traitsWindow" 1. 2. 3. 4}" |
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #PicoLisp | PicoLisp | (prin "Hit a key ... ")
(key)
(prinl)
(let Usec (usec)
(prin "Hit another key ... ")
(key)
(prinl)
(prinl "This took " (format (- (usec) Usec) 6) " seconds") ) |
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
... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | StringReverse["asdf"] |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #Factor | Factor | USING: continuations fry io io.encodings.utf8 io.files kernel
math ;
IN: rosetta-code.nth-line
: nth-line ( path encoding n -- str/f )
[ f ] 3dip '[
[ _ [ drop readln [ return ] unless* ] times ]
with-return
] with-file-reader ;
: nth-line-demo ( -- )
"input.txt" utf8 7 nth-line [ "line ... |
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
... | #Smalltalk | Smalltalk | "Example of creating a collection"
|a|
a := #( 1 1 2 'hello' 'world' #symbol #another 2 'hello' #symbol ).
a asSet. |
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #PowerShell | PowerShell |
[datetime]$start = Get-Date
[int]$count = 3
[timespan[]]$times = for ($i = 0; $i -lt $count; $i++)
{
Measure-Command {0..999999 | Out-Null}
}
[datetime]$end = Get-Date
$rate = [PSCustomObject]@{
StartTime = $start
EndTime = $end
Duration = ($end - $start).TotalSeconds
Ti... |
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
... | #MATLAB | MATLAB | >> fliplr(['She told me that she spoke English and I said great. '...
'Grabbed her hand out the club and I said let''s skate.'])
ans =
.etaks s'tel dias I dna bulc eht tuo dnah reh debbarG .taerg dias I dna hsilgnE ekops ehs taht em dlot ehS |
http://rosettacode.org/wiki/Ray-casting_algorithm | Ray-casting algorithm |
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Given a point and a polygon, check if the point is inside or out... | #11l | 11l | T Pt
Float x, y
F (x, y)
.x = x
.y = y
F String()
R ‘Pt(x=#., y=#.)’.format(.x, .y)
T Edge
Pt a, b
F (a, b)
.a = a
.b = b
F String()
R ‘Edge(a=#., b=#.)’.format(.a, .b)
T Poly
String name
[Edge] edges
F (name, edges)
.name = name
.... |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #Fortran | Fortran | MODULE SAMPLER !To sample a record from a file. SAM00100
CONTAINS SAM00200
CHARACTER*20 FUNCTION GETREC(N,F,IS) !Returns a status. SAM00300
Careful. Some compilers get confused over the function name's usage. SAM00... |
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
... | #Sparkling | Sparkling | function undupe(arr) {
var t = {};
foreach(arr, function(key, val) {
t[val] = true;
});
var r = {};
foreach(t, function(key) {
r[sizeof r] = key;
});
return 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
... | #SQL | SQL |
/*
This code is an implementation of "Remove duplicate elements" in SQL ORACLE 19c
p_in_str -- input string
p_delimiter -- delimeter
*/
WITH
FUNCTION remove_duplicate_elements(p_in_str IN varchar2, p_delimiter IN varchar2 DEFAULT ',') RETURN varchar2 IS
v_in_str varchar2(32767) := REPLACE(p_in_str,p_delimi... |
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #PureBasic | PureBasic | Procedure.d TimesPSec(Reset=#False)
Static starttime, cnt
Protected Result.d, dt
If Reset
starttime=ElapsedMilliseconds(): cnt=0
Else
cnt+1
dt=(ElapsedMilliseconds()-starttime)
If dt
Result=cnt/(ElapsedMilliseconds()-starttime)
EndIf
EndIf
ProcedureReturn Result*1000
EndProcedure
... |
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
... | #Maxima | Maxima | sreverse("abcdef"); /* "fedcba" */
sreverse("rats live on no evil star"); /* not a bug :o) */ |
http://rosettacode.org/wiki/Ray-casting_algorithm | Ray-casting algorithm |
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Given a point and a polygon, check if the point is inside or out... | #Ada | Ada | package Polygons is
type Point is record
X, Y : Float;
end record;
type Point_List is array (Positive range <>) of Point;
subtype Segment is Point_List (1 .. 2);
type Polygon is array (Positive range <>) of Segment;
function Create_Polygon (List : Point_List) return Polygon;
function Is... |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Open "input.txt" For Input As #1
Dim line_ As String
Dim count As Integer = 0
While Not Eof(1)
Line Input #1, line_ '' read each line
count += 1
If count = 7 Then
line_ = Trim(line_, Any !" \t") '' remove any leading or trailing spaces or tabs
If line_ = "" Then
Print "The 7... |
http://rosettacode.org/wiki/Ranking_methods | Ranking methods |
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
... | #11l | 11l | F mc_rank([(Int, String)] iterable)
‘Modified competition ranking’
[(Float, (Int, String))] r
V lastresult = -1
[(Int, String)] fifo
L(item) iterable
I item[0] == lastresult
fifo [+]= item
E
V n = L.index
L !fifo.empty
r.append((n, fifo.pop(0)))
... |
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
... | #Stata | Stata | . clear all
. input x y
1 1
1 1
1 2
2 1
2 2
1 1
2 1
2 1
1 2
2 2
end
. duplicates drop x y, force
. list
+-------+
| x y |
|-------|
1. | 1 1 |
2. | 1 2 |
3. | 2 1 |
4. | 2 2 |
+-------+ |
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
... | #Swift | Swift | println(Array(Set([3,2,1,2,3,4]))) |
http://rosettacode.org/wiki/Rate_counter | Rate counter | Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
Run N seconds worth... | #Python | Python | import subprocess
import time
class Tlogger(object):
def __init__(self):
self.counts = 0
self.tottime = 0.0
self.laststart = 0.0
self.lastreport = time.time()
def logstart(self):
self.laststart = time.time()
def logend(self):
self.counts +=1
self... |
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
... | #MAXScript | MAXScript | fn reverseString s =
(
local reversed = ""
for i in s.count to 1 by -1 do reversed += s[i]
reversed
) |
http://rosettacode.org/wiki/Ray-casting_algorithm | Ray-casting algorithm |
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Given a point and a polygon, check if the point is inside or out... | #ANSI_Standard_BASIC | ANSI Standard BASIC | 1000 PUBLIC NUMERIC x,y
1010 LET x=1
1020 LET y=2
1030 !
1040 DEF isLeft2(L(,),p()) = -SGN( (L(1,x)-L(2,x))*(p(y)-L(2,y)) - (p(x)-L(2,x))*(L(1,y)-L(2,y)))
1050 !
1060 FUNCTION inpolygon(p1(,),p2())
1070 LET k=UBOUND(p1,1)+1
1080 DIM send (1 TO 2,2)
1090 LET wn=0
1100 FOR n=1 TO UBOUND(p1,1)
1110 LET ... |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #Frink | Frink | nthLine[filename, lineNum] :=
{
line = nth[lines[filenameToURL[filename]], lineNum-1]
if line != undef
return line
else
{
println["The file $filename does not contain a line number $lineNum"]
return undef
}
} |
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file | Read a specific line from a file | Some languages have special semantics for obtaining a known line number from a file.
Task
Demonstrate how to obtain the contents of a specific line within a file.
For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (fo... | #FutureBasic | FutureBasic | window 1
long i = 1
Str255 s, lineSeven
CFURLRef url
url = openpanel 1, @"Select text file"
if ( url )
open "I", 2, url
while ( not eof(2) )
line input #2, s
if ( i == 7 )
lineSeven = s : break
end if
i++
wend
close 2
if ( lineSeven[0] )
print lineSeven
else
print "... |
http://rosettacode.org/wiki/Ranking_methods | Ranking methods |
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 | (*
The five ranking methods are implemented here as script objects sharing inherited code rather than as simple
handlers, although there appears to be little advantage either way. This way needs fewer lines of code
but more lines of explanatory comments!
*)
use AppleScript version "2.4" -- Mac OS 10.11 (Yos... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.