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/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Neko | Neko | /**
Detect division by zero
*/
var ans = 1.0 / 0.0
if $isinfinite(ans) $print("division by zero: ", ans, "\n")
ans = 1 / 0
if $isinfinite(ans) $print("division by zero: ", ans, "\n")
try $print($idiv(1, 0)) catch problem $print("idiv by zero: ", problem, "\n") |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #NetLogo | NetLogo | ;; Division by zero detection using CAREFULLY
;; The CAREFULLY clause exists in NetLogo since version 2.0
;; In prior versions of NetLogo, you must examine the divisor prior to performing the division.
;; The variables result, a, and b must all be previously created global, local, or agent -own'd variables.
;; NetL... |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #jq | jq | try tonumber catch false |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #Julia | Julia | using Printf
isnumber(s::AbstractString) = tryparse(Float64, s) isa Number
tests = ["1", "-121", "one", "pi", "1 + 1", "NaN", "1234567890123456789", "1234567890123456789123456789",
"1234567890123456789123456789.0", "1.3", "1.4e10", "Inf", "1//2", "1.0 + 1.0im"]
for t in tests
fl = isnumber(t) ? "is" :... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #Ring | Ring |
inputStr = ["",".","abcABC","XYZ ZYX","1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"]
for Str in inputStr
for x = 1 to len(Str)
for y = x + 1 to len(Str)
if Str[x] = Str[y]
char = Str[x]
? "Input = " + "'" + Str + "'" + ", length = " + len(Str)
? " First ... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #Ruby | Ruby | strings = ["",
".",
"abcABC",
"XYZ ZYX",
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
"hétérogénéité",
"🎆🎃🎇🎈",
"😍😀🙌💃😍🙌",
"🐠🐟🐡🦈🐬🐳🐋🐡",]
strings.each do |str|
seen = {}
print "#{str.inspect... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #Sidef | Sidef | func analyze_string(str) {
var chars = str.chars
chars.range.to_a.each_cons(2, {|a,b|
chars[a] == chars[b] || return b
})
return str.len
}
var strings = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄"]
strings.each {|str|
print "'#{str}' (size #{str... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #SQL | SQL |
/*
This code is an implementation of "Determination if a string has all the same characters" in SQL ORACLE 19c
p_in_str -- input string
*/
WITH
FUNCTION same_characters_in_string(p_in_str IN varchar2) RETURN varchar2 IS
v_que varchar2(32767) := p_in_str;
v_res varchar2(32767);
v_first varchar2(1);
... |
http://rosettacode.org/wiki/Dining_philosophers | Dining philosophers | The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou... | #Wren | Wren | import "random" for Random
import "scheduler" for Scheduler
import "timer" for Timer
var Rand = Random.new()
var ForkInUse = List.filled(5, false)
class Fork {
construct new(name, index) {
_name = name
_index = index
}
index { _index }
pickUp(philosopher) {
System.print... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Swift | Swift | import Foundation
let monthDays = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
let seasons = ["Chaos", "Discord", "Confusion", "Bureacracy", "The Aftermath"]
let dayNames = ["Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"]
let holyDays1 = ["Mungday", "Mojoday", "Syaday", "Zaraday"... |
http://rosettacode.org/wiki/Dijkstra%27s_algorithm | Dijkstra's algorithm | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro... | #VBA | VBA | Class Branch
Public from As Node '[according to Dijkstra the first Node should be closest to P]
Public towards As Node
Public length As Integer '[directed length!]
Public distance As Integer '[from P to farthest node]
Public key As String
Class Node
Public key As String
Public correspondingBranch As Branch
Const INFINI... |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displ... | #Quackery | Quackery | [ abs 0 swap
[ base share /mod
rot + swap
dup 0 = until ]
drop ] is digitsum ( n --> n )
[ 0 swap
[ dup base share > while
dip 1+
digitsum again ] ] is digitalroot ( n --> n n )
[ dup digitalroot
rot echo
say " has additive persistance "
... |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displ... | #R | R | y=1
digital_root=function(n){
x=sum(as.numeric(unlist(strsplit(as.character(n),""))))
if(x<10){
k=x
}else{
y=y+1
assign("y",y,envir = globalenv())
k=digital_root(x)
}
return(k)
}
print("Given number has additive persistence",y) |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #Nim | Nim | # Compile time error when a and b are differently sized arrays
# Runtime error when a and b are differently sized seqs
proc dotp[T](a,b: T): int =
doAssert a.len == b.len
for i in a.low..a.high:
result += a[i] * b[i]
echo dotp([1,3,-5], [4,-2,-1])
echo dotp(@[1,2,3],@[4,5,6]) |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #Oberon-2 | Oberon-2 |
MODULE DotProduct;
IMPORT
Out := NPCT:Console;
VAR
x,y: ARRAY 3 OF LONGINT;
PROCEDURE DotProduct(a,b: ARRAY OF LONGINT): LONGINT;
VAR
resp, i: LONGINT;
BEGIN
ASSERT(LEN(a) = LEN(b));
resp := 0;
FOR i := 0 TO LEN(x) - 1 DO
INC(resp,x[i]*y[i])
END;
RETURN resp
END DotProduct;
BEGIN
x[0] := ... |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and mu... | #Go | Go | package main
import "fmt"
func main() {
fmt.Println("Police Sanitation Fire")
fmt.Println("------ ---------- ----")
count := 0
for i := 2; i < 7; i += 2 {
for j := 1; j < 8; j++ {
if j == i { continue }
for k := 1; k < 8; k++ {
if k == i || k == j ... |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects ... | #Vorpal | Vorpal | a = new()
a.f = method(){
.x.print()
}
c = new()
c.g = method(){
(.x + 1).print()
}
# array of delegates
b = new()
b.delegate = new()
b.delegate[0] = a
b.delegate[1] = c
b.x = 3
b.f()
b.g()
# single delegate
d = new()
d.delegate = a
d.x = 7
d.f() |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects ... | #Wren | Wren | class Thingable {
thing { }
}
// Delegate that doesn't implement Thingable
class Delegate {
construct new() { }
}
// Delegate that implements Thingable
class Delegate2 is Thingable {
construct new() { }
thing { "delegate implementation" }
}
class Delegator {
construct new() {
_delega... |
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Class Triangle
Property P1 As Tuple(Of Double, Double)
Property P2 As Tuple(Of Double, Double)
Property P3 As Tuple(Of Double, Double)
Sub New(p1 As Tuple(Of Double, Double), p2 As Tuple(Of Double, Double), p3 As Tuple(Of Double, Double))
Me.P1 = p1
... |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Maple | Maple | FileTools:-Remove("input.txt");
FileTools:-RemoveDirectory("docs");
FileTools:-Remove("/input.txt");
FileTools:-RemoveDirectory("/docs");
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | wd = NotebookDirectory[];
DeleteFile[wd <> "input.txt"]
DeleteFile["/" <> "input.txt"]
DeleteDirectory[wd <> "docs"]
DeleteDirectory["/" <> "docs"] |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function Minor(a As Double(,), x As Integer, y As Integer) As Double(,)
Dim length = a.GetLength(0) - 1
Dim result(length - 1, length - 1) As Double
For i = 1 To length
For j = 1 To length
If i < x AndAlso j < y Then
result(i -... |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
method divide(dividend, divisor) public constant returns Rexx
do
quotient = dividend / divisor
catch exu = DivideException
exu.printStackTrace()
quotient = 'undefined'
catch exr = RuntimeException
exr.printStackTrace()
... |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #NewLISP | NewLISP | #! /usr/local/bin/newlisp
(define (check-division x y)
(catch (/ x y) 'check-zero)
(if (not (integer? check-zero))
(setq check-zero "Division by zero."))
check-zero
)
(println (check-division 10 4))
(println (check-division 4 0))
(println (check-division 20 5))
(println (check-division 11 0)... |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #Kotlin | Kotlin | // version 1.1
fun isNumeric(input: String): Boolean =
try {
input.toDouble()
true
} catch(e: NumberFormatException) {
false
}
fun main(args: Array<String>) {
val inputs = arrayOf("152", "-3.1415926", "Foo123", "-0", "456bar", "1.0E10")
for (input in inputs) println("$inp... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #Rust | Rust | fn unique(s: &str) -> Option<(usize, usize, char)> {
s.chars().enumerate().find_map(|(i, c)| {
s.chars()
.enumerate()
.skip(i + 1)
.find(|(_, other)| c == *other)
.map(|(j, _)| (i, j, c))
})
}
fn main() {
let strings = [
"",
".",
... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #Sidef | Sidef | func index_duplicates(str) {
gather {
for k,v in (str.chars.kv) {
var i = str.index(v, k+1)
take([k, i]) if (i != -1)
}
}
}
var strings = [
"", ".", "abcABC", "XYZ ZYX",
"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ",
"01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X",
"... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #Standard_ML | Standard ML |
datatype result=allSame | difference of string*char*int ;
val chkstring = fn input =>
let
val rec chk = fn ([],n) => allSame
| ([x],n) => allSame
| (x::y::t,n)=> if x=y then chk (y::t,n+1)
else difference (Int.fmt StringCvt.HEX(Char.ord(y)),y,n)
in
( ... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #Tcl | Tcl | package require Tcl 8.6 ; # For binary encode
array set yesno {1 Yes 0 No}
set test {
{}
{ }
{2}
{333}
{.55}
{tttTTT}
{4444 444k}
{jjjjjjj}
}
# Loop through test strings
foreach str $test {
set chars [dict create] ; # init dictionary
set same 1
set prev {}
# Loop ... |
http://rosettacode.org/wiki/Dining_philosophers | Dining philosophers | The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou... | #zkl | zkl | var [const] forks=(5).pump(List,Atomic.Bool.fp(False)), // True==fork in use
seats=(5).pump(List,'wrap(n){ List(forks[n],forks[(n+1)%5]) });
fcn sitAndEat(name,n){ // assigned seating
while(1){
fa,fb:=seats[n].shuffle(); // ambidextrous
if(fa.setIf(True,False)){ // got the first fork
if(fb.setIf... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Tcl | Tcl | package require Tcl 8.5
proc disdate {year month day} {
# Get the day of the year
set now [clock scan [format %02d-%02d-%04d $day $month $year] -format %d-%m-%Y]
scan [clock format $now -format %j] %d doy
# Handle leap years
if {!($year%4) && (($year%100) || !($year%400))} {
if {$doy == 60} {
... |
http://rosettacode.org/wiki/Dijkstra%27s_algorithm | Dijkstra's algorithm | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro... | #Wren | Wren | import "/dynamic" for Tuple
import "/trait" for Comparable
import "/sort" for Cmp, Sort
import "/set" for Set
var Edge = Tuple.create("Edge", ["v1", "v2", "dist"])
// One vertex of the graph, complete with mappings to neighboring vertices
class Vertex is Comparable {
static map { __map } // maps a name to its ... |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displ... | #Racket | Racket | #lang racket
(define/contract (additive-persistence/digital-root n (ap 0))
(->* (natural-number/c) (natural-number/c) (values natural-number/c natural-number/c))
(define/contract (sum-digits x (acc 0))
(->* (natural-number/c) (natural-number/c) natural-number/c)
(if (= x 0)
acc
(let-values... |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displ... | #Raku | Raku | sub digroot ($r, :$base = 10) {
my $root = $r.base($base);
my $persistence = 0;
while $root.chars > 1 {
$root = [+]($root.comb.map({:36($_)})).base($base);
$persistence++;
}
$root, $persistence;
}
my @testnums =
627615,
39390,
588225,
393900588225,
5814271898167... |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #Objeck | Objeck | bundle Default {
class DotProduct {
function : Main(args : String[]) ~ Nil {
DotProduct([1, 3, -5], [4, -2, -1])->PrintLine();
}
function : DotProduct(array_a : Int[], array_b : Int[]) ~ Int {
if(array_a = Nil) {
return 0;
};
if(array_b = Nil) {
return 0;
... |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and mu... | #Groovy | Groovy | class DepartmentNumbers {
static void main(String[] args) {
println("Police Sanitation Fire")
println("------ ---------- ----")
int count = 0
for (int i = 2; i <= 6; i += 2) {
for (int j = 1; j <= 7; ++j) {
if (j == i) continue
for (int... |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects ... | #zkl | zkl | class Thingable{ var thing; }
class Delegator{
var delegate;
fcn operation{
if (delegate) delegate.thing;
else "default implementation"
}
}
class Delegate(Thingable){ thing = "delegate implementation" } |
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)... | #Vlang | Vlang | struct Point {
x f64
y f64
}
fn (p Point) str() string {
return "(${p.x:.1f}, ${p.y:.1f})"
}
struct Triangle {
mut:
p1 Point
p2 Point
p3 Point
}
fn (t Triangle) str() string {
return "Triangle $t.p1, $t.p2, $t.p3"
}
fn (t Triangle) det_2d() f64 {
return t.p1.x * (t.p2.y - t.p3.y) +
... |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #MATLAB_.2F_Octave | MATLAB / Octave | delete('input.txt'); % delete local file input.txt
delete('/input.txt'); % delete file /input.txt
rmdir('docs'); % remove local directory docs
rmdir('/docs'); % remove directory /docs
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #MAXScript | MAXScript | -- Here
deleteFile "input.txt"
-- Root
deleteFile "\input.txt" |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
... | #VBA | VBA | Option Base 1
Private Function minor(a As Variant, x As Integer, y As Integer) As Variant
Dim l As Integer: l = UBound(a) - 1
Dim result() As Double
If l > 0 Then ReDim result(l, l)
For i = 1 To l
For j = 1 To l
result(i, j) = a(i - (i >= x), j - (j >= y))
Next j
Next i
... |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Nim | Nim | {.push overflowChecks: on.}
proc divCheck(x, y): bool =
try:
discard x div y
except DivByZeroDefect:
return true
return false
{.pop.} # Restore default check settings
echo divCheck(2, 0) |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #NS-HUBASIC | NS-HUBASIC | 10 ON ERROR GOTO 40
20 PRINT 1/0
30 END
40 IF ERR = 10 THEN PRINT "DIVISION BY ZERO IN LINE"ERL
50 RESUME 30 |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #OCaml | OCaml | let div_check x y =
try
ignore (x / y);
false
with Division_by_zero ->
true |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #LabVIEW | LabVIEW | local(str='12345')
string_isNumeric(#str) // true |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #Lasso | Lasso | local(str='12345')
string_isNumeric(#str) // true |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #Tcl | Tcl | package require Tcl 8.6 ; # For binary encode
array set yesno {1 Yes 2 No}
set test {
{}
{.}
{abcABC}
{XYZ ZYX}
{1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ}
{hétérogénéité}
}
# Loop through test strings
foreach str $test {
set chars [dict create] ; # init dictionary
set num_chars 1 ; # I... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #VBA | VBA |
Sub Main_SameCharacters()
Dim arr, i As Integer, respons As Integer
arr = Array("", " ", "2", "333", ".55", "tttTTT", "4444 444k", "111111112", " 123")
For i = LBound(arr) To UBound(arr)
If SameCharacters(arr(i), respons) Then
Debug.Print "Analyze : [" & arr(i) & "], lenght " & Len(arr(i... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Analyze(s As String)
Console.WriteLine("Examining [{0}] which has a length of {1}:", s, s.Length)
If s.Length > 1 Then
Dim b = s(0)
For i = 1 To s.Length
Dim c = s(i - 1)
If c <> b Then
Console.WriteLine... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Wren | Wren | import "/date" for Date
import "/fmt" for Fmt
var seasons = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"]
var weekdays = ["Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"]
var apostles = ["Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay"]
var holidays = ["Chaoflux", "D... |
http://rosettacode.org/wiki/Dijkstra%27s_algorithm | Dijkstra's algorithm | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro... | #zkl | zkl | const INF=(0).MAX;
fcn dijkstra(graph,start,dst){
Q :=graph.copy();
prev:=graph.keys.pump(Dictionary().add.fp1(Void));
dist:=graph.keys.pump(Dictionary().add.fp1(INF));
dist[start]=0;
while(Q){
Q.reduce('wrap(min,[(v,_)],ru){
if((d:=dist[v])<min){ ru.set(v); d } else min },
IN... |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displ... | #REXX | REXX | /* REXX ***************************************************************
* Test digroot
**********************************************************************/
/* n r p */
say right(7 ,12) d... |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #Objective-C | Objective-C | #import <stdio.h>
#import <stdint.h>
#import <stdlib.h>
#import <string.h>
#import <Foundation/Foundation.h>
// this class exists to return a result between two
// vectors: if vectors have different "size", valid
// must be NO
@interface VResult : NSObject
{
@private
double value;
BOOL valid;
}
+(instancetype)ne... |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and mu... | #GW-BASIC | GW-BASIC | 10 PRINT "Police Sanitation Fire"
20 PRINT "------|----------|----"
30 FOR P = 2 TO 7 STEP 2
40 FOR S = 1 TO 7
50 IF S = P THEN GOTO 100
60 FOR F = 1 TO 7
70 IF S = F OR F = P THEN GOTO 90
80 IF P+S+F = 12 THEN PRINT USING " # # #";P;F;S
90 NEXT F
100 NEXT S
110 NEXT P |
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)... | #Wren | Wren | import "/dynamic" for Tuple, Struct
var Point = Tuple.create("Point", ["x", "y"])
var Triangle = Struct.create("Triangle", ["p1", "p2", "p3"])
var det2D = Fn.new { |t|
return t.p1.x * (t.p2.y - t.p3.y) +
t.p2.x * (t.p3.y - t.p1.y) +
t.p3.x * (t.p1.y - t.p2.y)
}
var checkTriWinding = Fn... |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Mercury | Mercury | :- module delete_file.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
main(!IO) :-
io.remove_file("input.txt", _, !IO),
io.remove_file("/input.txt", _, !IO),
io.remove_file("docs", _, !IO),
io.remove_file("/docs", _, !IO). |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Nanoquery | Nanoquery | f = new(Nanoquery.IO.File)
f.delete("input.txt")
f.delete("docs")
f.delete("/input.txt")
f.delete("/docs") |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
... | #Wren | Wren | import "/matrix" for Matrix
import "/fmt" for Fmt
var arrays = [
[ [1, 2],
[3, 4] ],
[ [-2, 2, -3],
[-1, 1, 3],
[ 2, 0, -1] ],
[ [ 1, 2, 3, 4],
[ 4, 5, 6, 7],
[ 7, 8, 9, 10],
[10, 11, 12, 13] ],
[ [ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
... |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Octave | Octave | d = 5/0;
if ( isinf(d) )
if ( index(lastwarn(), "division by zero") > 0 )
error("division by zero")
endif
endif |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Oforth | Oforth | : divideCheck(n)
| e |
try: e [ 128 n / ] when: [ "Zero detected..." . ]
"Leaving" println ; |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Ol | Ol |
(define (safediv a b)
(if (eq? (type b) type-complex)
(/ a b) ; complex can't be 0
(let ((z (/ 1 (inexact b))))
(unless (or (equal? z +inf.0) (equal? z -inf.0))
(/ a b)))))
; testing:
(for-each (lambda (x)
(if x (print x) (print "division by zero detected")))
(list
... |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #Liberty_BASIC | Liberty BASIC |
DATA "PI", "0123", "-0123", "12.30", "-12.30", "123!", "0"
DATA "0.0", ".123", "-.123", "12E3", "12E-3", "12+3", "end"
while n$ <> "end"
read n$
print n$, IsNumber(n$)
wend
end
function IsNumber(string$)
on error goto [NotNumber]
string$ = trim$(string$)
'check for float overflow
n = val... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Main()
Dim input() = {"", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ"}
For Each s In input
Console.WriteLine($"'{s}' (Length {s.Length}) " + String.Join(", ", s.Select(Function(c, i) (c, i)).GroupBy(Function(t) t.c).Where(Function(g) g.Count() > ... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #Vlang | Vlang | fn analyze(s string) {
chars := s.runes()
le := chars.len
println("Analyzing $s which has a length of $le:")
if le > 1 {
for i in 1..le{
if chars[i] != chars[i-1] {
println(" Not all characters in the string are the same.")
println(" '${chars[i]}' (0... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #Wren | Wren | import "/fmt" for Conv, Fmt
var analyze = Fn.new { |s|
var chars = s.codePoints.toList
var le = chars.count
System.print("Analyzing %(Fmt.q(s)) which has a length of %(le):")
if (le > 1) {
for (i in 1...le) {
if (chars[i] != chars[i-1]) {
System.print(" Not all cha... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #zkl | zkl | fcn discordianDate(y,m,d){
var [const]
seasons=T("Chaos","Discord","Confusion","Bureaucracy","The Aftermath"),
weekday=T("Sweetmorn","Boomtime","Pungenday","Prickle-Prickle","Setting Orange"),
apostle=T("Mungday","Mojoday","Syaday","Zaraday","Maladay"),
holiday=T("Chaoflux","Discoflux","Confuflux","Buref... |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displ... | #Ring | Ring |
c = 0
see "Digital root of 627615 is " + digitRoot(627615, 10) + " persistance is " + c + nl
see "Digital root of 39390 is " + digitRoot(39390, 10) + " persistance is " + c + nl
see "Digital root of 588225 is " + digitRoot(588225, 10) + " persistance is " + c + nl
see "Digital root of 9992 is " + digitRoot(9992,... |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displ... | #Ruby | Ruby | class String
def digroot_persistence(base=10)
num = self.to_i(base)
persistence = 0
until num < base do
num = num.digits(base).sum
persistence += 1
end
[num.to_s(base), persistence]
end
end
puts "--- Examples in 10-Base ---"
%w(627615 39390 588225 393900588225).each do |str|
puts... |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #OCaml | OCaml | let dot = List.fold_left2 (fun z x y -> z +. x *. y) 0.
(*
# dot [1.0; 3.0; -5.0] [4.0; -2.0; -1.0];;
- : float = 3.
*) |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and mu... | #Haskell | Haskell | main :: IO ()
main =
mapM_ print $
[2, 4, 6] >>=
\x ->
[1 .. 7] >>=
\y ->
[12 - (x + y)] >>=
\z ->
case y /= z && 1 <= z && z <= 7 of
True -> [(x, y, z)]
_ -> [] |
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)... | #zkl | zkl | // A triangle is three pairs of points: ( (x,y), (x,y), (x,y) )
fcn det2D(triangle){
p1,p2,p3 := triangle;
p1[0]*(p2[1] - p3[1]) + p2[0]*(p3[1] - p1[1]) + p3[0]*(p1[1] - p2[1]);
}
fcn checkTriWinding(triangle,allowReversed){ //-->triangle, maybe new
detTri:=det2D(triangle);
if(detTri<0.0){
if(allowR... |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Nemerle | Nemerle | using System;
using System.IO;
using System.Console;
module DeleteFile
{
Main() : void
{
when (File.Exists("input.txt")) File.Delete("input.txt");
try {
when (File.Exists(@"\input.txt")) File.Delete(@"\input.txt");
}
catch {
|e is UnauthorizedAccessExcep... |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
runSample(arg)
return
-- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
method isFileDeleted(fn) public static returns boolean
ff = File(fn)
fDeleted = ff.delete()
return fDeleted
-- ~~~~~~~~~~~~~~~~~~~... |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
... | #zkl | zkl | var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
fcn perm(A){ // should verify A is square
numRows:=A.rows;
Utils.Helpers.permute(numRows.toList()).reduce( // permute(0,1,..numRows)
'wrap(s,pm){ s + numRows.reduce('wrap(x,i){ x*A[i,pm[i]] },1.0) },
0.0)
}
test:=fcn(A){
println... |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #ooRexx | ooRexx | /* REXX **************************************************************
* program demonstrates detects and handles division by zero.
* translated from REXX:
* removed fancy error reporting (ooRexx does not support linesize)
* removed label Novalue (as novalue is not enabled there)
* 28.04.2013 Walter Pachl
*******... |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Oz | Oz | try
{Show 42 div 0}
catch error(kernel(div0 ...) ...) then
{System.showInfo "Division by zero detected."}
end |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #Lisaac | Lisaac |
"123457".is_integer.println;
// write TRUE on stdin
|
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #Logo | Logo | show number? "-1.23 ; true |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #Vlang | Vlang | fn analyze(s string) {
chars := s.runes()
le := chars.len
println("Analyzing $s which has a length of $le:")
if le > 1 {
for i := 0; i < le-1; i++ {
for j := i + 1; j < le; j++ {
if chars[j] == chars[i] {
println(" Not all characters in the string... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #Wren | Wren | import "/fmt" for Conv, Fmt
var analyze = Fn.new { |s|
var chars = s.codePoints.toList
var le = chars.count
System.print("Analyzing %(Fmt.q(s)) which has a length of %(le):")
if (le > 1) {
for (i in 0...le-1) {
for (j in i+1...le) {
if (chars[j] == chars[i]) {
... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #XPL0 | XPL0 | include xpllib; \contains StrLen function
proc StrSame(S); \Show if string has same characters
char S;
int L, I, J, K;
[L:= StrLen(S);
IntOut(0, L); Text(0, ": ^""); Text(0, S); ChOut(0, ^"); CrLf(0);
for I:= 0 to L-1 do
for J:= I+1 to L-1 do
[if S(I) # S(J)... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #zkl | zkl | fcn stringSameness(str){ // Does not handle Unicode
sz,unique,uz := str.len(), str.unique(), unique.len();
println("Length %d: \"%s\"".fmt(sz,str));
if(sz==uz or uz==1) println("\tSame character in all positions");
else
println("\tDifferent: ",
unique[1,*].pump(List,
'wrap(c){ "'%s' (0x%x... |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displ... | #Run_BASIC | Run BASIC | print "Digital root of 627615 is "; digitRoot$(627615, 10)
print "Digital root of 39390 is "; digitRoot$(39390, 10)
print "Digital root of 588225 is "; digitRoot$(588225, 10)
print "Digital root of 393900588225 is "; digitRoot$(393900588225, 10)
print "Digital root of 9992 is "; digitRoot$... |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displ... | #Rust | Rust | fn sum_digits(mut n: u64, base: u64) -> u64 {
let mut sum = 0u64;
while n > 0 {
sum = sum + (n % base);
n = n / base;
}
sum
}
// Returns tuple of (additive-persistence, digital-root)
fn digital_root(mut num: u64, base: u64) -> (u64, u64) {
let mut pers = 0;
while num >= base {
... |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #Octave | Octave | a = [1, 3, -5]
b = [4, -2, -1] % or [4; -2; -1] and avoid transposition with '
disp( a * b' ) % ' means transpose |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #Oforth | Oforth | : dotProduct zipWith(#*) sum ; |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and mu... | #J | J | require 'stats'
permfrom=: ,/@(perm@[ {"_ 1 comb) NB. get permutations of length x from y possible items
alluniq=: # = #@~. NB. check items are unique
addto12=: 12 = +/ NB. check items add to 12
iseven=: -.@(2&|) NB. check items are even
policeeven=: {.@iseven NB. check first it... |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #NewLISP | NewLISP | (delete-file "input.txt")
(delete-file "/input.txt")
(remove-dir "docs")
(remove-dir "/docs") |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Nim | Nim | import os
removeFile("input.txt")
removeFile("/input.txt")
removeDir("docs")
removeDir("/docs") |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #PARI.2FGP | PARI/GP | iferr(1/0,
err,
print("division by 0"); print("or other non-invertible divisor"),
errname(err) == "e_INV"); |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #Pascal | Pascal | sub div_check
{local $@;
eval {$_[0] / $_[1]};
$@ and $@ =~ /division by zero/;} |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #Lua | Lua | if tonumber(a) ~= nil then
--it's a number
end;
|
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #M2000_Interpreter | M2000 Interpreter |
\\ version 2
Module Checkit {
function global isNumber(a$, de$=".") {
=false=true ' return boolean
if de$="" then de$=str$(.1,".") ' get current decimal point character
a$=trim$(ucase$(a$))
m=len(a$)
if m=0 then exit
c$=filter$(a$,"012345... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #XPL0 | XPL0 | include xpllib; \contains StrLen function
proc StrUnique(S); \Show if string has unique chars
char S;
int L, I, J, K;
[L:= StrLen(S);
IntOut(0, L); Text(0, ": ^""); Text(0, S); ChOut(0, ^"); CrLf(0);
for I:= 0 to L-1 do
for J:= I+1 to L-1 do
[if S(I) = S(J) th... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #Yabasic | Yabasic | sub caracteresunicos (cad$)
local lngt
lngt = len(cad$)
print "cadena = \"", cad$, "\", longitud = ", lngt
for i = 1 to lngt
for j = i + 1 to lngt
if mid$(cad$,i,1) = mid$(cad$,j,1) then
print " Primer duplicado en las posiciones ", i, " y ", j, ", caracter = \'", mid$(... |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displ... | #Scala | Scala | def digitalRoot(x:BigInt, base:Int=10):(Int,Int) = {
def sumDigits(x:BigInt):Int=x.toString(base) map (_.asDigit) sum
def loop(s:Int, c:Int):(Int,Int)=if (s < 10) (s, c) else loop(sumDigits(s), c+1)
loop(sumDigits(x), 1)
}
Seq[BigInt](627615, 39390, 588225, BigInt("393900588225")) foreach {x =>
var (s, c)=dig... |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #Ol | Ol |
(define (dot-product a b)
(apply + (map * a b)))
(print (dot-product '(1 3 -5) '(4 -2 -1)))
; ==> 3
|
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #Oz | Oz | declare
fun {DotProduct Xs Ys}
{Length Xs} = {Length Ys} %% assert
{List.foldL {List.zip Xs Ys Number.'*'} Number.'+' 0}
end
in
{Show {DotProduct [1 3 ~5] [4 ~2 ~1]}} |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and mu... | #Java | Java | public class DepartmentNumbers {
public static void main(String[] args) {
System.out.println("Police Sanitation Fire");
System.out.println("------ ---------- ----");
int count = 0;
for (int i = 2; i <= 6; i += 2) {
for (int j = 1; j <= 7; ++j) {
if (j ... |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #Objeck | Objeck |
use IO;
bundle Default {
class FileExample {
function : Main(args : String[]) ~ Nil {
File->Delete("output.txt");
File->Delete("/output.txt");
Directory->Delete("docs");
Directory->Delete("/docs");
}
}
}
|
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.