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/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.
| #Objective-C | Objective-C | NSFileManager *fm = [NSFileManager defaultManager];
// Pre-OS X 10.5
[fm removeFileAtPath:@"input.txt" handler:nil];
[fm removeFileAtPath:@"/input.txt" handler:nil];
[fm removeFileAtPath:@"docs" handler:nil];
[fm removeFileAtPath:@"/docs" handler:nil];
// OS X 10.5+
[fm removeItemAtPath:@"input.txt" error:NULL];
[f... |
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.
| #Perl | Perl | sub div_check
{local $@;
eval {$_[0] / $_[1]};
$@ and $@ =~ /division by zero/;} |
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.
| #Phix | Phix | try
integer i = 1/0
catch e
?e[E_USER]
end try
puts(1,"still running...\n")
|
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... | #Maple | Maple | isNumeric := proc(s)
try
if type(parse(s), numeric) then
printf("The string is numeric."):
else
printf("The string is not numeric."):
end if:
catch:
printf("The string is not numeric."):
end try:
end proc: |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | NumberQ[ToExpression["02553352000242"]] |
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 ... | #zkl | zkl | fcn stringUniqueness(str){ // Does not handle Unicode
sz,unique,uz,counts := str.len(), str.unique(), unique.len(), str.counts();
println("Length %d: \"%s\"".fmt(sz,str));
if(sz==uz or uz==1) println("\tAll characters are unique");
else // counts is (char,count, char,count, ...)
println("\tDuplicate... |
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... | #Scheme | Scheme | ; Convert an integer into a list of its digits.
(define integer->list
(lambda (integer)
(let loop ((list '()) (int integer))
(if (< int 10)
(cons int list)
(loop (cons (remainder int 10) list) (quotient int 10))))))
; Return the sum of the digits of an integer.
(define integer-sum-digi... |
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 ... | #PARI.2FGP | PARI/GP | dot(u,v)={
sum(i=1,#u,u[i]*v[i])
}; |
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... | #JavaScript | JavaScript | (function () {
'use strict';
// concatMap :: (a -> [b]) -> [a] -> [b]
function concatMap(f, xs) {
return [].concat.apply([], xs.map(f));
};
return '(Police, Sanitation, Fire)\n' +
concatMap(function (x) {
return concatMap(function (y) {
return concatMa... |
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.
| #OCaml | OCaml | Sys.remove "input.txt";;
Sys.remove "/input.txt";; |
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.
| #ooRexx | ooRexx | /*REXX pgm deletes a file */
file= 'afile.txt' /*name of a file to be deleted.*/
res=sysFileDelete(file); Say file 'res='res
File= 'bfile.txt' /*name of a file to be deleted.*/
res=sysFileDelete(file); Say file 'res='res |
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.
| #PHP | PHP | function div_check($x, $y) {
@trigger_error(''); // a dummy to detect when error didn't occur
@($x / $y);
$e = error_get_last();
return $e['message'] != '';
} |
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.
| #PicoLisp | PicoLisp | (catch '("Div/0") (/ A B)) |
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.
| #PL.2FI | PL/I | Proc DivideDZ(a,b) Returns(Float Bin(33));
Dcl (a,b,c) Float Bin(33);
On ZeroDivide GoTo MyError;
c=a/b;
Return(c);
MyError:
Put Skip List('Divide by Zero Detected!');
End DivideDZ;
xx=DivideDZ(1,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... | #MATLAB | MATLAB |
function r = isnum(a)
r = ~isnan(str2double(a))
end
% tests
disp(isnum(123)) % 1
disp(isnum("123")) % 1
disp(isnum("foo123")) % 0
disp(isnum("123bar")) % 0
disp(isnum("3.1415")) % 1
|
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... | #Maxima | Maxima | numberp(parse_string("170141183460469231731687303715884105727")); |
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... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "bigint.s7i";
const func bigInteger: digitalRoot (in var bigInteger: num, in bigInteger: base, inout bigInteger: persistence) is func
result
var bigInteger: sum is 0_;
begin
persistence := 0_;
while num >= base do
sum := 0_;
while num > 0_ do
su... |
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... | #Sidef | Sidef | func digroot (r, base = 10) {
var root = r.base(base)
var persistence = 0
while (root.len > 1) {
root = root.chars.map{|n| Number(n, 36) }.sum(0).base(base)
++persistence
}
return(persistence, root)
}
var nums = [5, 627615, 39390, 588225, 393900588225]
var bases = [2, 3, 8, 10, 16,... |
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 ... | #Pascal | Pascal | sub dotprod
{
my($vec_a, $vec_b) = @_;
die "they must have the same size\n" unless @$vec_a == @$vec_b;
my $sum = 0;
$sum += $vec_a->[$_] * $vec_b->[$_] for 0..$#$vec_a;
return $sum;
}
my @vec_a = (1,3,-5);
my @vec_b = (4,-2,-1);
print dotprod(\@vec_a,\@vec_b), "\n"; # 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... | #jq | jq | {"fire":1,"police":4,"sanitation":7}
|
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... | #Julia | Julia | using Printf
function findsolution(rng=1:7)
rst = Matrix{Int}(0, 3)
for p in rng, f in rng, s in rng
if p != s != f != p && p + s + f == 12 && iseven(p)
rst = [rst; p s f]
end
end
return rst
end
function printsolutions(sol::Matrix{Int})
println(" Pol. Fire Sa... |
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.
| #Oz | Oz | for Dir in ["/" "./"] do
try {OS.unlink Dir#"output.txt"}
catch _ then {System.showInfo "File does not exist."} end
try {OS.rmDir Dir#"docs"}
catch _ then {System.showInfo "Directory does not exist."} end
end |
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.
| #PARI.2FGP | PARI/GP | system("rm -rf docs");
system("rm input.txt");
system("rm -rf /docs");
system("rm /input.txt"); |
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.
| #PL.2FSQL | PL/SQL | FUNCTION divide(n1 IN NUMBER, n2 IN NUMBER)
RETURN BOOLEAN
IS
result NUMBER;
BEGIN
result := n1/n2;
RETURN(FALSE);
EXCEPTION
WHEN ZERO_DIVIDE THEN
RETURN(TRUE);
END divide; |
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.
| #PowerShell | PowerShell |
function div ($a, $b) {
try{$a/$b}
catch{"Bad parameters: `$a = $a and `$b = $b"}
}
div 10 2
div 1 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... | #MAXScript | MAXScript | fn isNumeric str =
(
try
(
(str as integer) != undefined
)
catch(false)
)
isNumeric "123" |
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... | #min | min | (
dup (((int integer?) (pop false)) try) dip
((float float?) (pop false)) try or
) :numeric? |
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... | #Smalltalk | Smalltalk | digitalRoot :=
[:nr :arIn |
r := (nr printString asArray collect:#digitValue) sum.
r > 9 ifTrue:[
digitalRoot value:r value:arIn+1.
] ifFalse:[
{ arIn+1 . r }
].
].
#(
627615 39390 588225 393900588225 10 199
199999999999999999999999999999999999999999999999999999999999999999999... |
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... | #SmileBASIC | SmileBASIC | DEF DIGITAL_ROOT N OUT DR,AP
AP=0
DR=N
WHILE DR>9
INC AP
STRDR$=STR$(DR)
NEWDR=0
FOR I=0 TO LEN(STRDR$)-1
INC NEWDR,VAL(MID$(STRDR$,I,1))
NEXT
DR=NEWDR
WEND
END |
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 ... | #Perl | Perl | sub dotprod
{
my($vec_a, $vec_b) = @_;
die "they must have the same size\n" unless @$vec_a == @$vec_b;
my $sum = 0;
$sum += $vec_a->[$_] * $vec_b->[$_] for 0..$#$vec_a;
return $sum;
}
my @vec_a = (1,3,-5);
my @vec_b = (4,-2,-1);
print dotprod(\@vec_a,\@vec_b), "\n"; # 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... | #Kotlin | Kotlin | // version 1.1.2
fun main(args: Array<String>) {
println("Police Sanitation Fire")
println("------ ---------- ----")
var count = 0
for (i in 2..6 step 2) {
for (j in 1..7) {
if (j == i) continue
for (k in 1..7) {
if (k == i || k == j) continue
... |
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.
| #Pascal | Pascal | use File::Spec::Functions qw(catfile rootdir);
# here
unlink 'input.txt';
rmdir 'docs';
# root dir
unlink catfile rootdir, 'input.txt';
rmdir catfile rootdir, '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.
| #Perl | Perl | use File::Spec::Functions qw(catfile rootdir);
# here
unlink 'input.txt';
rmdir 'docs';
# root dir
unlink catfile rootdir, 'input.txt';
rmdir catfile rootdir, '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.
| #Prolog | Prolog |
div(A, B, C, Ex) :-
catch((C is A/B), Ex, (C = infinity)).
|
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.
| #Pure | Pure | > 1/0, -1/0, 0/0;
inf,-inf,nan |
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... | #MiniScript | MiniScript | isNumeric = function(s)
return s == "0" or s == "-0" or val(s) != 0
end function
print isNumeric("0")
print isNumeric("42")
print isNumeric("-3.14157")
print isNumeric("5@*#!")
print isNumeric("spam") |
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... | #MIPS_Assembly | MIPS Assembly |
# $a0 char val
# $a1 address pointer
# $a2 PERIOD_HIT_FLAG
# $a3 HAS_DIGITS_FLAG
.data
### CHANGE THIS STRING TO TEST DIFFERENT ONES... ###
string: .asciiz "-.1236"
s_false: .asciiz "False"
s_true: .asciiz "True"
.text
main:
set_up: #test for 0th char == 45 or 46 or 48...57
la $a1,string
lb $a0,($a1)
... |
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... | #Tcl | Tcl | package require Tcl 8.5
proc digitalroot num {
for {set p 0} {[string length $num] > 1} {incr p} {
set num [::tcl::mathop::+ {*}[split $num ""]]
}
list $p $num
}
foreach n {627615 39390 588225 393900588225} {
lassign [digitalroot $n] p r
puts [format "$n has additive persistence $p and digital ro... |
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 ... | #Phix | Phix | ?sum(sq_mul({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... | #Lua | Lua |
print( "Fire", "Police", "Sanitation" )
sol = 0
for f = 1, 7 do
for p = 1, 7 do
for s = 1, 7 do
if s + p + f == 12 and p % 2 == 0 and f ~= p and f ~= s and p ~= s then
print( f, p, s ); sol = sol + 1
end
end
end
end
print( string.format( "\n%d solutions ... |
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.
| #Phix | Phix | without js -- (file i/o)
constant root = iff(platform()=LINUX?"/":"C:\\")
?delete_file("input.txt")
?delete_file(root&"input.txt")
?remove_directory("docs")
?remove_directory(root&"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.
| #PHP | PHP | <?php
unlink('input.txt');
unlink('/input.txt');
rmdir('docs');
rmdir('/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.
| #Python | Python | def div_check(x, y):
try:
x / y
except ZeroDivisionError:
return True
else:
return False |
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.
| #Q | Q | r:x%0
?[1=sum r=(0n;0w;-0w);"division by zero detected";()] |
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.
| #R | R | d <- 5/0
if ( !is.finite(d) ) {
# it is Inf, -Inf, or NaN
} |
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... | #Mirah | Mirah | import java.text.NumberFormat
import java.text.ParsePosition
import java.util.Scanner
# this first example relies on catching an exception,
# which is bad style and poorly performing in Java
def is_numeric?(s:string)
begin
Double.parseDouble(s)
return true
rescue
return false
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... | #mIRC_Scripting_Language | mIRC Scripting Language | var %value = 3
if (%value isnum) {
echo -s %value is numeric.
} |
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... | #TI-83_BASIC | TI-83 BASIC | :ClrHome
:1→X
:Input ">",Str1
:Str1→Str2
:Repeat L≤1
:Disp Str1
:length(Str1→L
:L→dim(L₁
:seq(expr(sub(Str1,A,1)),A,1,L)→L₁
:sum(L₁→N
:{0,.5,1→L₂
:NL₂→L₃
:Med-Med L₂,L₃,Y₁
:Equ►String(Y₁,Str1
:sub(Str1,1,length(Str1)-3→Str1
:X+1→X
:End
:Pause
:ClrHome
:Disp Str2,"DIGITAL ROOT",expr(Str1),"ADDITIVE","PERSISTENCE",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... | #TypeScript | TypeScript | // Digital root
function rootAndPers(n: number, bas: number): [number, number] {
var pers = 0;
while (n >= bas)
{
var s = 0;
do
{
s += n % bas;
n = Math.floor(n / bas);
} while (n > 0);
pers++;
n = s;
}
return [n, pers];
}
function intToString(n: number, wdth: number): ... |
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 ... | #Phixmonti | Phixmonti | def sq_mul
0 tolist var c
len for
var i
i get rot i get rot * c swap 0 put var c
endfor
c
enddef
def sq_sum
0 swap
len for
get rot + swap
endfor
swap
enddef
1 3 -5 3 tolist
4 -2 -1 3 tolist
sq_mul
sq_sum
pstack |
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 ... | #PHP | PHP | <?php
function dot_product($v1, $v2) {
if (count($v1) != count($v2))
throw new Exception('Arrays have different lengths');
return array_sum(array_map('bcmul', $v1, $v2));
}
echo dot_product(array(1, 3, -5), array(4, -2, -1)), "\n";
?> |
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... | #MAD | MAD | NORMAL MODE IS INTEGER
PRINT COMMENT $ POLICE SANITATION FIRE$
THROUGH LOOP, FOR P=2, 2, P.G.7
THROUGH LOOP, FOR S=1, 1, S.G.7
THROUGH LOOP, FOR F=1, 1, F.G.7
WHENEVER P.E.S .OR. P.E.F .OR. S.E.F, TRANSFER TO LOOP
WHENEVER P+S+F .E. 12, PRIN... |
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... | #Maple | Maple | #determines if i, j, k are exclusive numbers
exclusive_numbers := proc(i, j, k)
if (i = j) or (i = k) or (j = k) then
return false;
end if;
return true;
end proc;
#outputs all possible combinations of numbers that statisfy given conditions
department_numbers := proc()
local i, j, k;
printf("Police Sanitation ... |
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.
| #Picat | Picat |
import os.
del(Arg), directory(Arg) =>
rmdir(Arg).
del(Arg), file(Arg) =>
rm(Arg).
main(Args) =>
foreach (Arg in Args)
del(Arg)
end.
|
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.
| #PicoLisp | PicoLisp | (call 'rm "input.txt")
(call 'rmdir "docs")
(call 'rm "/input.txt")
(call 'rmdir "/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.
| #Pike | Pike | int main(){
rm("input.txt");
rm("/input.txt");
rm("docs");
rm("/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.
| #Racket | Racket |
#lang racket
(with-handlers ([exn:fail:contract:divide-by-zero?
(λ (e) (displayln "Divided by zero"))])
(/ 1 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.
| #Raku | Raku | sub div($a, $b) {
my $r;
try {
$r = $a / $b;
CATCH {
default { note "Unexpected exception, $_" }
}
}
return $r // Nil;
}
say div(10,2);
say div(1, sin(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.
| #REBOL | REBOL | rebol [
Title: "Detect Divide by Zero"
URL: http://rosettacode.org/wiki/Divide_by_Zero_Detection
]
; The 'try' word returns an error object if the operation fails for
; whatever reason. The 'error?' word detects an error object and
; 'disarm' keeps it from triggering so I can analyze it to print the
; appropr... |
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... | #Modula-3 | Modula-3 | MODULE Numeric EXPORTS Main;
IMPORT IO, Fmt, Text;
PROCEDURE isNumeric(s: TEXT): BOOLEAN =
BEGIN
FOR i := 0 TO Text.Length(s) DO
WITH char = Text.GetChar(s, i) DO
IF i = 0 AND char = '-' THEN
EXIT;
END;
IF char >= '0' AND char <= '9' THEN
EXIT;
END;
... |
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... | #uBasic.2F4tH | uBasic/4tH | PRINT "Digital root of 627615 is "; FUNC(_FNdigitalroot(627615, 10)) ;
PRINT " (additive persistence " ; Pop(); ")"
PRINT "Digital root of 39390 is "; FUNC(_FNdigitalroot(39390, 10)) ;
PRINT " (additive persistence " ; Pop(); ")"
PRINT "Digital root of 588225 is "; FUNC(_FNdigitalroot(588225, 10)) ;
PRINT " (additi... |
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... | #UNIX_Shell | UNIX Shell | #!/usr/bin/env bash
numbers=(627615 39390 588225 393900588225 55)
declare root
for number in "${numbers[@]}"; do
declare -i iterations
root="${number}"
while [[ "${#root}" -ne 1 ]]; do
root="$(( $(fold -w1 <<<"${root}" | xargs | sed 's/ /+/g') ))"
iterations+=1
done
echo -e "${nu... |
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 ... | #Picat | Picat | go =>
L1 = [1, 3, -5],
L2 = [4, -2, -1],
println(dot_product=dot_product(L1,L2)),
catch(println(dot_product([1,2,3,4],[1,2,3])),E, println(E)),
nl.
dot_product(L1,L2) = _, L1.length != L2.length =>
throw($dot_product_not_same_length(L1,L2)).
dot_product(L1,L2) = sum([L1[I]*L2[I] : I in 1..L1.length]).... |
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 ... | #PicoLisp | PicoLisp | (de dotProduct (A B)
(sum * A B) )
(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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Select[Permutations[Range[7], {3}], Total[#] == 12 && EvenQ[First[#]] &] |
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... | #Modula-2 | Modula-2 | MODULE DepartmentNumbers;
FROM Conversions IMPORT IntToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE WriteInt(num : INTEGER);
VAR str : ARRAY[0..16] OF CHAR;
BEGIN
IntToStr(num,str);
WriteString(str);
END WriteInt;
VAR i,j,k,count : INTEGER;
BEGIN
count:=0;
WriteString("Police ... |
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.
| #PowerShell | PowerShell | # possible aliases for Remove-Item: rm, del, ri
Remove-Item input.txt
Remove-Item \input.txt # file system root
Remove-Item -Recurse docs # recurse for deleting folders including content
Remove-Item -Recurse \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.
| #ProDOS | ProDOS | deletedirectory 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.
| #REXX | REXX | /*REXX program demonstrates detection and handling division by zero. */
signal on syntax /*handle all REXX syntax errors. */
x = sourceline() /*being cute, x=is the size of this pgm*/
y = x - x ... |
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.
| #Ring | Ring |
Try
see 9/0
Catch
see "Catch!" + nl + cCatchError
Done
|
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... | #MUMPS | MUMPS | USER>WRITE +"1"
1
USER>WRITE +"1A"
1
USER>WRITE +"A1"
0
USER>WRITE +"1E"
1
USER>WRITE +"1E2"
100
USER>WRITE +"1EA24"
1
USER>WRITE +"1E3A"
1000
USER>WRITE +"1E-3"
.001
|
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... | #Nanoquery | Nanoquery | def isNum(str)
try
double(str)
return true
catch
return false
end
end |
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... | #VBA | VBA | Option Base 1
Private Sub digital_root(n As Variant)
Dim s As String, t() As Integer
s = CStr(n)
ReDim t(Len(s))
For i = 1 To Len(s)
t(i) = Mid(s, i, 1)
Next i
Do
dr = WorksheetFunction.Sum(t)
s = CStr(dr)
ReDim t(Len(s))
For i = 1 To Len(s)
t(... |
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... | #VBScript | VBScript | Function digital_root(n)
ap = 0
Do Until Len(n) = 1
x = 0
For i = 1 To Len(n)
x = x + CInt(Mid(n,i,1))
Next
n = x
ap = ap + 1
Loop
digital_root = "Additive Persistence = " & ap & vbCrLf &_
"Digital Root = " & n & vbCrLf
End Function
WScript.StdOut.Write digital_root(WScript.Arguments(0)) |
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 ... | #PL.2FI | PL/I | get (n);
begin;
declare (A(n), B(n)) float;
declare dot_product float;
get list (A);
get list (B);
dot_product = sum(a*b);
put (dot_product);
end; |
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 ... | #Plain_English | Plain English | To run:
Start up.
Make an example vector and another example vector.
Compute a dot product of the example vector and the other example vector.
Destroy the example vector. Destroy the other example vector.
Convert the dot product to a string.
Write the string on the console.
Wait for the escape key.
Shut down.
An elem... |
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... | #Mercury | Mercury | :- module department_numbers.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is cc_multi.
:- implementation.
:- import_module int, list, solutions, string.
main(!IO) :-
io.print_line("P S F", !IO),
unsorted_aggregate(department_number, print_solution, !IO).
:- pred print_solution({int... |
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... | #Nim | Nim | type Solution = tuple[p, s, f: int]
iterator solutions(max, total: Positive): Solution =
for p in countup(2, max, 2):
for s in 1..max:
if s == p: continue
let f = total - p - s
if f notin [p, s] and f in 1..max:
yield (p, s, f)
echo "P S F"
for sol in solutions(7, 12):
echo sol.p, ... |
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.
| #PureBasic | PureBasic | DeleteFile("input.txt")
DeleteDirectory("docs","") ; needs to delete all included files
DeleteFile("/input.txt")
DeleteDirectory("/docs","*.*") ; deletes all files according to a pattern
DeleteDirectory("/docs","",#PB_FileSystem_Recursive) ; deletes all files and directories recursive |
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.
| #Python | Python | import os
# current directory
os.remove("output.txt")
os.rmdir("docs")
# root directory
os.remove("/output.txt")
os.rmdir("/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.
| #RPGIV | RPGIV |
dcl-c DIVIDE_BY_ZERO 00102;
dcl-s result zoned(5:2);
dcl-s value1 zoned(5:2);
dcl-s value2 zoned(5:2);
value1 = 10;
value2 = 0;
monitor;
eval(h) result = value1 / value2; // Using half rounding here for the eval result
on-error DIVIDE_BY_ZERO;
... |
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.
| #Ruby | Ruby | def div_check(x, y)
begin
x / y
rescue ZeroDivisionError
true
else
false
end
end |
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.
| #Rust | Rust | fn test_division(numerator: u32, denominator: u32) {
match numerator.checked_div(denominator) {
Some(result) => println!("{} / {} = {}", numerator, denominator, result),
None => println!("{} / {} results in a division by zero", numerator, denominator)
}
}
fn main() {
test_division(5, 4);
... |
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... | #Nemerle | Nemerle | using System;
using System.Console;
module IsNumeric
{
IsNumeric( input : string) : bool
{
mutable meh = 0.0; // I don't want it, not going to use it, why force me to declare it?
double.TryParse(input, out meh)
}
Main() : void
{
def num = "-1.2345E6";
def not = "... |
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... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
numeric digits 20
loop n_ over getTestData()
-- could have used n_.datatype('N') directly here...
if isNumeric(n_) then msg = 'numeric'
else msg = 'not numeric'
say ('"'n_'"').right(25)':' msg
end n_
return
-... |
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... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Function DigitalRoot(num As Long) As Tuple(Of Integer, Integer)
Dim additivepersistence = 0
While num > 9
num = num.ToString().ToCharArray().Sum(Function(x) Integer.Parse(x))
additivepersistence = additivepersistence + 1
End While
Return Tuple... |
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 ... | #PostScript | PostScript | /dotproduct{
/x exch def
/y exch def
/sum 0 def
/i 0 def
x length y length eq %Check if both arrays have the same length
{
x length{
/sum x i get y i get mul sum add def
/i i 1 add def
}repeat
sum ==
}
{
-1 ==
}ifelse
}def |
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 ... | #PowerShell | PowerShell |
function dotproduct( $a, $b) {
$a | foreach -Begin {$i = $res = 0} -Process { $res += $_*$b[$i++] } -End{$res}
}
dotproduct (1..2) (1..2)
dotproduct (1..10) (11..20)
|
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... | #Objeck | Objeck | class Program {
function : Main(args : String[]) ~ Nil {
sol := 1;
"\t\tFIRE\tPOLICE\tSANITATION"->PrintLine();
for( f := 1; f < 8; f+=1; ) {
for( p := 1; p < 8; p+=1; ) {
for( s:= 1; s < 8; s+=1; ) {
if( f <> p & f <> s & p <> s & ( p and 1 ) = 0 & ( f + s + p = 12 ) ) {
... |
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.
| #R | R | file.remove("input.txt")
file.remove("/input.txt")
# or
file.remove("input.txt", "/input.txt")
# or
unlink("input.txt"); unlink("/input.txt")
# directories needs the recursive flag
unlink("docs", recursive = TRUE)
unlink("/docs", recursive = TRUE) |
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.
| #Racket | Racket |
#lang racket
;; here
(delete-file "input.txt")
(delete-directory "docs")
(delete-directory/files "docs") ; recursive deletion
;; in the root
(delete-file "/input.txt")
(delete-directory "/docs")
(delete-directory/files "/docs")
;; or in the root with relative paths
(parameterize ([current-directory "/"])
(del... |
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.
| #Raku | Raku | unlink 'input.txt';
unlink '/input.txt';
rmdir 'docs';
rmdir '/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.
| #Scala | Scala | object DivideByZero extends Application {
def check(x: Int, y: Int): Boolean = {
try {
val result = x / y
println(result)
return false
} catch {
case x: ArithmeticException => {
return true
}
}
}
println("divided by zero = " + check(1, 0))
def check1(x: 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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
const proc: doDivide (in integer: numer, in integer: denom) is func
begin
block
writeln(numer <& " div " <& denom <& " = " <& numer div denom);
exception
catch NUMERIC_ERROR:
writeln("Division by zero detected.");
end block;
end func... |
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... | #Nim | Nim | import strutils
proc isNumeric(s: string): bool =
try:
discard s.parseFloat()
result = true
except ValueError:
result = false
const Strings = ["1", "3.14", "-100", "1e2", "Inf", "rose"]
for s in Strings:
echo s, " is ", if s.isNumeric(): "" else: "not ", "numeric" |
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... | #Objeck | Objeck |
class Numeric {
function : Main(args : String[]) ~ Nil {
if(args->Size() = 1) {
IsNumeric(args[0])->PrintLine();
};
}
function : IsNumeric(str : String) ~ Bool {
return str->IsFloat();
}
} |
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... | #Vlang | Vlang | import strconv
fn sum(ii u64, base int) int {
mut s := 0
mut i := ii
b64 := u64(base)
for ; i > 0; i /= b64 {
s += int(i % b64)
}
return s
}
fn digital_root(n u64, base int) (int, int) {
mut persistence := 0
mut root := int(n)
for x := n; x >= u64(base); x = u64(root) {
root = sum(x, base)
persistenc... |
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... | #Wortel | Wortel | @let {
sumDigits ^(@sum @arr)
drootl &\@rangef [. sumDigits ^(\~>1 #@arr)]
droot ^(@last drootl)
apers ^(#-drootl)
[
!console.log "[number]: [digital root] [additive persistence] [intermediate sums]"
~@each [627615 39390 588225 393900588225]
&n !console.log "{n}: {!droot n} {!aper... |
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 ... | #Prolog | Prolog | dot_product(L1, L2, N) :-
maplist(mult, L1, L2, P),
sumlist(P, N).
mult(A,B,C) :-
C is A*B. |
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 ... | #PureBasic | PureBasic | Procedure dotProduct(Array a(1),Array b(1))
Protected i, sum, length = ArraySize(a())
If ArraySize(a()) = ArraySize(b())
For i = 0 To length
sum + a(i) * b(i)
Next
EndIf
ProcedureReturn sum
EndProcedure
If OpenConsole()
Dim a(2)
Dim b(2)
a(0) = 1 : a(1) = 3 : a(2) = -5
b(0) = 4 : b... |
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.