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/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
... | #Tcl | Tcl | set result [lsort -unique $listname] |
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
... | #True_BASIC | True BASIC |
OPTION BASE 1
LET max = 10
DIM dat(10), res(10)
FOR i = 1 TO max
READ dat(i)
NEXT i
DATA 1, 2, 1, 4, 5, 2, 15, 1, 3, 4
LET res(1) = dat(1)
LET count = 1
LET posic = 1
DO WHILE posic < max
LET posic = posic + 1
LET esnuevo = 1
LET indice = 1
DO WHILE (indice <= count) AND esnuevo = 1
IF dat(p... |
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... | #Racket | Racket |
#lang racket
;; Racket has a useful `time*' macro that does just what's requested:
;; run some expression N times, and produce timing results
(require unstable/time)
;; Sample use:
(define (fib n) (if (<= n 1) n (+ (fib (- n 1)) (fib (- n 2)))))
(time* 10 (fib 38))
;; But of course, can be used to measure exter... |
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... | #Raku | Raku | sub runrate($N where $N > 0, &todo) {
my $n = $N;
my $start = now;
todo() while --$n;
my $end = now;
say "Start time: ", DateTime.new($start).Str;
say "End time: ", DateTime.new($end).Str;
my $elapsed = $end - $start;
say "Elapsed time: $elapsed seconds";
say "Rate: { ($N / $el... |
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
... | #min | min | ("" split reverse "" join) :reverse-str |
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... | #AutoHotkey | AutoHotkey | Points :=[{x: 5.0, y: 5.0}
, {x: 5.0, y: 8.0}
, {x:-10.0, y: 5.0}
, {x: 0.0, y: 5.0}
, {x: 10.0, y: 5.0}
, {x: 8.0, y: 5.0}
, {x: 10.0, y:10.0}]
Square :=[{x: 0.0, y: 0.0}, {x:10.0, y: 0.0}
, {x:10.0, y: 0.0}, {x:10.0, y:10.0}
, {x:10.0, y:10.0}, {x: 0.0, y:10.0}
, {x: 0.0, y:10.0}, {x: 0.0, y: 0.... |
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... | #Go | Go | package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
)
func main() {
if line, err := rsl("input.txt", 7); err == nil {
fmt.Println("7th line:")
fmt.Println(line)
} else {
fmt.Println("rsl:", err)
}
}
func rsl(fn string, n int) (string, error) {
if n < 1 {
return "", fmt.Errorf("invalid request:... |
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
... | #AutoHotkey | AutoHotkey | Rank(data, opt:=1){ ; opt = 1 Standard (default), 2 Modified, 3 Dense, 4 Ordinal, 5 Fractional
for index, val in StrSplit(data, "`n", "`r") {
RegExMatch(val, "^(\d+)\s+(.*)", Match)
if !(Match1=prev)
n := index
prev := Match1
Res1 .= n "`t" Match "`n"
Res4 .= index "`t" Match "`n"
Temp .= n ":" index " ... |
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
... | #TSE_SAL | TSE SAL |
//
// Go through the list, and for each element, check the rest of the list to see if it appears again, and discard it if it does.
//
INTEGER PROC FNBlockGetUniqueAllToBufferB( INTEGER bufferI )
INTEGER B = FALSE
INTEGER downB = TRUE
STRING s[255] = ""
IF ( NOT ( IsBlockInCurrFile() ) ) Warn( "Please mark a block... |
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... | #REXX | REXX | /*REXX program reports on the amount of elapsed time 4 different tasks use (wall clock).*/
time.= /*nullify times for all the tasks below*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
call time 'Reset' ... |
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
... | #MiniScript | MiniScript | str = "This is a string"
print "Forward: " + str
newStr = ""
for i in range(str.len-1, 0)
newStr = newStr + str[i]
end for
print "Reversed: " + newStr |
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... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct { double x, y; } vec;
typedef struct { int n; vec* v; } polygon_t, *polygon;
#define BIN_V(op, xx, yy) vec v##op(vec a,vec b){vec c;c.x=xx;c.y=yy;return c;}
#define BIN_S(op, r) double v##op(vec a, vec b){ return r; }
BIN_V(sub, a.x - b.x, a.y ... |
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... | #Groovy | Groovy | def line = null
new File("lines.txt").eachLine { currentLine, lineNumber ->
if (lineNumber == 7) {
line = currentLine
}
}
println "Line 7 = $line" |
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
... | #APL | APL | standard ← ∊∘(⌊\¨⊢⊂⍳∘≢)∘(1,2≠/⊢)∘(1⌷[2]⊢),⊢
modified ← ∊∘(⌈\∘⌽¨⊢⊂⍳∘≢)∘(1,2≠/⊢)∘(1⌷[2]⊢),⊢
dense ← (+\1,2≠/1⌷[2]⊢),⊢
ordinal ← ⍳∘≢,⊢
fractional ← ∊∘((≢(/∘⊢)+/÷≢)¨⊢⊂⍳∘≢)∘(1,2≠/⊢)∘(1⌷[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
... | #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
list_old="b'A'A'5'1'2'3'2'3'4"
list_sort=MIXED_SORT (list_old)
list_new=REDUCE (list_sort)
PRINT list_old
PRINT list_new
|
http://rosettacode.org/wiki/Range_consolidation | Range consolidation | Define a range of numbers R, with bounds b0 and b1 covering all numbers between and including both bounds.
That range can be shown as:
[b0, b1]
or equally as:
[b1, b0]
Given two ranges, the act of consolidation between them compares the two ranges:
If one range covers all of the other then t... | #11l | 11l | F consolidate(ranges)
F normalize(s)
R sorted(s.filter(bounds -> !bounds.empty).map(bounds -> sorted(bounds)))
V norm = normalize(ranges)
L(&r1) norm
V i = L.index
I !r1.empty
L(j) i + 1 .< norm.len
V& r2 = norm[j]
I !r2.empty & r1.last >= r2[0]
... |
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... | #Ring | Ring |
# Project : Rate counter
see "method 1: calculate reciprocal of elapsed time:" + nl
for trial = 1 to 3
start = clock()
tasktomeasure()
finish = clock()
see "rate = " + 100 / (finish-start) + " per second" + nl
next
see "method 2: count completed tasks in one second:" + nl
for trial = 1 to 3
r... |
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
... | #MIPS_Assembly | MIPS Assembly |
# First, it gets the length of the original string
# Then, it allocates memory from the copy
# Then it copies the pointer to the original string, and adds the strlen
# subtract 1, then that new pointer is at the last char.
# while(strlen)
# copy char
# decrement strlen
# decrement source pointer
# ... |
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... | #C.2B.2B | C++ | #include <algorithm>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <limits>
using namespace std;
const double epsilon = numeric_limits<float>().epsilon();
const numeric_limits<double> DOUBLE;
const double MIN = DOUBLE.min();
const double MAX = DOUBLE.max();
struct Point { const double x, y; }... |
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... | #Haskell | Haskell | main :: IO ()
main = do contents <- readFile filename
case drop 6 $ lines contents of
[] -> error "File has less than seven lines"
l:_ -> putStrLn l
where filename = "testfile" |
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
... | #AWK | AWK | ##
## Dense ranking in file: ranking_d.awk
##
BEGIN{ lastresult = "!"; lastrank = 0 }
function d_rank(){
if($1==lastresult){
print lastrank, $0
}else{
lastresult = $1
print ++lastrank, $0 }
}
//{d_rank() }
##
## Fractional ranking in file: ranking_f.awk
##
BEGIN{
last = "!"
... |
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
... | #UnixPipes | UnixPipes | bash$ # original list
bash$ printf '6\n2\n3\n6\n4\n2\n'
6
2
3
6
4
2
bash$ # made uniq
bash$ printf '6\n2\n3\n6\n4\n2\n'|sort -n|uniq
2
3
4
6
bash$ |
http://rosettacode.org/wiki/Range_consolidation | Range consolidation | Define a range of numbers R, with bounds b0 and b1 covering all numbers between and including both bounds.
That range can be shown as:
[b0, b1]
or equally as:
[b1, b0]
Given two ranges, the act of consolidation between them compares the two ranges:
If one range covers all of the other then t... | #Action.21 | Action! | INCLUDE "H6:REALMATH.ACT"
DEFINE PTR="CARD"
DEFINE RANGESIZE="12"
DEFINE LOW_="+0"
DEFINE HIGH_="+6"
TYPE Range=[CARD l1,l2,l3,h1,h2,h3]
PROC Inverse(Range POINTER r)
REAL tmp
RealAssign(r LOW_,tmp)
RealAssign(r HIGH_,r LOW_)
RealAssign(tmp,r HIGH_)
RETURN
PROC Normalize(Range POINTER r)
IF RealLess(r... |
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... | #Ruby | Ruby | require 'benchmark'
Document = Struct.new(:id,:a,:b,:c)
documents_a = []
documents_h = {}
1.upto(10_000) do |n|
d = Document.new(n)
documents_a << d
documents_h[d.id] = d
end
searchlist = Array.new(1000){ rand(10_000)+1 }
Benchmark.bm(10) do |x|
x.report('array'){searchlist.each{|el| documents_a.any?{|d| d.id... |
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
... | #Mirah | Mirah | def reverse(s:string)
StringBuilder.new(s).reverse
end
puts reverse('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... | #CoffeeScript | CoffeeScript | Point = (@x,@y) ->
pointInPoly = (point,poly) ->
segments = for pointA, index in poly
pointB = poly[(index + 1) % poly.length]
[pointA,pointB]
intesected = (segment for segment in segments when rayIntesectsSegment(point,segment))
intesected.length % 2 != 0
rayInte... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main()
write(readline("foo.bar.txt",7)|"failed")
end
procedure readline(f,n) # return n'th line of file f
f := open(\f,"r") | fail # open file
every i := n & line := |read(f) \ n do i -:= 1 # <== here
close(f)
if i = 0 then return line
end |
http://rosettacode.org/wiki/Read_a_configuration_file | Read a configuration file | The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# pr... | #11l | 11l | F readconf(fname)
[String = String] ret
L(=line) File(fname).read_lines()
line = line.trim((‘ ’, "\t", "\r", "\n"))
I line == ‘’ | line.starts_with(‘#’)
L.continue
V boolval = 1B
I line.starts_with(‘;’)
line = line.ltrim(‘;’)
I line.split_py().len != 1
... |
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
... | #BASIC | BASIC | 10 READ N
20 DIM S(N),N$(N),R(N)
30 FOR I=1 TO N: READ S(I),N$(I): NEXT
40 PRINT "--- Standard ranking ---": GOSUB 100: GOSUB 400
50 PRINT "--- Modified ranking ---": GOSUB 150: GOSUB 400
60 PRINT "--- Dense ranking ---": GOSUB 200: GOSUB 400
70 PRINT "--- Ordinal ranking ---": GOSUB 250: GOSUB 400
80 PRINT "--- Fracti... |
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
... | #Ursala | Ursala | #cast %s
example = |=hS& 'mississippi' |
http://rosettacode.org/wiki/Range_consolidation | Range consolidation | Define a range of numbers R, with bounds b0 and b1 covering all numbers between and including both bounds.
That range can be shown as:
[b0, b1]
or equally as:
[b1, b0]
Given two ranges, the act of consolidation between them compares the two ranges:
If one range covers all of the other then t... | #Ada | Ada | with Ada.Text_IO;
with Ada.Containers.Vectors;
procedure Range_Consolidation is
type Set_Type is record
Left, Right : Float;
end record;
package Set_Vectors is
new Ada.Containers.Vectors (Positive, Set_Type);
procedure Normalize (Set : in out Set_Vectors.Vector) is
function Less_... |
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... | #Run_BASIC | Run BASIC | html "<table bgcolor=wheat border=1><tr><td align=center colspan=2>Rate Counter</td></tr>
<tr><td>Run Job Times</td><td>"
textbox #runTimes,"10",3
html "</tr><tr><td align=center colspan=2>"
button #r,"Run", [runIt]
html " "
button #a, "Average", [ave]
html "</td></tr></table>"
wait
[runIt]... |
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
... | #Modula-2 | Modula-2 | MODULE ReverseStr;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar;
PROCEDURE WriteInt(n : INTEGER);
VAR buf : ARRAY[0..15] OF CHAR;
BEGIN
FormatString("%i", buf, n);
WriteString(buf)
END WriteInt;
PROCEDURE ReverseStr(in : ARRAY OF CHAR; VAR out : ARRAY OF CHA... |
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... | #Common_Lisp | Common Lisp | (defun point-in-polygon (point polygon)
(do ((in-p nil)) ((endp polygon) in-p)
(when (ray-intersects-segment point (pop polygon))
(setf in-p (not in-p)))))
(defun ray-intersects-segment (point segment &optional (epsilon .001))
(destructuring-bind (px . py) point
(destructuring-bind ((ax . ay) . (bx ... |
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... | #J | J | readLine=: 4 :0
(x-1) {:: <;.2 ] 1!:1 boxxopen y
) |
http://rosettacode.org/wiki/Read_a_configuration_file | Read a configuration file | The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# pr... | #Ada | Ada | with Config; use Config;
with Ada.Text_IO; use Ada.Text_IO;
procedure Rosetta_Read_Cfg is
cfg: Configuration:= Init("rosetta_read.cfg", Case_Sensitive => False, Variable_Terminator => ' ');
fullname : String := cfg.Value_Of("*", "fullname");
favouritefruit : String := cfg.Value_Of("*", "favouritefruit")... |
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
... | #C | C |
#include<stdlib.h>
#include<stdio.h>
typedef struct{
int score;
char name[100];
}entry;
void ordinalRanking(entry* list,int len){
int i;
printf("\n\nOrdinal Ranking\n---------------");
for(i=0;i<len;i++)
printf("\n%d\t%d\t%s",i+1,list[i].score,list[i].name);
}
void standardRanking(entry* list,int l... |
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
... | #VBA | VBA |
Option Explicit
Sub Main()
Dim myArr() As Variant, i As Long
myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, "Alpha", 1, 235, 4, 1.25, 1.25, "Beta", 1.23456789101112E+16, "Delta", "Alpha", "Charlie", 1, 2, "Foxtrot", "Foxtrot", "Alpha", 235))
'return :
For i = LBound(myArr) To UBo... |
http://rosettacode.org/wiki/Range_consolidation | Range consolidation | Define a range of numbers R, with bounds b0 and b1 covering all numbers between and including both bounds.
That range can be shown as:
[b0, b1]
or equally as:
[b1, b0]
Given two ranges, the act of consolidation between them compares the two ranges:
If one range covers all of the other then t... | #AutoHotkey | AutoHotkey | RangeConsolidation(arr){
arr1 := [], arr2 := [], result := []
for i, obj in arr
arr1[i,1] := min(arr[i]*), arr1[i,2] := max(arr[i]*) ; sort each range individually
for i, obj in arr1
if (obj.2 > arr2[obj.1])
arr2[obj.1] := obj.2 ; creates helper array sorted by range
i := 1
for start, stop in arr2
... |
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... | #Scala | Scala | def task(n: Int) = Thread.sleep(n * 1000)
def rate(fs: List[() => Unit]) = {
val jobs = fs map (f => scala.actors.Futures.future(f()))
val cnt1 = scala.actors.Futures.awaitAll(5000, jobs: _*).count(_ != None)
val cnt2 = scala.actors.Futures.awaitAll(5000, jobs: _*).count(_ != None)
val cnt3 = scala.actors.Futur... |
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
... | #Modula-3 | Modula-3 | MODULE Reverse EXPORTS Main;
IMPORT IO, Text;
PROCEDURE String(item: TEXT): TEXT =
VAR result: TEXT := "";
BEGIN
FOR i := Text.Length(item) - 1 TO 0 BY - 1 DO
result := Text.Cat(result, Text.FromChar(Text.GetChar(item, i)));
END;
RETURN result;
END String;
BEGIN
IO.Put(String("Foobarbaz"... |
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... | #D | D | import std.stdio, std.math, std.algorithm;
immutable struct Point { double x, y; }
immutable struct Edge { Point a, b; }
immutable struct Figure {
string name;
Edge[] edges;
}
bool contains(in Figure poly, in Point p) pure nothrow @safe @nogc {
static bool raySegI(in Point p, in Edge edge)
pure noth... |
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... | #Java | Java | package linenbr7;
import java.io.*;
public class LineNbr7 {
public static void main(String[] args) throws Exception {
File f = new File(args[0]);
if (!f.isFile() || !f.canRead())
throw new IOException("can't read " + args[0]);
BufferedReader br = new BufferedReader(new Fi... |
http://rosettacode.org/wiki/Read_a_configuration_file | Read a configuration file | The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# pr... | #Aime | Aime | record r, s;
integer c;
file f;
list l;
text an, d, k;
an = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
f.affix("tmp/config");
while ((c = f.peek) ^ -1) {
integer removed;
f.side(" \t\r");
c = f.peek;
removed = c == ';';
if (removed) {
f.pick;
f.side(" \... |
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
... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace RankingMethods {
class Program {
static void Main(string[] args) {
Dictionary<string, int> scores = new Dictionary<string, int> {
["Solomon"] = 44,
["Jason"] = 42,
["Err... |
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
... | #VBScript | VBScript |
Function remove_duplicates(list)
arr = Split(list,",")
Set dict = CreateObject("Scripting.Dictionary")
For i = 0 To UBound(arr)
If dict.Exists(arr(i)) = False Then
dict.Add arr(i),""
End If
Next
For Each key In dict.Keys
tmp = tmp & key & ","
Next
remove_duplicates = Left(tmp,Len(tmp)-1)
End Function
... |
http://rosettacode.org/wiki/Range_consolidation | Range consolidation | Define a range of numbers R, with bounds b0 and b1 covering all numbers between and including both bounds.
That range can be shown as:
[b0, b1]
or equally as:
[b1, b0]
Given two ranges, the act of consolidation between them compares the two ranges:
If one range covers all of the other then t... | #C | C | #include <stdio.h>
#include <stdlib.h>
typedef struct range_tag {
double low;
double high;
} range_t;
void normalize_range(range_t* range) {
if (range->high < range->low) {
double tmp = range->low;
range->low = range->high;
range->high = tmp;
}
}
int range_compare(const voi... |
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... | #Sidef | Sidef | var benchmark = frequire('Benchmark');
func job1 {
#...job1 code...
}
func job2 {
#...job2 code...
}
const COUNT = -1; # run for one CPU second
benchmark.timethese(COUNT, Hash.new('Job1' => job1, 'Job2' => job2)); |
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
... | #MUMPS | MUMPS | REVERSE
;Take in a string and reverse it using the built in function $REVERSE
NEW S
READ:30 "Enter a string: ",S
WRITE !,$REVERSE(S)
QUIT |
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... | #Factor | Factor | USING: kernel prettyprint sequences arrays math math.vectors ;
IN: raycasting
: between ( a b x -- ? ) [ last ] tri@ [ < ] curry bi@ xor ;
: lincomb ( a b x -- w )
3dup [ last ] tri@
[ - ] curry bi@
[ drop ] 2dip
neg 2dup + [ / ] curry bi@
[ [ v*n ] curry ] bi@ bi* v+ ;
: leftof ( a b x -- ? ) dup [ linc... |
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... | #jq | jq | # Input - a line number to read, counting from 1
# Output - a stream with 0 or 1 items
def read_line:
. as $in
| label $top
| foreach inputs as $line
(0; .+1; if . == $in then $line, break $top else empty end) ; |
http://rosettacode.org/wiki/Read_a_configuration_file | Read a configuration file | The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# pr... | #Arturo | Arturo | parseConfig: function [f][
lines: split.lines read f
lines: select map lines 'line [strip replace line {/[#;].*/} ""]
'line [not? empty? line]
result: #[]
fields: loop lines 'line [
field: first match line {/^[A-Z]+/}
rest: strip replace line field ""
... |
http://rosettacode.org/wiki/Read_a_file_line_by_line | Read a file line by line | Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
| #360_Assembly | 360 Assembly | * Read a file line by line 12/06/2016
READFILE CSECT
SAVE (14,12) save registers on entry
PRINT NOGEN
BALR R12,0 establish addressability
USING *,R12 set base register
ST R13,SAVEA+4 link mySA->prevSA
LA ... |
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
... | #C.2B.2B | C++ | #include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <ostream>
#include <set>
#include <vector>
template<typename T>
std::ostream& print(std::ostream& os, const T& src) {
auto it = src.cbegin();
auto end = src.cend();
os << "[";
if (it != end) {
os << *it;
... |
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
... | #Vedit_macro_language | Vedit macro language | Sort(0, File_Size) // sort the data
While(Replace("^(.*)\N\1$", "\1", REGEXP+BEGIN+NOERR)){} // remove duplicates |
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
... | #Vim_Script | Vim Script | call filter(list, 'count(list, v:val) == 1') |
http://rosettacode.org/wiki/Range_consolidation | Range consolidation | Define a range of numbers R, with bounds b0 and b1 covering all numbers between and including both bounds.
That range can be shown as:
[b0, b1]
or equally as:
[b1, b0]
Given two ranges, the act of consolidation between them compares the two ranges:
If one range covers all of the other then t... | #C.23 | C# | using static System.Math;
using System.Linq;
using System;
public static class RangeConsolidation
{
public static void Main() {
foreach (var list in new [] {
new[] { (1.1, 2.2) }.ToList(),
new[] { (6.1, 7.2), (7.2, 8.3) }.ToList(),
new[] { (4d, 3d), (2, 1) }.ToList(),
... |
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... | #Smalltalk | Smalltalk | |times|
times := Bag new.
1 to: 10 do: [:n| times add:
(Time millisecondsToRun: [3000 factorial])].
Transcript show: times average asInteger. |
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
... | #Nanoquery | Nanoquery | def reverse(string)
l = ""
for char in list(str(string)).reverse()
l += char
end
return l
end |
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... | #Fortran | Fortran | module Polygons
use Points_Module
implicit none
type polygon
type(point), dimension(:), allocatable :: points
integer, dimension(:), allocatable :: vertices
end type polygon
contains
function create_polygon(pts, vt)
type(polygon) :: create_polygon
type(point), dimension(:), intent(in) ... |
http://rosettacode.org/wiki/Random_sentence_from_book | Random sentence from book | Read in the book "The War of the Worlds", by H. G. Wells.
Skip to the start of the book, proper.
Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ?
Keep account of what words follow words and how many times it is seen, (treat sentence terminators as words too).
Keep a... | #ALGOL_68 | ALGOL 68 | # generate random sentences using text from a book as a basis #
# use the associative array in the Associate array/iteration task #
PR read "aArray.a68" PR
# returns s with chars removed #
PRIO REMOVE = 1;
OP REMOVE = ( STRING s, chars )STRING:
BEGIN
[ ... |
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... | #Julia | Julia | open(readlines, "path/to/file")[7] |
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... | #Kotlin | Kotlin | // version 1.1.2
import java.io.File
fun main(args: Array<String>) {
/* The following code reads the whole file into memory
and so should not be used for large files
which should instead be read line by line until the
desired line is reached */
val lines = File("input.txt").readLines(... |
http://rosettacode.org/wiki/Read_a_configuration_file | Read a configuration file | The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# pr... | #AutoHotkey | AutoHotkey |
; Author: AlephX, Aug 18 2011
data = %A_scriptdir%\rosettaconfig.txt
comma := ","
Loop, Read, %data%
{
if NOT (instr(A_LoopReadLine, "#") == 1 OR A_LoopReadLine == "")
{
if instr(A_LoopReadLine, ";") == 1
{
parameter := RegExReplace(Substr(A_LoopReadLine,2), "^[ \s]+|[ \s]+$", "")
%parameter% = "1... |
http://rosettacode.org/wiki/Read_a_file_line_by_line | Read a file line by line | Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
| #8th | 8th |
"path/to/file" f:open ( . cr ) f:eachline f:close
|
http://rosettacode.org/wiki/Read_a_file_line_by_line | Read a file line by line | Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program readfile64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM... |
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
... | #Cowgol | Cowgol | include "cowgol.coh";
# List of competitors
record Competitor is
score: uint8;
name: [uint8];
end record;
var cs: Competitor[] := {
{44, "Solomon"},
{42, "Jason"},
{42, "Errol"},
{41, "Garry"},
{41, "Bernard"},
{41, "Barry"},
{39, "Stephen"}
};
# Rank competitors given ranking ... |
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
... | #Visual_FoxPro | Visual FoxPro |
LOCAL i As Integer, n As Integer, lcOut As String
CLOSE DATABASES ALL
CLEAR
CREATE CURSOR nums (num I)
INDEX ON num TAG num COLLATE "Machine"
SET ORDER TO 0
n = 50
RAND(-1)
FOR i = 1 TO n
INSERT INTO nums VALUES (RanInt(1, 10))
ENDFOR
SELECT num, COUNT(num) As cnt FROM nums ;
GROUP BY num INTO CURSOR grouped
LIST... |
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
... | #Wart | Wart | def (dedup l)
let exists (table)
collect+each x l
unless exists.x
yield x
exists.x <- 1 |
http://rosettacode.org/wiki/Range_consolidation | Range consolidation | Define a range of numbers R, with bounds b0 and b1 covering all numbers between and including both bounds.
That range can be shown as:
[b0, b1]
or equally as:
[b1, b0]
Given two ranges, the act of consolidation between them compares the two ranges:
If one range covers all of the other then t... | #C.2B.2B | C++ | #include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
// A range is represented as std::pair<from, to>
template <typename iterator>
void normalize_ranges(iterator begin, iterator end) {
for (iterator i = begin; i != end; ++i) {
if (i->second < i->first)
std::swap(i->f... |
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... | #Tcl | Tcl | set iters 10
# A silly example task
proc theTask {} {
for {set a 0} {$a < 100000} {incr a} {
expr {$a**3+$a**2+$a+1}
}
}
# Measure the time taken $iters times
for {set i 1} {$i <= $iters} {incr i} {
set t [lindex [time {
theTask
}] 0]
puts "task took $t microseconds on iteration ... |
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
... | #Neko | Neko | /* Reverse a string, in Neko */
var reverse = function(s) {
var len = $ssize(s)
if len < 2 return s
var reverse = $smake(len)
var pos = 0
while len > 0 $sset(reverse, pos ++= 1, $sget(s, len -= 1))
return reverse
}
var str = "never odd or even"
$print(str, "\n")
$print(reverse(str), "\n\n")
str = "a... |
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... | #FreeBASIC | FreeBASIC | Type Point
As Single x,y
End Type
Function inpolygon(p1() As Point,p2 As Point) As Integer
#Macro 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))
#EndMacro
Dim As Integer index,nextindex
Dim k As Integer=UBound(p1)+1
Dim send (1 To 2) As Point
Dim wn As Integer=0
F... |
http://rosettacode.org/wiki/Random_sentence_from_book | Random sentence from book | Read in the book "The War of the Worlds", by H. G. Wells.
Skip to the start of the book, proper.
Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ?
Keep account of what words follow words and how many times it is seen, (treat sentence terminators as words too).
Keep a... | #Julia | Julia | """ weighted random pick of items in a Dict{String, Int} where keys are words, values counts """
function weightedrandompick(dict, total)
n = rand(1:total)
for (key, value) in dict
n -= value
if n <= 0
return key
end
end
return last(keys(dict))
end
let
""" Read ... |
http://rosettacode.org/wiki/Random_sentence_from_book | Random sentence from book | Read in the book "The War of the Worlds", by H. G. Wells.
Skip to the start of the book, proper.
Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ?
Keep account of what words follow words and how many times it is seen, (treat sentence terminators as words too).
Keep a... | #Nim | Nim | import random, sequtils, strutils, tables
from unicode import utf8
const StopChars = [".", "?", "!"]
proc weightedChoice(choices: CountTable[string]; totalCount: int): string =
## Return a string from "choices" key using counts as weights.
var n = rand(1..totalCount)
for word, count in choices.pairs:
dec ... |
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... | #Lasso | Lasso | local(f) = file('unixdict.txt')
handle => { #f->close }
local(this_line = string,line = 0)
#f->forEachLine => {
#line++
#line == 7 ? #this_line = #1
#line == 7 ? loop_abort
}
#this_line // 6th, which is the 7th line in the file
|
http://rosettacode.org/wiki/Read_a_configuration_file | Read a configuration file | The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# pr... | #AWK | AWK |
# syntax: GAWK -f READ_A_CONFIGURATION_FILE.AWK
BEGIN {
fullname = favouritefruit = ""
needspeeling = seedsremoved = "false"
fn = "READ_A_CONFIGURATION_FILE.INI"
while (getline rec <fn > 0) {
tmp = tolower(rec)
if (tmp ~ /^ *fullname/) { fullname = extract(rec) }
else if (tmp ~ /^ *f... |
http://rosettacode.org/wiki/Rare_numbers | Rare numbers | Definitions and restrictions
Rare numbers are positive integers n where:
n is expressed in base ten
r is the reverse of n (decimal digits)
n must be non-palindromic (n ≠ r)
(n+r) is the sum
(n-r) is the difference and must be positive
the sum and the ... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;
using UI = System.UInt64;
using LST = System.Collections.Generic.List<System.Collections.Generic.List<sbyte>>;
using Lst = System.Collections.Generic.List<sbyte>;
using DT = System.DateTime;
class Program {
const sby... |
http://rosettacode.org/wiki/Range_expansion | Range expansion | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range s... | #11l | 11l | F rangeexpand(txt)
[Int] lst
L(r) txt.split(‘,’)
I ‘-’ C r[1..]
V rr = r[1..].split(‘-’, 2)
lst [+]= Int(r[0]‘’rr[0]) .. Int(rr[1])
E
lst.append(Int(r))
R lst
print(rangeexpand(‘-6,-3--1,3-5,7-11,14,15,17-20’)) |
http://rosettacode.org/wiki/Read_a_file_line_by_line | Read a file line by line | Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
| #Action.21 | Action! | char array TXT
Proc Main()
Open (1,"D:FILENAME.TXT",4,0)
Do
InputSD(1,TXT)
PrintE(TXT)
Until EOF(1)
Od
Close(1)
Return
|
http://rosettacode.org/wiki/Read_a_file_line_by_line | Read a file line by line | Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Line_By_Line is
File : File_Type;
begin
Open (File => File,
Mode => In_File,
Name => "line_by_line.adb");
While not End_Of_File (File) Loop
Put_Line (Get_Line (File));
end loop;
Close (File);
end Line_By_Line;
|
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
... | #D | D | import std.algorithm;
import std.stdio;
void main() {
immutable scores = [
"Solomon": 44,
"Jason": 42,
"Errol": 42,
"Garry": 41,
"Bernard": 41,
"Barry": 41,
"Stephen": 39
];
scores.standardRank;
scores.modifiedRank;
scores.denseRank;
sc... |
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
... | #Wortel | Wortel | @uniq [1 2 3 2 1 2 3] ; returns [1 2 3] |
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
... | #Wren | Wren | import "/sort" for Sort
// Using a map - order of distinct items is undefined.
var removeDuplicates1 = Fn.new { |a|
if (a.count <= 1) return a
var m = {}
for (e in a) m[e] = true
return m.keys.toList
}
// Sort elements and remove consecutive duplicates.
var removeDuplicates2 = Fn.new { |a|
if (a... |
http://rosettacode.org/wiki/Range_consolidation | Range consolidation | Define a range of numbers R, with bounds b0 and b1 covering all numbers between and including both bounds.
That range can be shown as:
[b0, b1]
or equally as:
[b1, b0]
Given two ranges, the act of consolidation between them compares the two ranges:
If one range covers all of the other then t... | #Clojure | Clojure | (defn normalize [r]
(let [[n1 n2] r]
[(min n1 n2) (max n1 n2)]))
(defn touch? [r1 r2]
(let [[lo1 hi1] (normalize r1)
[lo2 hi2] (normalize r2)]
(or (<= lo2 lo1 hi2)
(<= lo2 hi1 hi2))))
(defn consolidate-touching-ranges [rs]
(let [lows (map #(apply min %) rs)
highs (map #(apply ... |
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... | #UNIX_Shell | UNIX Shell | #!/bin/bash
while : ; do
task && echo >> .fc
done |
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... | #Vlang | Vlang | import rand
import time
// representation of time.Time is nanosecond, actual resolution system specific
struct RateStateS {
mut:
last_flush time.Time
period time.Duration
tick_count int
}
fn (mut p_rate RateStateS) tic_rate() {
p_rate.tick_count++
now := time.now()
if now-p_rate.last_flus... |
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
... | #Nemerle | Nemerle | ncc -reference:System.Windows.Forms reverse.n |
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... | #Go | Go | package main
import (
"fmt"
"math"
)
type xy struct {
x, y float64
}
type seg struct {
p1, p2 xy
}
type poly struct {
name string
sides []seg
}
func inside(pt xy, pg poly) (i bool) {
for _, side := range pg.sides {
if rayIntersectsSegment(pt, side) {
i = !i
... |
http://rosettacode.org/wiki/Random_sentence_from_book | Random sentence from book | Read in the book "The War of the Worlds", by H. G. Wells.
Skip to the start of the book, proper.
Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ?
Keep account of what words follow words and how many times it is seen, (treat sentence terminators as words too).
Keep a... | #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Random_sentence_from_book
use warnings;
my $book = do { local (@ARGV, $/) = 'waroftheworlds.txt'; <> };
my (%one, %two);
s/^.*?START OF THIS\N*\n//s, s/END OF THIS.*//s,
tr/a-zA-Z.!?/ /c, tr/ / /s for $book;
my $qr = qr/(\b\w+\b|[.!?])/;
$one{$1}{$2}+... |
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... | #Liberty_BASIC | Liberty BASIC | fileName$ ="F:\sample.txt"
requiredLine =7
open fileName$ for input as #i
f$ =input$( #i, lof( #i))
close #i
line7$ =word$( f$, 7, chr$( 13))
if line7$ =chr$( 13) +chr$( 10) or line7$ ="" then notice "Empty line! ( or file has fewer lines)."
print line7$ |
http://rosettacode.org/wiki/Read_a_configuration_file | Read a configuration file | The task is to read a configuration file in standard configuration file format,
and set variables accordingly.
For this task, we have a configuration file as follows:
# This is a configuration file in standard configuration file format
#
# Lines beginning with a hash or a semicolon are ignored by the application
# pr... | #BASIC | BASIC |
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' '
' Read a Configuration File V1.0 '
' '
' Developed by A. David Garza Marín in VB-DOS for '
' RosettaCode. December 2, 2016. '
' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ' ... |
http://rosettacode.org/wiki/Rare_numbers | Rare numbers | Definitions and restrictions
Rare numbers are positive integers n where:
n is expressed in base ten
r is the reverse of n (decimal digits)
n must be non-palindromic (n ≠ r)
(n+r) is the sum
(n-r) is the difference and must be positive
the sum and the ... | #C.2B.2B | C++ |
// Rare Numbers : Nigel Galloway - December 20th., 2019;
// Nigel Galloway/Enter your username - January 4th., 2021 (see discussion page.
#include <functional>
#include <bitset>
#include <cmath>
using namespace std;
using Z2 = optional<long long>; using Z1 = function<Z2()>;
// powers of 10 array
constexpr auto pow10 ... |
http://rosettacode.org/wiki/Range_expansion | Range expansion | A format for expressing an ordered list of integers is to use a comma separated list of either
individual integers
Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints)
The range s... | #8th | 8th | \ Given a low and high limit, create an array containing the numbers in the
\ range, inclusive:
: n:gen-range \ low hi -- a
\ make sure they are in order:
2dup n:> if swap then
\ fill the array with the values:
[] ' a:push
2swap loop ;
\ Take a string, either "X" or "X-Y", and correctly return either a num... |
http://rosettacode.org/wiki/Read_a_file_line_by_line | Read a file line by line | Read a file one line at a time,
as opposed to reading the entire file at once.
Related tasks
Read a file character by character
Input loop.
| #Aime | Aime | file f;
text s;
f.affix("src/aime.c");
while (f.line(s) != -1) {
o_text(s);
o_byte('\n');
} |
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
... | #Elixir | Elixir | defmodule Ranking do
def methods(data) do
IO.puts "stand.\tmod.\tdense\tord.\tfract."
Enum.group_by(data, fn {score,_name} -> score end)
|> Enum.map(fn {score,pairs} ->
names = Enum.map(pairs, fn {_,name} -> name end) |> Enum.reverse
{score, names}
end)
|> Enum.sort_by(fn {sco... |
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
... | #XBS | XBS | func RemoveDuplicates(Array){
set NewArray = [];
foreach(k,v as Array){
if (NewArray->includes(v)){
Array->splice(toint(k),1);
} else {
NewArray->push(v);
}
}
}
set Arr = ["Hello",1,2,"Hello",3,1];
log(Arr);
RemoveDuplicates(Arr);
log(Arr); |
http://rosettacode.org/wiki/Range_consolidation | Range consolidation | Define a range of numbers R, with bounds b0 and b1 covering all numbers between and including both bounds.
That range can be shown as:
[b0, b1]
or equally as:
[b1, b0]
Given two ranges, the act of consolidation between them compares the two ranges:
If one range covers all of the other then t... | #Dyalect | Dyalect | type Pt(s, e) with Lookup
func Pt.Min() => min(this.s, this.e)
func Pt.Max() => max(this.s, this.e)
func Pt.ToString() => "(\(this.s), \(this.e))"
let rng = [
[ Pt(1.1, 2.2) ],
[ Pt(6.1, 7.2), Pt(7.2, 8.3) ],
[ Pt(4.0, 3.0), Pt(2, 1) ],
[ Pt(4.0, 3.0), Pt(2, 1), Pt(-1, 2), Pt(3.9, 10) ],
[ Pt(... |
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... | #Wren | Wren | var cube = Fn.new { |n| n * n * n }
var benchmark = Fn.new { |n, func, arg, calls|
var times = List.filled(n, 0)
for (i in 0...n) {
var m = System.clock
for (j in 0...calls) func.call(arg)
times[i] = ((System.clock - m) * 1000).round // milliseconds
}
return times
}
System.p... |
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
... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols nobinary
reverseThis = 'asdf'
sihTesrever = reverseThis.reverse
say reverseThis
say sihTesrever
return |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.