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/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Haskell | Haskell | import Data.Char (digitToInt)
import Text.Printf (printf)
damm :: String -> Bool
damm = (==0) . foldl (\r -> (table !! r !!) . digitToInt) 0
where
table =
[ [0, 3, 1, 7, 5, 9, 8, 6, 4, 2]
, [7, 0, 9, 2, 1, 5, 4, 8, 6, 3]
, [4, 2, 0, 6, 8, 7, 1, 3, 5, 9]
, [1, 7, 5, 0, 9, 8, 3, 4, 2, 6]
, [6, 1, 2, 3, 0, 4, 5, 9, 7, 8]
, [3, 6, 7, 4, 2, 0, 9, 5, 8, 1]
, [5, 8, 6, 9, 7, 2, 0, 1, 3, 4]
, [8, 9, 4, 5, 3, 6, 2, 0, 1, 7]
, [9, 4, 3, 8, 6, 1, 7, 2, 0, 5]
, [2, 5, 8, 1, 4, 3, 6, 7, 9, 0] ]
main :: IO ()
main = mapM_ (uncurry(printf "%6s is valid: %s\n") . ((,) <*> show . damm) . show)
[5724, 5727, 112946, 112949] |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
static class Program
{
static List<long> primes = new List<long>() { 3, 5 };
static void Main(string[] args)
{
const int cutOff = 200;
const int bigUn = 100000;
const int chunks = 50;
const int little = bigUn / chunks;
const string tn = " cuban prime";
Console.WriteLine("The first {0:n0}{1}s:", cutOff, tn);
int c = 0;
bool showEach = true;
long u = 0, v = 1;
DateTime st = DateTime.Now;
for (long i = 1; i <= long.MaxValue; i++)
{
bool found = false;
int mx = System.Convert.ToInt32(Math.Ceiling(Math.Sqrt(v += (u += 6))));
foreach (long item in primes)
{
if (item > mx) break;
if (v % item == 0) { found = true; break; }
}
if (!found)
{
c += 1; if (showEach)
{
for (var z = primes.Last() + 2; z <= v - 2; z += 2)
{
bool fnd = false;
foreach (long item in primes)
{
if (item > mx) break;
if (z % item == 0) { fnd = true; break; }
}
if (!fnd) primes.Add(z);
}
primes.Add(v); Console.Write("{0,11:n0}", v);
if (c % 10 == 0) Console.WriteLine();
if (c == cutOff)
{
showEach = false;
Console.Write("\nProgress to the {0:n0}th{1}: ", bigUn, tn);
}
}
if (c % little == 0) { Console.Write("."); if (c == bigUn) break; }
}
}
Console.WriteLine("\nThe {1:n0}th{2} is {0,17:n0}", v, c, tn);
Console.WriteLine("Computation time was {0} seconds", (DateTime.Now - st).TotalSeconds);
if (System.Diagnostics.Debugger.IsAttached) Console.ReadKey();
}
} |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Groovy | Groovy | import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
class CreateFile {
static void main(String[] args) throws IOException {
String os = System.getProperty("os.name")
if (os.contains("Windows")) {
Path path = Paths.get("tape.file")
Files.write(path, Collections.singletonList("Hello World!"))
} else {
Path path = Paths.get("/dev/tape")
Files.write(path, Collections.singletonList("Hello World!"))
}
}
} |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Haskell | Haskell | module Main (main) where
main :: IO ()
main = writeFile "/dev/tape" "Hello from Rosetta Code!" |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
write(open("/dev/tape","w"),"Hi")
end |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #IS-BASIC | IS-BASIC | 100 OPEN #1:"Tape1:README.TXT" ACCESS OUTPUT
110 PRINT #1:"I am a tape file now, or hope to be soon."
120 CLOSE #1 |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Java | Java | import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
public class CreateFile {
public static void main(String[] args) throws IOException {
String os = System.getProperty("os.name");
if (os.contains("Windows")) {
Path path = Paths.get("tape.file");
Files.write(path, Collections.singletonList("Hello World!"));
} else {
Path path = Paths.get("/dev/tape");
Files.write(path, Collections.singletonList("Hello World!"));
}
}
} |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
| #JavaScript | JavaScript | const money = require('money-math')
let hamburgers = 4000000000000000
let hamburgerPrice = 5.50
let shakes = 2
let shakePrice = 2.86
let tax = 7.65
let hamburgerTotal = money.mul(hamburgers.toFixed(0), money.floatToAmount(hamburgerPrice))
let shakeTotal = money.mul(shakes.toFixed(0), money.floatToAmount(shakePrice))
let subTotal = money.add(hamburgerTotal, shakeTotal)
let taxTotal = money.percent(subTotal, tax)
let total = money.add(subTotal, taxTotal)
console.log('Hamburger Total:', hamburgerTotal)
console.log('Shake Total:', shakeTotal)
console.log('Sub Total:', subTotal)
console.log('Tax:', taxTotal)
console.log('Total:', total)
|
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
| #jq | jq | def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
# print as dollars and cents
def dollars:
(. % 100) as $c
| "$\((. - $c) /100).\($c)";
def dollars($width):
dollars | lpad($width);
def innerproduct($y):
. as $x
| reduce range(0;$x|length) as $i (0; . + ($x[$i]*$y[$i]));
def plus($y):
. as $x
| reduce range(0;$x|length) as $i ([]; .[$i] = ($x[$i]+$y[$i]));
# Round up or down
def integer_division($y):
(. % $y) as $remainder
| (. - $remainder) / $y
| if $remainder * 2 > $y then . + 1 else . end;
# For computing taxes
def precision: 10000;
def cents: integer_division(precision);
### The task:
def p: [550, 286];
def q: [4000000000000000, 2];
def taxrate: 765; # relative to `precision`
(p | innerproduct(q)) as $before_tax # cents
| ($before_tax * taxrate) as $taxes # relative to precision
| ((($before_tax * precision) + $taxes) | cents) as $after_tax # cents
| ($after_tax|tostring|length + 2) as $width
|
" Total before tax: \($before_tax | dollars($width))",
" - tax: \($taxes | cents | dollars($width))",
" Total after tax: \($after_tax | dollars($width))" |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
| #Io | Io | curry := method(fn,
a := call evalArgs slice(1)
block(
b := a clone appendSeq(call evalArgs)
performWithArgList("fn", b)
)
)
// example:
increment := curry( method(a,b,a+b), 1 )
increment call(5)
// result => 6 |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
| #J | J | threePlus=: 3&+
threePlus 7
10
halve =: %&2 NB. % means divide
halve 20
10
someParabola =: _2 3 1 &p. NB. x^2 + 3x - 2 |
http://rosettacode.org/wiki/Create_an_object_at_a_given_address | Create an object at a given address |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #Raku | Raku | use NativeCall;
use NativeCall::Types;
# bind to basic libc memory management
sub malloc(size_t) returns Pointer[uint8] is native {*};
sub memset(Pointer, uint32, size_t) is native {*};
sub free(Pointer[uint8]) is native {*};
my Pointer[uint8] $base-p = malloc(100);
memset($base-p, 0, 100);
# define object as a C struct that contains a short and an int
class SampleObject is repr('CStruct') {
has uint16 $.foo is rw;
has uint8 $.bar is rw;
}
# for arguments sake our object is at byte offset 64 in the
# allocated memory
my $offset-p = $base-p.clone.add(64);
my $object-p := nativecast(Pointer[SampleObject], $offset-p);
note "creating object at address {+$object-p}";
my $struct := $object-p.deref;
$struct.foo = 41;
$struct.bar = 99;
# check we can update
$struct.foo++; # 42
# Check that we're actually updating the memory
use Test;
# look at the bytes directly to verify we've written to memory. Don't be too exact, as
# the positions may vary on different platforms depending on endianess and field alignment.
my $rec-size = nativesizeof(SampleObject);
my uint8 @bytes-written = (0 ..^ $rec-size).map(-> $i {$base-p[64 + $i]}).grep: * > 0;
# first field 'foo' (amount is small enough to fit in one byte)
is @bytes-written[0], 42, 'object first field';
# second field 'bar'
is @bytes-written[1], 99, 'object second field';
# verify that changing the origin changes the object values
memset($base-p, 1, 100); # set every byte to 1
is $struct.foo, 256 + 1, 'short updated at origin';
is $struct.bar, 1, 'byte updated at origin';
# tidy up
free($base-p);
done-testing;
|
http://rosettacode.org/wiki/Cyclotomic_polynomial | Cyclotomic polynomial | The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n.
Task
Find and print the first 30 cyclotomic polynomials.
Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient.
See also
Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.
The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient. | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Text
Module Module1
Private ReadOnly MAX_ALL_FACTORS As Integer = 100_000
#Const ALGORITHM = 2
Class Term
Implements IComparable(Of Term)
Public ReadOnly Property Coefficient As Long
Public ReadOnly Property Exponent As Long
Public Sub New(c As Long, Optional e As Long = 0)
Coefficient = c
Exponent = e
End Sub
Public Shared Operator -(t As Term) As Term
Return New Term(-t.Coefficient, t.Exponent)
End Operator
Public Shared Operator +(lhs As Term, rhs As Term) As Term
If lhs.Exponent <> rhs.Exponent Then
Throw New ArgumentException("Exponents not equal")
End If
Return New Term(lhs.Coefficient + rhs.Coefficient, lhs.Exponent)
End Operator
Public Shared Operator *(lhs As Term, rhs As Term) As Term
Return New Term(lhs.Coefficient * rhs.Coefficient, lhs.Exponent + rhs.Exponent)
End Operator
Public Function CompareTo(other As Term) As Integer Implements IComparable(Of Term).CompareTo
Return -Exponent.CompareTo(other.Exponent)
End Function
Public Overrides Function ToString() As String
If Coefficient = 0 Then
Return "0"
End If
If Exponent = 0 Then
Return Coefficient.ToString
End If
If Coefficient = 1 Then
If Exponent = 1 Then
Return "x"
End If
Return String.Format("x^{0}", Exponent)
End If
If Coefficient = -1 Then
If Exponent = 1 Then
Return "-x"
End If
Return String.Format("-x^{0}", Exponent)
End If
If Exponent = 1 Then
Return String.Format("{0}x", Coefficient)
End If
Return String.Format("{0}x^{1}", Coefficient, Exponent)
End Function
End Class
Class Polynomial
Implements IEnumerable(Of Term)
Private ReadOnly polyTerms As New List(Of Term)
Public Sub New()
polyTerms.Add(New Term(0))
End Sub
Public Sub New(ParamArray values() As Term)
If values.Length = 0 Then
polyTerms.Add(New Term(0))
Else
polyTerms.AddRange(values)
End If
Normalize()
End Sub
Public Sub New(values As IEnumerable(Of Term))
polyTerms.AddRange(values)
If polyTerms.Count = 0 Then
polyTerms.Add(New Term(0))
End If
Normalize()
End Sub
Public Function LeadingCoeficient() As Long
Return polyTerms(0).Coefficient
End Function
Public Function Degree() As Long
Return polyTerms(0).Exponent
End Function
Public Function HasCoefficentAbs(coeff As Long) As Boolean
For Each t In polyTerms
If Math.Abs(t.Coefficient) = coeff Then
Return True
End If
Next
Return False
End Function
Public Function GetEnumerator() As IEnumerator(Of Term) Implements IEnumerable(Of Term).GetEnumerator
Return polyTerms.GetEnumerator
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return polyTerms.GetEnumerator
End Function
Private Sub Normalize()
polyTerms.Sort(Function(a As Term, b As Term) a.CompareTo(b))
End Sub
Public Shared Operator +(lhs As Polynomial, rhs As Term) As Polynomial
Dim terms As New List(Of Term)
Dim added = False
For Each ct In lhs
If ct.Exponent = rhs.Exponent Then
added = True
If ct.Coefficient + rhs.Coefficient <> 0 Then
terms.Add(ct + rhs)
End If
Else
terms.Add(ct)
End If
Next
If Not added Then
terms.Add(rhs)
End If
Return New Polynomial(terms)
End Operator
Public Shared Operator *(lhs As Polynomial, rhs As Term) As Polynomial
Dim terms As New List(Of Term)
For Each ct In lhs
terms.Add(ct * rhs)
Next
Return New Polynomial(terms)
End Operator
Public Shared Operator +(lhs As Polynomial, rhs As Polynomial) As Polynomial
Dim terms As New List(Of Term)
Dim thisCount = lhs.polyTerms.Count
Dim polyCount = rhs.polyTerms.Count
While thisCount > 0 OrElse polyCount > 0
If thisCount = 0 Then
Dim polyTerm = rhs.polyTerms(polyCount - 1)
terms.Add(polyTerm)
polyCount -= 1
ElseIf polyCount = 0 Then
Dim thisTerm = lhs.polyTerms(thisCount - 1)
terms.Add(thisTerm)
thisCount -= 1
Else
Dim polyTerm = rhs.polyTerms(polyCount - 1)
Dim thisTerm = lhs.polyTerms(thisCount - 1)
If thisTerm.Exponent = polyTerm.Exponent Then
Dim t = thisTerm + polyTerm
If t.Coefficient <> 0 Then
terms.Add(t)
End If
thisCount -= 1
polyCount -= 1
ElseIf thisTerm.Exponent < polyTerm.Exponent Then
terms.Add(thisTerm)
thisCount -= 1
Else
terms.Add(polyTerm)
polyCount -= 1
End If
End If
End While
Return New Polynomial(terms)
End Operator
Public Shared Operator *(lhs As Polynomial, rhs As Polynomial) As Polynomial
Throw New Exception("Not implemented")
End Operator
Public Shared Operator /(lhs As Polynomial, rhs As Polynomial) As Polynomial
Dim q As New Polynomial
Dim r = lhs
Dim lcv = rhs.LeadingCoeficient
Dim dv = rhs.Degree
While r.Degree >= rhs.Degree
Dim lcr = r.LeadingCoeficient
Dim s = lcr \ lcv
Dim t As New Term(s, r.Degree() - dv)
q += t
r += rhs * -t
End While
Return q
End Operator
Public Overrides Function ToString() As String
Dim builder As New StringBuilder
Dim it = polyTerms.GetEnumerator()
If it.MoveNext Then
builder.Append(it.Current)
End If
While it.MoveNext
If it.Current.Coefficient < 0 Then
builder.Append(" - ")
builder.Append(-it.Current)
Else
builder.Append(" + ")
builder.Append(it.Current)
End If
End While
Return builder.ToString
End Function
End Class
Function GetDivisors(number As Integer) As List(Of Integer)
Dim divisors As New List(Of Integer)
Dim root = CType(Math.Sqrt(number), Long)
For i = 1 To root
If number Mod i = 0 Then
divisors.Add(i)
Dim div = number \ i
If div <> i AndAlso div <> number Then
divisors.Add(div)
End If
End If
Next
Return divisors
End Function
Private ReadOnly allFactors As New Dictionary(Of Integer, Dictionary(Of Integer, Integer)) From {{2, New Dictionary(Of Integer, Integer) From {{2, 1}}}}
Function GetFactors(number As Integer) As Dictionary(Of Integer, Integer)
If allFactors.ContainsKey(number) Then
Return allFactors(number)
End If
Dim factors As New Dictionary(Of Integer, Integer)
If number Mod 2 = 0 Then
Dim factorsDivTwo = GetFactors(number \ 2)
For Each pair In factorsDivTwo
If Not factors.ContainsKey(pair.Key) Then
factors.Add(pair.Key, pair.Value)
End If
Next
If factors.ContainsKey(2) Then
factors(2) += 1
Else
factors.Add(2, 1)
End If
If number < MAX_ALL_FACTORS Then
allFactors.Add(number, factors)
End If
Return factors
End If
Dim root = CType(Math.Sqrt(number), Long)
Dim i = 3L
While i <= root
If number Mod i = 0 Then
Dim factorsDivI = GetFactors(number \ i)
For Each pair In factorsDivI
If Not factors.ContainsKey(pair.Key) Then
factors.Add(pair.Key, pair.Value)
End If
Next
If factors.ContainsKey(i) Then
factors(i) += 1
Else
factors.Add(i, 1)
End If
If number < MAX_ALL_FACTORS Then
allFactors.Add(number, factors)
End If
Return factors
End If
i += 2
End While
factors.Add(number, 1)
If number < MAX_ALL_FACTORS Then
allFactors.Add(number, factors)
End If
Return factors
End Function
Private ReadOnly computedPolynomials As New Dictionary(Of Integer, Polynomial)
Function CyclotomicPolynomial(n As Integer) As Polynomial
If computedPolynomials.ContainsKey(n) Then
Return computedPolynomials(n)
End If
If n = 1 Then
REM polynomial: x - 1
Dim p As New Polynomial(New Term(1, 1), New Term(-1))
computedPolynomials.Add(n, p)
Return p
End If
Dim factors = GetFactors(n)
Dim terms As New List(Of Term)
Dim cyclo As Polynomial
If factors.ContainsKey(n) Then
REM n prime
For index = 1 To n
terms.Add(New Term(1, index - 1))
Next
cyclo = New Polynomial(terms)
computedPolynomials.Add(n, cyclo)
Return cyclo
ElseIf factors.Count = 2 AndAlso factors.ContainsKey(2) AndAlso factors(2) = 1 AndAlso factors.ContainsKey(n / 2) AndAlso factors(n / 2) = 1 Then
REM n = 2p
Dim prime = n \ 2
Dim coeff = -1
For index = 1 To prime
coeff *= -1
terms.Add(New Term(coeff, index - 1))
Next
cyclo = New Polynomial(terms)
computedPolynomials.Add(n, cyclo)
Return cyclo
ElseIf factors.Count = 1 AndAlso factors.ContainsKey(2) Then
REM n = 2^h
Dim h = factors(2)
terms = New List(Of Term) From {
New Term(1, Math.Pow(2, h - 1)),
New Term(1)
}
cyclo = New Polynomial(terms)
computedPolynomials.Add(n, cyclo)
Return cyclo
ElseIf factors.Count = 1 AndAlso factors.ContainsKey(n) Then
REM n = p^k
Dim p = 0
Dim k = 0
For Each it In factors
p = it.Key
k = it.Value
Next
For index = 1 To p
terms.Add(New Term(1, (index - 1) * Math.Pow(p, k - 1)))
Next
cyclo = New Polynomial(terms)
computedPolynomials.Add(n, cyclo)
Return cyclo
ElseIf factors.Count = 2 AndAlso factors.ContainsKey(2) Then
REM n = 2^h * p^k
Dim p = 0
For Each it In factors
If it.Key <> 2 Then
p = it.Key
End If
Next
Dim coeff = -1
Dim twoExp = CType(Math.Pow(2, factors(2) - 1), Long)
Dim k = factors(p)
For index = 1 To p
coeff *= -1
terms.Add(New Term(coeff, (index - 1) * twoExp * Math.Pow(p, k - 1)))
Next
cyclo = New Polynomial(terms)
computedPolynomials.Add(n, cyclo)
Return cyclo
ElseIf factors.ContainsKey(2) AndAlso (n / 2) Mod 2 = 1 AndAlso n / 2 > 1 Then
REM CP(2m)[x] = CP(-m)[x], n odd integer > 1
Dim cycloDiv2 = CyclotomicPolynomial(n \ 2)
For Each t In cycloDiv2
If t.Exponent Mod 2 = 0 Then
terms.Add(t)
Else
terms.Add(-t)
End If
Next
cyclo = New Polynomial(terms)
computedPolynomials.Add(n, cyclo)
Return cyclo
End If
#If ALGORITHM = 0 Then
REM slow - uses basic definition
Dim divisors = GetDivisors(n)
REM Polynomial: (x^n - 1)
cyclo = New Polynomial(New Term(1, n), New Term(-1))
For Each i In divisors
Dim p = CyclotomicPolynomial(i)
cyclo /= p
Next
computedPolynomials.Add(n, cyclo)
Return cyclo
#ElseIf ALGORITHM = 1 Then
REM Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor
Dim divisors = GetDivisors(n)
Dim maxDivisor = Integer.MinValue
For Each div In divisors
maxDivisor = Math.Max(maxDivisor, div)
Next
Dim divisorExceptMax As New List(Of Integer)
For Each div In divisors
If maxDivisor Mod div <> 0 Then
divisorExceptMax.Add(div)
End If
Next
REM Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor
cyclo = New Polynomial(New Term(1, n), New Term(-1)) / New Polynomial(New Term(1, maxDivisor), New Term(-1))
For Each i In divisorExceptMax
Dim p = CyclotomicPolynomial(i)
cyclo /= p
Next
computedPolynomials.Add(n, cyclo)
Return cyclo
#ElseIf ALGORITHM = 2 Then
REM Fastest
REM Let p ; q be primes such that p does not divide n, and q divides n
REM Then Cp(np)[x] = CP(n)[x^p] / CP(n)[x]
Dim m = 1
cyclo = CyclotomicPolynomial(m)
Dim primes As New List(Of Integer)
For Each it In factors
primes.Add(it.Key)
Next
primes.Sort()
For Each prime In primes
REM CP(m)[x]
Dim cycloM = cyclo
REM Compute CP(m)[x^p]
terms = New List(Of Term)
For Each t In cyclo
terms.Add(New Term(t.Coefficient, t.Exponent * prime))
Next
cyclo = New Polynomial(terms) / cycloM
m *= prime
Next
REM Now, m is the largest square free divisor of n
Dim s = n \ m
REM Compute CP(n)[x] = CP(m)[x^s]
terms = New List(Of Term)
For Each t In cyclo
terms.Add(New Term(t.Coefficient, t.Exponent * s))
Next
cyclo = New Polynomial(terms)
computedPolynomials.Add(n, cyclo)
Return cyclo
#Else
Throw New Exception("Invalid algorithm")
#End If
End Function
Sub Main()
Console.WriteLine("Task 1: cyclotomic polynomials for n <= 30:")
For i = 1 To 30
Dim p = CyclotomicPolynomial(i)
Console.WriteLine("CP[{0}] = {1}", i, p)
Next
Console.WriteLine()
Console.WriteLine("Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:")
Dim n = 0
For i = 1 To 10
While True
n += 1
Dim cyclo = CyclotomicPolynomial(n)
If cyclo.HasCoefficentAbs(i) Then
Console.WriteLine("CP[{0}] has coefficient with magnitude = {1}", n, i)
n -= 1
Exit While
End If
End While
Next
End Sub
End Module |
http://rosettacode.org/wiki/Cut_a_rectangle | Cut a rectangle | A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles are shown below.
Write a program that calculates the number of different ways to cut an m × n rectangle. Optionally, show each of the cuts.
Possibly related task: Maze generation for depth-first search.
| #Wren | Wren | import "/fmt" for Fmt
var grid = []
var w = 0
var h = 0
var len = 0
var cnt = 0
var next = [0] * 4
var dir = [[0, -1], [-1, 0], [0, 1], [1, 0]]
var walk // recursive
walk = Fn.new { |y, x|
if (y == 0 || y == h || x == 0 || x == w) {
cnt = cnt + 2
return
}
var t = y * (w + 1) + x
grid[t] = grid[t] + 1
grid[len-t] = grid[len-t] + 1
for (i in 0..3) {
if (grid[t + next[i]] == 0) {
System.write("") // guard against VM recursion bug
walk.call(y + dir[i][0], x + dir[i][1])
}
}
grid[t] = grid[t] - 1
grid[len-t] = grid[len-t] - 1
}
var solve // recursive
solve = Fn.new { |hh, ww, recur|
h = hh
w = ww
if (h&1 != 0) {
var t = w
w = h
h = t
}
if (h&1 != 0) return 0
if (w == 1) return 1
if (w == 2) return h
if (h == 2) return w
var cy = (h/2).floor
var cx = (w/2).floor
len = (h + 1) * (w + 1)
grid = List.filled(len, 0)
len = len - 1
next[0] = -1
next[1] = -w - 1
next[2] = 1
next[3] = w + 1
if (recur) cnt = 0
var x = cx + 1
while (x < w) {
var t = cy * (w + 1) + x
grid[t] = 1
grid[len-t] = 1
walk.call(cy - 1, x)
x = x + 1
}
cnt = cnt + 1
if (h == w) {
cnt = cnt * 2
} else if ((w&1 == 0) && recur) {
System.write("") // guard against VM recursion bug
solve.call(w, h, false)
}
return cnt
}
for (y in 1..10) {
for (x in 1..y) {
if ((x&1 == 0) || (y&1 ==0)) {
Fmt.print("$2d x $2d : $d", y, x, solve.call(y, x, true))
}
}
} |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Lua | Lua |
str = string.lower( "March 7 2009 7:30pm EST" )
month = string.match( str, "%a+" )
if month == "january" then month = 1
elseif month == "february" then month = 2
elseif month == "march" then month = 3
elseif month == "april" then month = 4
elseif month == "may" then month = 5
elseif month == "june" then month = 6
elseif month == "july" then month = 7
elseif month == "august" then month = 8
elseif month == "september" then month = 9
elseif month == "october" then month = 10
elseif month == "november" then month = 11
elseif month == "december" then month = 12
end
strproc = string.gmatch( str, "%d+" )
day = strproc()
year = strproc()
hour = strproc()
min = strproc()
if string.find( str, "pm" ) then hour = hour + 12 end
print( os.date( "%c", os.time{ year=year, month=month, day=day, hour=hour, min=min, sec=0 } + 12 * 3600 ) )
|
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #FutureBasic | FutureBasic | window 1
long y
CFDateRef dt
NSInteger day
CFCalendarRef cal
DateComponentsRef comps
cal = fn CalendarCurrent
comps = fn DateComponentsInit
DateComponentsSetMonth( comps, 12 )
DateComponentsSetDay( comps, 25 )
for y = 2008 to 2121
DateComponentsSetYear( comps, y )
dt = fn CalendarDateFromComponents( cal, comps )
day = fn CalendarComponentFromDate( cal, NSCalendarUnitWeekday, dt )
if ( day == 1 )
print y
end if
next
HandleEvents |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #Gambas | Gambas | Public Sub Main()
Dim siCount As Short
For siCount = 2008 To 2121
If WeekDay(Date(siCount, 12, 25)) = 0 Then Print Format(Date(siCount, 12, 25), "dddd dd mmmm yyyy") & " falls on a Sunday"
Next
End |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #JavaScript | JavaScript | (() => {
'use strict';
// cusipValid = Dict Char Int -> String -> Bool
const cusipValid = charMap => s => {
const
ns = fromMaybe([])(
traverse(flip(lookupDict)(charMap))(
chars(s)
)
);
return 9 === ns.length && (
last(ns) === rem(
10 - rem(
sum(apList(
apList([quot, rem])(
zipWith(identity)(
cycle([identity, x => 2 * x])
)(take(8)(ns))
)
)([10]))
)(10)
)(10)
);
};
//----------------------- TEST ------------------------
// main :: IO ()
const main = () => {
// cusipMap :: Dict Char Int
const cusipMap = dictFromList(
zip(chars(
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#"
))(enumFrom(0)));
console.log(unlines(map(
apFn(
s => validity => s + ' -> ' + str(validity)
)(cusipValid(cusipMap))
)([
'037833100',
'17275R102',
'38259P508',
'594918104',
'68389X106',
'68389X105'
])));
};
//----------------- GENERIC FUNCTIONS -----------------
// Just :: a -> Maybe a
const Just = x => ({
type: 'Maybe',
Nothing: false,
Just: x
});
// Nothing :: Maybe a
const Nothing = () => ({
type: 'Maybe',
Nothing: true,
});
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a =>
b => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
// apFn :: (a -> b -> c) -> (a -> b) -> a -> c
const apFn = f =>
// Applicative instance for functions.
// f(x) applied to g(x).
g => x => f(x)(
g(x)
);
// apList (<*>) :: [(a -> b)] -> [a] -> [b]
const apList = fs =>
// The sequential application of each of a list
// of functions to each of a list of values.
xs => fs.flatMap(
f => xs.map(f)
);
// append (++) :: [a] -> [a] -> [a]
// append (++) :: String -> String -> String
const append = xs =>
// A list or string composed by
// the concatenation of two others.
ys => xs.concat(ys);
// chars :: String -> [Char]
const chars = s =>
s.split('');
// cons :: a -> [a] -> [a]
const cons = x =>
xs => Array.isArray(xs) ? (
[x].concat(xs)
) : 'GeneratorFunction' !== xs
.constructor.constructor.name ? (
x + xs
) : ( // cons(x)(Generator)
function*() {
yield x;
let nxt = xs.next()
while (!nxt.done) {
yield nxt.value;
nxt = xs.next();
}
}
)();
// cycle :: [a] -> Generator [a]
function* cycle(xs) {
const lng = xs.length;
let i = 0;
while (true) {
yield(xs[i])
i = (1 + i) % lng;
}
}
// dictFromList :: [(k, v)] -> Dict
const dictFromList = kvs =>
Object.fromEntries(kvs);
// enumFrom :: Enum a => a -> [a]
function* enumFrom(x) {
// A non-finite succession of enumerable
// values, starting with the value x.
let v = x;
while (true) {
yield v;
v = succ(v);
}
}
// flip :: (a -> b -> c) -> b -> a -> c
const flip = f =>
1 < f.length ? (
(a, b) => f(b, a)
) : (x => y => f(y)(x));
// fromEnum :: Enum a => a -> Int
const fromEnum = x =>
typeof x !== 'string' ? (
x.constructor === Object ? (
x.value
) : parseInt(Number(x))
) : x.codePointAt(0);
// fromMaybe :: a -> Maybe a -> a
const fromMaybe = def =>
// A default value if mb is Nothing
// or the contents of mb.
mb => mb.Nothing ? def : mb.Just;
// fst :: (a, b) -> a
const fst = tpl =>
// First member of a pair.
tpl[0];
// identity :: a -> a
const identity = x =>
// The identity function. (`id`, in Haskell)
x;
// last :: [a] -> a
const last = xs =>
// The last item of a list.
0 < xs.length ? xs.slice(-1)[0] : undefined;
// length :: [a] -> Int
const length = xs =>
// Returns Infinity over objects without finite
// length. This enables zip and zipWith to choose
// the shorter argument when one is non-finite,
// like cycle, repeat etc
(Array.isArray(xs) || 'string' === typeof xs) ? (
xs.length
) : Infinity;
// liftA2 :: (a -> b -> c) -> Maybe a -> Maybe b -> Maybe c
const liftA2 = f => a => b =>
a.Nothing ? a : b.Nothing ? b : Just(f(a.Just)(b.Just));
// lookupDict :: a -> Dict -> Maybe b
const lookupDict = k => dct => {
const v = dct[k];
return undefined !== v ? (
Just(v)
) : Nothing();
};
// map :: (a -> b) -> [a] -> [b]
const map = f =>
// The list obtained by applying f
// to each element of xs.
// (The image of xs under f).
xs => (
Array.isArray(xs) ? (
xs
) : xs.split('')
).map(f);
// pureMay :: a -> Maybe a
const pureMay = x => Just(x);
// Given a type name string, returns a
// specialised 'pure', where
// 'pure' lifts a value into a particular functor.
// pureT :: String -> f a -> (a -> f a)
const pureT = t => x =>
'List' !== t ? (
'Either' === t ? (
pureLR(x)
) : 'Maybe' === t ? (
pureMay(x)
) : 'Node' === t ? (
pureTree(x)
) : 'Tuple' === t ? (
pureTuple(x)
) : pureList(x)
) : pureList(x);
// pureTuple :: a -> (a, a)
const pureTuple = x =>
Tuple('')(x);
// quot :: Int -> Int -> Int
const quot = n =>
m => Math.floor(n / m);
// rem :: Int -> Int -> Int
const rem = n => m => n % m;
// snd :: (a, b) -> b
const snd = tpl => tpl[1];
// str :: a -> String
const str = x =>
x.toString();
// succ :: Enum a => a -> a
const succ = x => {
const t = typeof x;
return 'number' !== t ? (() => {
const [i, mx] = [x, maxBound(x)].map(fromEnum);
return i < mx ? (
toEnum(x)(1 + i)
) : Error('succ :: enum out of range.')
})() : x < Number.MAX_SAFE_INTEGER ? (
1 + x
) : Error('succ :: Num out of range.')
};
// sum :: [Num] -> Num
const sum = xs =>
// The numeric sum of all values in xs.
xs.reduce((a, x) => a + x, 0);
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => 'GeneratorFunction' !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
// The first argument is a sample of the type
// allowing the function to make the right mapping
// toEnum :: a -> Int -> a
const toEnum = e => x =>
({
'number': Number,
'string': String.fromCodePoint,
'boolean': Boolean,
'object': v => e.min + v
} [typeof e])(x);
// traverse :: (Applicative f) => (a -> f b) -> [a] -> f [b]
const traverse = f =>
// Collected results of mapping each element
// of a structure to an action, and evaluating
// these actions from left to right.
xs => 0 < xs.length ? (() => {
const
vLast = f(xs.slice(-1)[0]),
t = vLast.type || 'List';
return xs.slice(0, -1).reduceRight(
(ys, x) => liftA2(cons)(f(x))(ys),
liftA2(cons)(vLast)(pureT(t)([]))
);
})() : [
[]
];
// uncons :: [a] -> Maybe (a, [a])
const uncons = xs => {
// Just a tuple of the head of xs and its tail,
// Or Nothing if xs is an empty list.
const lng = length(xs);
return (0 < lng) ? (
Infinity > lng ? (
Just(Tuple(xs[0])(xs.slice(1))) // Finite list
) : (() => {
const nxt = take(1)(xs);
return 0 < nxt.length ? (
Just(Tuple(nxt[0])(xs))
) : Nothing();
})() // Lazy generator
) : Nothing();
};
// uncurry :: (a -> b -> c) -> ((a, b) -> c)
const uncurry = f =>
// A function over a pair, derived
// from a curried function.
x => ((...args) => {
const
xy = 1 < args.length ? (
args
) : args[0];
return f(xy[0])(xy[1]);
})(x);
// unlines :: [String] -> String
const unlines = xs =>
// A single string formed by the intercalation
// of a list of strings with the newline character.
xs.join('\n');
// zip :: [a] -> [b] -> [(a, b)]
const zip = xs =>
// Use of `take` and `length` here allows for zipping with non-finite
// lists - i.e. generators like cycle, repeat, iterate.
ys => {
const
lng = Math.min(length(xs), length(ys)),
vs = take(lng)(ys);
return take(lng)(xs).map(
(x, i) => Tuple(x)(vs[i])
);
};
// Use of `take` and `length` here allows zipping with non-finite lists
// i.e. generators like cycle, repeat, iterate.
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = f => xs => ys => {
const lng = Math.min(length(xs), length(ys));
return Infinity > lng ? (() => {
const
as = take(lng)(xs),
bs = take(lng)(ys);
return Array.from({
length: lng
}, (_, i) => f(as[i])(
bs[i]
));
})() : zipWithGen(f)(xs)(ys);
};
// zipWithGen :: (a -> b -> c) ->
// Gen [a] -> Gen [b] -> Gen [c]
const zipWithGen = f => ga => gb => {
function* go(ma, mb) {
let
a = ma,
b = mb;
while (!a.Nothing && !b.Nothing) {
let
ta = a.Just,
tb = b.Just
yield(f(fst(ta))(fst(tb)));
a = uncons(snd(ta));
b = uncons(snd(tb));
}
}
return go(uncons(ga), uncons(gb));
};
// MAIN ---
return main();
})(); |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace standardDeviation
{
class Program
{
static void Main(string[] args)
{
List<double> nums = new List<double> { 2, 4, 4, 4, 5, 5, 7, 9 };
for (int i = 1; i <= nums.Count; i++)
Console.WriteLine(sdev(nums.GetRange(0, i)));
}
static double sdev(List<double> nums)
{
List<double> store = new List<double>();
foreach (double n in nums)
store.Add((n - nums.Average()) * (n - nums.Average()));
return Math.Sqrt(store.Sum() / store.Count);
}
}
} |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #F.23 | F# | > open System;;
> Console.WriteLine( DateTime.Now.ToString("yyyy-MM-dd") );;
2010-08-13
> Console.WriteLine( "{0:D}", DateTime.Now );;
Friday, August 13, 2010 |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Factor | Factor | USING: formatting calendar io ;
now "%Y-%m-%d" strftime print
now "%A, %B %d, %Y" strftime print |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #C.23 | C# | using System.IO;
using System.Linq;
namespace CSV_data_manipulation
{
class Program
{
static void Main()
{
var input = File.ReadAllLines("test_in.csv");
var output = input.Select((line, i) =>
{
if (i == 0)
return line + ",SUM";
var sum = line.Split(',').Select(int.Parse).Sum();
return line + "," + sum;
}).ToArray();
File.WriteAllLines("test_out.csv", output);
}
}
}
|
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #J | J | OpTbl=: _99 ". ];._2 noun define
0 3 1 7 5 9 8 6 4 2
7 0 9 2 1 5 4 8 6 3
4 2 0 6 8 7 1 3 5 9
1 7 5 0 9 8 3 4 2 6
6 1 2 3 0 4 5 9 7 8
3 6 7 4 2 0 9 5 8 1
5 8 6 9 7 2 0 1 3 4
8 9 4 5 3 6 2 0 1 7
9 4 3 8 6 1 7 2 0 5
2 5 8 1 4 3 6 7 9 0
)
getdigits=: 10&#.inv
getDamm=: verb define
row=. 0
for_digit. getdigits y do.
row=. OpTbl {~ <row,digit
end.
)
checkDamm=: 0 = getDamm |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
| #C.2B.2B | C++ | #include <iostream>
#include <vector>
#include <chrono>
#include <climits>
#include <cmath>
using namespace std;
vector <long long> primes{ 3, 5 };
int main()
{
cout.imbue(locale(""));
const int cutOff = 200, bigUn = 100000,
chunks = 50, little = bigUn / chunks;
const char tn[] = " cuban prime";
cout << "The first " << cutOff << tn << "s:" << endl;
int c = 0;
bool showEach = true;
long long u = 0, v = 1;
auto st = chrono::system_clock::now();
for (long long i = 1; i <= LLONG_MAX; i++)
{
bool found = false;
long long mx = (long long)(ceil(sqrt(v += (u += 6))));
for (long long item : primes)
{
if (item > mx) break;
if (v % item == 0) { found = true; break; }
}
if (!found)
{
c += 1; if (showEach)
{
for (long long z = primes.back() + 2; z <= v - 2; z += 2)
{
bool fnd = false;
for (long long item : primes)
{
if (item > mx) break;
if (z % item == 0) { fnd = true; break; }
}
if (!fnd) primes.push_back(z);
}
primes.push_back(v); cout.width(11); cout << v;
if (c % 10 == 0) cout << endl;
if (c == cutOff)
{
showEach = false;
cout << "\nProgress to the " << bigUn << "th" << tn << ": ";
}
}
if (c % little == 0) { cout << "."; if (c == bigUn) break; }
}
}
cout << "\nThe " << c << "th" << tn << " is " << v;
chrono::duration<double> elapsed_seconds = chrono::system_clock::now() - st;
cout << "\nComputation time was " << elapsed_seconds.count() << " seconds" << endl;
return 0;
} |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #JCL | JCL | // EXEC PGM=IEBGENER
//* Create a file named "TAPE.FILE" on magnetic tape; "UNIT=TAPE"
//* may vary depending on site-specific esoteric name assignment
//SYSPRINT DD SYSOUT=*
//SYSIN DD DUMMY
//SYSUT2 DD UNIT=TAPE,DSN=TAPE.FILE,DISP=(,CATLG)
//SYSUT1 DD *
DATA TO BE WRITTEN TO TAPE
/* |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Julia | Julia |
open("/dev/tape", "w") do f
write(f, "Hello tape!")
end
|
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Kotlin | Kotlin | // version 1.1.0 (Linux)
import java.io.FileWriter
fun main(args: Array<String>) {
val lp0 = FileWriter("/dev/tape")
lp0.write("Hello, world!")
lp0.close()
} |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Lua | Lua | require "lfs"
local out
if lfs.attributes('/dev/tape') then
out = '/dev/tape'
else
out = 'tape.file'
end
file = io.open(out, 'w')
file:write('Hello world')
io.close(file) |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Nim | Nim | var t = open("/dev/tape", fmWrite)
t.writeln "Hi Tape!"
t.close |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Phix | Phix | include builtins/write_file.e
constant filepath = iff(platform()=WINDOWS?"tape.file":"/dev/tape"),
write_file(file_path,"Hello world!") |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
| #Julia | Julia | using Printf
p = [big"5.50", big"2.86"]
q = [4000000000000000, 2]
tr = big"0.0765"
beftax = p' * q
tax = beftax * tr
afttax = beftax + tax
@printf " - tot. before tax: %20.2f \$\n" beftax
@printf " - tax: %20.2f \$\n" tax
@printf " - tot. after tax: %20.2f \$\n" afttax |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
| #Kotlin | Kotlin | // version 1.1.2
import java.math.BigDecimal
import java.math.MathContext
fun main(args: Array<String>) {
val mc = MathContext.DECIMAL128
val nHamburger = BigDecimal("4000000000000000", mc)
val pHamburger = BigDecimal("5.50")
val nMilkshakes = BigDecimal("2", mc)
val pMilkshakes = BigDecimal("2.86")
val taxRate = BigDecimal("0.0765")
val price = nHamburger * pHamburger + nMilkshakes * pMilkshakes
val tax = price * taxRate
val fmt = "%20.2f"
println("Total price before tax : ${fmt.format(price)}")
println("Tax thereon @ 7.65% : ${fmt.format(tax)}")
println("Total price after tax : ${fmt.format(price + tax)}")
} |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
| #Java | Java | public class Currier<ARG1, ARG2, RET> {
public interface CurriableFunctor<ARG1, ARG2, RET> {
RET evaluate(ARG1 arg1, ARG2 arg2);
}
public interface CurriedFunctor<ARG2, RET> {
RET evaluate(ARG2 arg);
}
final CurriableFunctor<ARG1, ARG2, RET> functor;
public Currier(CurriableFunctor<ARG1, ARG2, RET> fn) { functor = fn; }
public CurriedFunctor<ARG2, RET> curry(final ARG1 arg1) {
return new CurriedFunctor<ARG2, RET>() {
public RET evaluate(ARG2 arg2) {
return functor.evaluate(arg1, arg2);
}
};
}
public static void main(String[] args) {
Currier.CurriableFunctor<Integer, Integer, Integer> add
= new Currier.CurriableFunctor<Integer, Integer, Integer>() {
public Integer evaluate(Integer arg1, Integer arg2) {
return new Integer(arg1.intValue() + arg2.intValue());
}
};
Currier<Integer, Integer, Integer> currier
= new Currier<Integer, Integer, Integer>(add);
Currier.CurriedFunctor<Integer, Integer> add5
= currier.curry(new Integer(5));
System.out.println(add5.evaluate(new Integer(2)));
}
} |
http://rosettacode.org/wiki/Create_an_object_at_a_given_address | Create an object at a given address |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #Rust | Rust | use std::{mem,ptr};
fn main() {
let mut data: i32;
// Rust does not allow us to use uninitialized memory but the STL provides an `unsafe`
// function to override this protection.
unsafe {data = mem::uninitialized()}
// Construct a raw pointer (perfectly safe)
let address = &mut data as *mut _;
unsafe {ptr::write(address, 5)}
println!("{0:p}: {0}", &data);
unsafe {ptr::write(address, 6)}
println!("{0:p}: {0}", &data);
} |
http://rosettacode.org/wiki/Create_an_object_at_a_given_address | Create an object at a given address |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #S-BASIC | S-BASIC |
var first, addr = integer
based second = integer
first = 12345
location var addr = first
base second at addr
print "Value of first variable ="; first
print "Address of first variable = "; hex$(addr)
print "Value of second variable ="; second
end
|
http://rosettacode.org/wiki/Create_an_object_at_a_given_address | Create an object at a given address |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #Scala | Scala | package require critcl
# A command to 'make an integer object' and couple it to a Tcl variable
critcl::cproc linkvar {Tcl_Interp* interp char* var1} int {
int *intPtr = (int *) ckalloc(sizeof(int));
*intPtr = 0;
Tcl_LinkVar(interp, var1, (void *) intPtr, TCL_LINK_INT);
return (int) intPtr;
}
# A command to couple another Tcl variable to an 'integer object'; UNSAFE!
critcl::cproc linkagain(Tcl_Interp* interp int addr char* var2} void {
int *intPtr = (int *) addr;
Tcl_LinkVar(interp, var2, (void *) intPtr, TCL_LINK_INT);
}
# Conventionally, programs that use critcl structure in packages
# This is used to prevent recompilation, especially on systems like Windows
package provide machAddrDemo 1 |
http://rosettacode.org/wiki/Create_an_object_at_a_given_address | Create an object at a given address |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #Tcl | Tcl | package require critcl
# A command to 'make an integer object' and couple it to a Tcl variable
critcl::cproc linkvar {Tcl_Interp* interp char* var1} int {
int *intPtr = (int *) ckalloc(sizeof(int));
*intPtr = 0;
Tcl_LinkVar(interp, var1, (void *) intPtr, TCL_LINK_INT);
return (int) intPtr;
}
# A command to couple another Tcl variable to an 'integer object'; UNSAFE!
critcl::cproc linkagain(Tcl_Interp* interp int addr char* var2} void {
int *intPtr = (int *) addr;
Tcl_LinkVar(interp, var2, (void *) intPtr, TCL_LINK_INT);
}
# Conventionally, programs that use critcl structure in packages
# This is used to prevent recompilation, especially on systems like Windows
package provide machAddrDemo 1 |
http://rosettacode.org/wiki/Cyclotomic_polynomial | Cyclotomic polynomial | The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n.
Task
Find and print the first 30 cyclotomic polynomials.
Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient.
See also
Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.
The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient. | #Wren | Wren | import "/trait" for Stepped
import "/sort" for Sort
import "/math" for Int, Nums
import "/fmt" for Fmt
var algo = 2
var maxAllFactors = 1e5
class Term {
construct new(coef, exp) {
_coef = coef
_exp = exp
}
coef { _coef }
exp { _exp }
*(t) { Term.new(_coef * t.coef, _exp + t.exp) }
+(t) {
if (_exp != t.exp) Fiber.abort("Exponents unequal in term '+' method.")
return Term.new(_coef + t.coef, _exp)
}
- { Term.new(-_coef, _exp) }
toString {
if (_coef == 0) return "0"
if (_exp == 0) return _coef.toString
if (_coef == 1) return (_exp == 1) ? "x" : "x^%(_exp)"
if (_exp == 1) return "%(_coef)x"
return "%(_coef)x^%(_exp)"
}
}
class Poly {
// pass coef, exp in pairs as parameters
construct new(values) {
var le = values.count
if (le == 0) {
_terms = [Term.new(0, 0)]
} else {
if (le%2 != 0) Fiber.abort("Odd number of parameters(%(le)) passed to Poly constructor.")
_terms = []
for (i in Stepped.new(0...le, 2)) _terms.add(Term.new(values[i], values[i+1]))
tidy()
}
}
terms { _terms }
hasCoefAbs(coef) { _terms.any { |t| t.coef.abs == coef } }
+(p2) {
var p3 = Poly.new([])
var le = _terms.count
var le2 = p2.terms.count
while (le > 0 || le2 > 0) {
if (le == 0) {
p3.terms.add(p2.terms[le2-1])
le2 = le2 - 1
} else if (le2 == 0) {
p3.terms.add(_terms[le-1])
le = le - 1
} else {
var t = _terms[le-1]
var t2 = p2.terms[le2-1]
if (t.exp == t2.exp) {
var t3 = t + t2
if (t3.coef != 0) p3.terms.add(t3)
le = le - 1
le2 = le2 - 1
} else if (t.exp < t2.exp) {
p3.terms.add(t)
le = le - 1
} else {
p3.terms.add(t2)
le2 = le2 - 1
}
}
}
p3.tidy()
return p3
}
addTerm(t) {
var q = Poly.new([])
var added = false
for (i in 0..._terms.count) {
var ct = _terms[i]
if (ct.exp == t.exp) {
added = true
if (ct.coef + t.coef != 0) q.terms.add(ct + t)
} else {
q.terms.add(ct)
}
}
if (!added) q.terms.add(t)
q.tidy()
return q
}
mulTerm(t) {
var q = Poly.new([])
for (i in 0..._terms.count) {
var ct = _terms[i]
q.terms.add(ct * t)
}
q.tidy()
return q
}
/(v) {
var p = this
var q = Poly.new([])
var lcv = v.leadingCoef
var dv = v.degree
while (p.degree >= v.degree) {
var lcp = p.leadingCoef
var s = (lcp/lcv).truncate
var t = Term.new(s, p.degree - dv)
q = q.addTerm(t)
p = p + v.mulTerm(-t)
}
q.tidy()
return q
}
leadingCoef { _terms[0].coef }
degree { _terms[0].exp }
toString {
var sb = ""
var first = true
for (t in _terms) {
if (first) {
sb = sb + t.toString
first = false
} else {
sb = sb + " "
if (t.coef > 0) {
sb = sb + "+ "
sb = sb + t.toString
} else {
sb = sb + "- "
sb = sb + (-t).toString
}
}
}
return sb
}
// in place descending sort by term.exp
sortTerms() {
var cmp = Fn.new { |t1, t2| (t2.exp - t1.exp).sign }
Sort.quick(_terms, 0, _terms.count-1, cmp)
}
// sort terms and remove any unnecesary zero terms
tidy() {
sortTerms()
if (degree > 0) {
for (i in _terms.count-1..0) {
if (_terms[i].coef == 0) _terms.removeAt(i)
}
if (_terms.count == 0) _terms.add(Term.new(0, 0))
}
}
}
var computed = {}
var allFactors = {2: {2: 1}}
var getFactors // recursive function
getFactors = Fn.new { |n|
var f = allFactors[n]
if (f) return f
var factors = {}
if (n%2 == 0) {
var factorsDivTwo = getFactors.call(n/2)
for (me in factorsDivTwo) factors[me.key] = me.value
factors[2] = factors[2] ? factors[2] + 1 : 1
if (n < maxAllFactors) allFactors[n] = factors
return factors
}
var prime = true
var sqrt = n.sqrt.floor
var i = 3
while (i <= sqrt){
if (n%i == 0) {
prime = false
for (me in getFactors.call(n/i)) factors[me.key] = me.value
factors[i] = factors[i] ? factors[i] + 1 : 1
if (n < maxAllFactors) allFactors[n] = factors
return factors
}
i = i + 2
}
if (prime) {
factors[n] = 1
if (n < maxAllFactors) allFactors[n] = factors
}
return factors
}
var cycloPoly // recursive function
cycloPoly = Fn.new { |n|
var p = computed[n]
if (p) return p
if (n == 1) {
// polynomialL x - 1
p = Poly.new([1, 1, -1, 0])
computed[1] = p
return p
}
var factors = getFactors.call(n)
var cyclo = Poly.new([])
if (factors[n]) {
// n is prime
for (i in 0...n) cyclo.terms.add(Term.new(1, i))
} else if (factors.count == 2 && factors[2] == 1 && factors[n/2] == 1) {
// n == 2p
var prime = n / 2
var coef = -1
for (i in 0...prime) {
coef = coef * (-1)
cyclo.terms.add(Term.new(coef, i))
}
} else if (factors.count == 1) {
var h = factors[2]
if (h) { // n == 2^h
cyclo.terms.addAll([Term.new(1, 1 << (h-1)), Term.new(1, 0)])
} else if (!factors[n]) {
// n == p ^ k
var p = 0
for (prime in factors.keys) p = prime
var k = factors[p]
for (i in 0...p) {
var pk = p.pow(k-1).floor
cyclo.terms.add(Term.new(1, i * pk))
}
}
} else if (factors.count == 2 && factors[2]) {
// n = 2^h * p^k
var p = 0
for (prime in factors.keys) if (prime != 2) p = prime
var coef = -1
var twoExp = 1 << (factors[2] - 1)
var k = factors[p]
for (i in 0...p) {
coef = coef * (-1)
var pk = p.pow(k-1).floor
cyclo.terms.add(Term.new(coef, i * twoExp * pk))
}
} else if (factors[2] && (n/2) % 2 == 1 && (n/2) > 1) {
// CP(2m)[x] == CP(-m)[x], n odd integer > 1
var cycloDiv2 = cycloPoly.call(n/2)
for (t in cycloDiv2.terms) {
var t2 = t
if (t.exp % 2 != 0) t2 = -t
cyclo.terms.add(t2)
}
} else if (algo == 0) {
// slow - uses basic definition
var divs = Int.properDivisors(n)
// polynomial: x^n - 1
var cyclo = Poly.new([1, n, -1, 0])
for (i in divs) {
var p = cycloPoly.call(i)
cyclo = cyclo / p
}
} else if (algo == 1) {
// faster - remove max divisor (and all divisors of max divisor)
// only one divide for all divisors of max divisor
var divs = Int.properDivisors(n)
var maxDiv = Nums.max(divs)
var divsExceptMax = divs.where { |d| maxDiv % d != 0 }.toList
// polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor
cyclo = Poly.new([1, n, -1, 0])
cyclo = cyclo / Poly.new([1, maxDiv, -1, 0])
for (i in divsExceptMax) {
var p = cycloPoly.call(i)
cyclo = cyclo / p
}
} else if (algo == 2) {
// fastest
// let p, q be primes such that p does not divide n, and q divides n
// then CP(np)[x] = CP(n)[x^p] / CP(n)[x]
var m = 1
cyclo = cycloPoly.call(m)
var primes = []
for (prime in factors.keys) primes.add(prime)
Sort.quick(primes)
for (prime in primes) {
// CP(m)[x]
var cycloM = cyclo
// compute CP(m)[x^p]
var terms = []
for (t in cycloM.terms) terms.add(Term.new(t.coef, t.exp * prime))
cyclo = Poly.new([])
cyclo.terms.addAll(terms)
cyclo.tidy()
cyclo = cyclo / cycloM
m = m * prime
}
// now, m is the largest square free divisor of n
var s = n / m
// Compute CP(n)[x] = CP(m)[x^s]
var terms = []
for (t in cyclo.terms) terms.add(Term.new(t.coef, t.exp * s))
cyclo = Poly.new([])
cyclo.terms.addAll(terms)
} else {
Fiber.abort("Invalid algorithm.")
}
cyclo.tidy()
computed[n] = cyclo
return cyclo
}
System.print("Task 1: cyclotomic polynomials for n <= 30:")
for (i in 1..30) {
var p = cycloPoly.call(i)
Fmt.print("CP[$2d] = $s", i, p)
}
System.print("\nTask 2: Smallest cyclotomic polynomial with n or -n as a coefficient:")
var n = 0
for (i in 1..7) {
while(true) {
n = n + 1
var cyclo = cycloPoly.call(n)
if (cyclo.hasCoefAbs(i)) {
Fmt.print("CP[$d] has coefficient with magnitude = $d", n, i)
n = n - 1
break
}
}
} |
http://rosettacode.org/wiki/Cut_a_rectangle | Cut a rectangle | A given rectangle is made from m × n squares. If m and n are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180°). All such paths for 2 × 2 and 4 × 3 rectangles are shown below.
Write a program that calculates the number of different ways to cut an m × n rectangle. Optionally, show each of the cuts.
Possibly related task: Maze generation for depth-first search.
| #zkl | zkl | fcn cut_it(h,w){
if(h.isOdd){
if(w.isOdd) return(0);
t,h,w=h,w,t; // swap w,h: a,b=c,d --> a=c; b=d; so need a tmp
}
if(w==1) return(1);
nxt :=T(T(w+1, 1,0), T(-w-1, -1,0), T(-1, 0,-1), T(1, 0,1)); #[next, dy,dx]
blen:=(h + 1)*(w + 1) - 1;
grid:=(blen + 1).pump(List(),False); //-->L(False,False...)
walk:='wrap(y,x){ // lambda closure
if(y==0 or y==h or x==0 or x==w) return(1);
count,t:=0,y*(w + 1) + x;
grid[t]=grid[blen - t]=True;
foreach nt,dy,dx in (nxt){
if(not grid[t + nt]) count+=self.fcn(y + dy, x + dx,vm.pasteArgs(2));
}
grid[t]=grid[blen - t]=False;
count
};
t:=h/2*(w + 1) + w/2;
if(w.isOdd){
grid[t]=grid[t + 1]=True;
count:=walk(h/2, w/2 - 1);
count + walk(h/2 - 1, w/2)*2;
}else{
grid[t]=True;
count:=walk(h/2, w/2 - 1);
if(h==w) return(count*2);
count + walk(h/2 - 1, w/2);
}
} |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Maple | Maple | twelve_hours := proc(str)
local dt, zone;
local months := ["January","February","March","April","May","June","July","August","September","October","November","December"];
dt := StringTools:-ParseTime("%B %d %Y %l:%M%p", str);
zone := StringTools:-RegSplit(" ", str)[-1];
dt := Date(dt:-year, dt:-month, dt:-monthDay, dt:-hour, dt:-minute, timezone = zone);
dt := dt + 12 * Unit(hours);
printf("%s %d %d ", months[Month(dt)], DayOfMonth(dt), Year(dt));
if (HourOfDay(dt) >= 12) then
printf("%d:%dpm ", HourOfDay(dt)-12, Minute(dt));
else
printf("%d:%dam ", HourOfDay(dt), Minute(dt));
end if;
printf(TimeZone(dt));
end proc;
|
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | dstr = "March 7 2009 7:30pm EST";
DateString[DatePlus[dstr, {12, "Hour"}], {"DayName", " ", "MonthName", " ", "Day", " ", "Year", " ", "Hour24", ":", "Minute", "AMPM"}] |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #GAP | GAP | Filtered([2008 .. 2121], y -> WeekDay([25, 12, y]) = "Sun");
# [ 2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118 ]
# A possible implementation of WeekDayAlt
days := ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];;
WeekDayAlt := function(args)
local d, m, y, k;
d := args[1];
m := args[2];
y := args[3];
if m < 3 then
m := m + 12;
y := y - 1;
fi;
k := 1 + RemInt(d + QuoInt((m + 1)*26, 10) + y + QuoInt(y, 4)
+ 6*QuoInt(y, 100) + QuoInt(y, 400) + 5, 7);
return days[k];
end;
Filtered([2008 .. 2121], y -> WeekDayAlt([25, 12, y]) = "Sun");
# [ 2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118 ] |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #Go | Go | package main
import "fmt"
import "time"
func main() {
for year := 2008; year <= 2121; year++ {
if time.Date(year, 12, 25, 0, 0, 0, 0, time.UTC).Weekday() ==
time.Sunday {
fmt.Printf("25 December %d is Sunday\n", year)
}
}
} |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #Julia | Julia | module CUSIP
function _lastdigitcusip(input::AbstractString)
input = uppercase(input)
s = 0
for (i, c) in enumerate(input)
if isdigit(c)
v = Int(c) - 48
elseif isalpha(c)
v = Int(c) - 64 + 9
elseif c == '*'
v = 36
elseif c == '@'
v = 37
elseif c == '#'
v = 38
end
if iseven(i); v *= 2 end
s += div(v, 10) + rem(v, 10)
end
return Char(rem(10 - rem(s, 10), 10) + 48)
end
checkdigit(input::AbstractString) = input[9] == _lastdigitcusip(input[1:8])
end # module CUSIP
for code in ("037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105")
println("$code is ", CUSIP.checkdigit(code) ? "correct." : "not correct.")
end |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #Kotlin | Kotlin | // version 1.1.0
fun isCusip(s: String): Boolean {
if (s.length != 9) return false
var sum = 0
for (i in 0..7) {
val c = s[i]
var v = when (c) {
in '0'..'9' -> c.toInt() - 48
in 'A'..'Z' -> c.toInt() - 55 // lower case letters apparently invalid
'*' -> 36
'@' -> 37
'#' -> 38
else -> return false
}
if (i % 2 == 1) v *= 2 // check if odd as using 0-based indexing
sum += v / 10 + v % 10
}
return s[8].toInt() - 48 == (10 - (sum % 10)) % 10
}
fun main(args: Array<String>) {
val candidates = listOf(
"037833100",
"17275R102",
"38259P508",
"594918104",
"68389X106",
"68389X105"
)
for (candidate in candidates)
println("$candidate -> ${if(isCusip(candidate)) "correct" else "incorrect"}")
} |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #C.2B.2B | C++ |
#include <assert.h>
#include <cmath>
#include <vector>
#include <iostream>
template<int N> struct MomentsAccumulator_
{
std::vector<double> m_;
MomentsAccumulator_() : m_(N + 1, 0.0) {}
void operator()(double v)
{
double inc = 1.0;
for (auto& mi : m_)
{
mi += inc;
inc *= v;
}
}
};
double Stdev(const std::vector<double>& moments)
{
assert(moments.size() > 2);
assert(moments[0] > 0.0);
const double mean = moments[1] / moments[0];
const double meanSquare = moments[2] / moments[0];
return sqrt(meanSquare - mean * mean);
}
int main(void)
{
std::vector<int> data({ 2, 4, 4, 4, 5, 5, 7, 9 });
MomentsAccumulator_<2> accum;
for (auto d : data)
{
accum(d);
std::cout << "Running stdev: " << Stdev(accum.m_) << "\n";
}
}
|
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Fantom | Fantom |
fansh> Date.today.toLocale("YYYY-MM-DD")
2011-02-24
fansh> Date.today.toLocale("WWWW, MMMM DD, YYYY")
Thursday, February 24, 2011
|
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Forth | Forth | : .-0 ( n -- n )
[char] - emit
dup 10 < if [char] 0 emit then ;
: .short-date
time&date ( s m h D M Y )
1 u.r .-0 1 u.r .-0 1 u.r
drop drop drop ;
: str-table
create ( n -- ) 0 do , loop
does> ( n -- str len ) swap cells + @ count ;
here ," December"
here ," November"
here ," October"
here ," September"
here ," August"
here ," July"
here ," June"
here ," May"
here ," April"
here ," March"
here ," February"
here ," January"
12 str-table months
here ," Sunday"
here ," Saturday"
here ," Friday"
here ," Thursday"
here ," Wednesday"
here ," Tuesday"
here ," Monday"
7 str-table weekdays
\ Zeller's Congruence
: zeller ( m -- days since March 1 )
9 + 12 mod 1- 26 10 */ 3 + ;
: weekday ( d m y -- 0..6 ) \ Monday..Sunday
over 3 < if 1- then
dup 4 /
over 100 / -
over 400 / + +
swap zeller + +
1+ 7 mod ;
: 3dup dup 2over rot ;
: .long-date
time&date ( s m h D M Y )
3dup weekday weekdays type ." , "
>R 1- months type space 1 u.r ." , " R> .
drop drop drop ; |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #C.2B.2B | C++ | #include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>
class CSV
{
public:
CSV(void) : m_nCols( 0 ), m_nRows( 0 )
{}
bool open( const char* filename, char delim = ',' )
{
std::ifstream file( filename );
clear();
if ( file.is_open() )
{
open( file, delim );
return true;
}
return false;
}
void open( std::istream& istream, char delim = ',' )
{
std::string line;
clear();
while ( std::getline( istream, line ) )
{
unsigned int nCol = 0;
std::istringstream lineStream(line);
std::string cell;
while( std::getline( lineStream, cell, delim ) )
{
m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
nCol++;
}
m_nCols = std::max( m_nCols, nCol );
m_nRows++;
}
}
bool save( const char* pFile, char delim = ',' )
{
std::ofstream ofile( pFile );
if ( ofile.is_open() )
{
save( ofile );
return true;
}
return false;
}
void save( std::ostream& ostream, char delim = ',' )
{
for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
{
for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
{
ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
if ( (nCol+1) < m_nCols )
{
ostream << delim;
}
else
{
ostream << std::endl;
}
}
}
}
void clear()
{
m_oData.clear();
m_nRows = m_nCols = 0;
}
std::string& operator()( unsigned int nCol, unsigned int nRow )
{
m_nCols = std::max( m_nCols, nCol+1 );
m_nRows = std::max( m_nRows, nRow+1 );
return m_oData[std::make_pair(nCol, nRow)];
}
inline unsigned int GetRows() { return m_nRows; }
inline unsigned int GetCols() { return m_nCols; }
private:
// trim string for empty spaces in begining and at the end
inline std::string &trim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
private:
std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;
unsigned int m_nCols;
unsigned int m_nRows;
};
int main()
{
CSV oCSV;
oCSV.open( "test_in.csv" );
oCSV( 0, 0 ) = "Column0";
oCSV( 1, 1 ) = "100";
oCSV( 2, 2 ) = "200";
oCSV( 3, 3 ) = "300";
oCSV( 4, 4 ) = "400";
oCSV.save( "test_out.csv" );
return 0;
} |
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #Java | Java | public class DammAlgorithm {
private static final int[][] table = {
{0, 3, 1, 7, 5, 9, 8, 6, 4, 2},
{7, 0, 9, 2, 1, 5, 4, 8, 6, 3},
{4, 2, 0, 6, 8, 7, 1, 3, 5, 9},
{1, 7, 5, 0, 9, 8, 3, 4, 2, 6},
{6, 1, 2, 3, 0, 4, 5, 9, 7, 8},
{3, 6, 7, 4, 2, 0, 9, 5, 8, 1},
{5, 8, 6, 9, 7, 2, 0, 1, 3, 4},
{8, 9, 4, 5, 3, 6, 2, 0, 1, 7},
{9, 4, 3, 8, 6, 1, 7, 2, 0, 5},
{2, 5, 8, 1, 4, 3, 6, 7, 9, 0},
};
private static boolean damm(String s) {
int interim = 0;
for (char c : s.toCharArray()) interim = table[interim][c - '0'];
return interim == 0;
}
public static void main(String[] args) {
int[] numbers = {5724, 5727, 112946, 112949};
for (Integer number : numbers) {
boolean isValid = damm(number.toString());
if (isValid) {
System.out.printf("%6d is valid\n", number);
} else {
System.out.printf("%6d is invalid\n", number);
}
}
}
} |
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
| #Common_Lisp | Common Lisp | ;;; Show the first 200 and the 100,000th cuban prime.
;;; Cuban primes are the difference of 2 consecutive cubes.
(defun primep (n)
(cond ((< n 4) t)
((evenp n) nil)
((zerop (mod n 3)) nil)
(t (loop for i from 5 upto (isqrt n) by 6
when (or
(zerop (mod n i))
(zerop (mod n (+ i 2))))
return nil
finally (return t)))))
(defun cube (n) (* n n n))
(defun cuban (n)
(loop for i from 1
for j from 2
for cube-diff = (- (cube j) (cube i))
when (primep cube-diff)
collect cube-diff into cuban-primes
and count i into counter
when (= counter n)
return cuban-primes))
(format t "~a~%" "1st to 200th cuban prime numbers:")
(format t
"~{~<~%~,120:;~10:d ~>~}~%"
(cuban 200))
(format t "~%100,000th cuban prime number = ~:d"
(car (last (cuban 100000))))
(princ #\newline) |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #PicoLisp | PicoLisp | (out "/dev/tape"
(prin "Hello World!") ) |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Python | Python | >>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n')
...
>>> |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Racket | Racket |
#lang racket
(with-output-to-file "/dev/tape" #:exists 'append
(λ() (displayln "I am a cheap imitation of the Perl code for a boring problem")))
|
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Raku | Raku | my $tape = open "/dev/tape", :w or die "Can't open tape: $!";
$tape.say: "I am a tape file now, or hope to be soon.";
$tape.close; |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #REXX | REXX | /*REXX pgm demonstrates writing records to an attached magnetic tape.*/
dsName = 'TAPE.FILE' /*dsName of "file" being written.*/
do j=1 for 100 /*write 100 records to mag tape. */
call lineout dsName, 'this is record' j || "."
end /*j*/
/*stick a fork in it, we're done.*/ |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Ring | Ring |
# Project : Create a file on magnetic tape
fn = "Tape.file"
fp = fopen(fn,"w")
str = "I am a tape file now, or hope to be soon."
fwrite(fp, str)
fclose(fp)
|
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
| #Lua | Lua | C = setmetatable(require("bc"), {__call=function(t,...) return t.new(...) end})
C.digits(6) -- enough for .nn * .nnnn ==> .nnnnnn, follow with trunc(2) to trim trailing zeroes
subtot = (C"4000000000000000" * C"5.50" + C"2" * C"2.86"):trunc(2) -- cosmetic trunc
tax = (subtot * C"0.0765" + C"0.005"):trunc(2) -- rounding trunc
total = (subtot + tax):trunc(2) -- cosmetic trunc
print(("Before tax: %20s"):format(subtot:tostring()))
print(("Tax : %20s"):format(tax:tostring()))
print(("With tax : %20s"):format(total:tostring())) |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
| #M2000_Interpreter | M2000 Interpreter |
Module Currency_Task {
Locale 1033
Font "Courier New"
Form 80,32
\\Decimal type
hamburgers=4000000000000000@
\\ Currency type
hamburger_price=5.5#
milkshakes=2#
milkshake_price=2.86#
tax_rate=0.0765#
\\ Using Columns with variable width in console
PrHeadLine("Item","price","quantity", "value")
PrLine("hamburger",hamburger_price,hamburgers,hamburgers*hamburger_price)
PrLine("milkshake", milkshake_price,milkshakes,milkshakes*milkshake_price)
PrResults( "subtotal", hamburgers*hamburger_price+milkshakes*milkshake_price)
PrResults("tax", (hamburgers*hamburger_price+milkshakes*milkshake_price)*tax_rate)
\\ 1 is double by default we can use 1# or 1@
PrResults("total", (hamburgers*hamburger_price+milkshakes*milkshake_price)*(tax_rate+1))
\\ Using variables for partial calculations. They get type from expression result
h_p_q=hamburgers*hamburger_price
m_p_q=milkshakes*milkshake_price
\\ Using format$ to prepare final strings
Print format$("{0:15}{1:-8}{2:-25}{3:-25}","Item", "price", "quantity", "value")
Print format$("{0:15}{1:2:-8}{2:0:-25}{3:2:-25}","hamburger",hamburger_price,hamburgers, h_p_q)
Print format$("{0:15}{1:2:-8}{2:0:-25}{3:2:-25}","milkshake", milkshake_price,milkshakes,m_p_q)
Print format$("{0:-48}{1:2:-25}","subtotal", h_p_q+m_p_q)
Print format$("{0:-48}{1:2:-25}","tax", (h_p_q+m_p_q)*tax_rate)
Print format$("{0:-48}{1:2:-25}","total", (h_p_q+m_p_q)*(tax_rate+1))
\\ Another time to feed Document to export to clipboard
Document Doc$=format$("{0:15}{1:-8}{2:-25}{3:-25}","Item", "price", "quantity", "value")+{
}+format$("{0:15}{1:2:-8}{2:0:-25}{3:2:-25}","hamburger",hamburger_price,hamburgers, h_p_q)+{
}+format$("{0:15}{1:2:-8}{2:0:-25}{3:2:-25}","milkshake", milkshake_price,milkshakes,m_p_q)+{
}+format$("{0:-48}{1:2:-25}","subtotal", h_p_q+m_p_q)+{
}+format$("{0:-48}{1:2:-25}","tax", (h_p_q+m_p_q)*tax_rate)+{
}+format$("{0:-48}{1:2:-25}","total", (h_p_q+m_p_q)*(tax_rate+1))+{
}
clipboard Doc$
\\ one line user function definition
\\ x get type from passed value
Def ExpressionType$(x)=Type$(X)
\\ Check Expression final type
Print ExpressionType$(hamburgers)="Decimal"
Print ExpressionType$(milkshakes)="Currency"
Print ExpressionType$(h_p_q)="Decimal"
Print ExpressionType$(m_p_q)="Currency"
Print ExpressionType$((h_p_q+m_p_q)*tax_rate)="Decimal"
Print ExpressionType$((h_p_q+m_p_q)*(tax_rate+1))="Decimal"
Sub PrHeadLine(a$,b$,c$,d$)
Print Part $(1,15),a$,$(3,8),b$, $(3,25),c$, $(3,25),d$
Print
End Sub
Sub PrLine(a$,b,c,d)
Print Part $(1,15),a$,$("0.00"),$(3,8),b, $("0"),$(3,25),c,$("0.00"), $(3,25),d
Print
End Sub
Sub PrResults(a$,b)
Print Part $(3,48),a$,$("0.00"),$(3,25),b
Print
End Sub
}
Currency_Task
|
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
| #JavaScript | JavaScript | function addN(n) {
var curry = function(x) {
return x + n;
};
return curry;
}
add2 = addN(2);
alert(add2);
alert(add2(7)); |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
| #jq | jq |
def plus(x): . + x;
def plus5: plus(5);
|
http://rosettacode.org/wiki/Create_an_object_at_a_given_address | Create an object at a given address |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #Wren | Wren | /* create_object_at_given_address.wren */
import "./fmt" for Fmt
foreign class Integer {
construct new(i) {}
foreign value
foreign value=(i)
foreign address
}
var i = Integer.new(42)
Fmt.print("Integer object with value of: $d allocated at address $#x.", i.value, i.address)
i.value = 42
Fmt.print("Integer object value reset to: $d but still at address $#x.", i.value, i.address)
i.value = 43
Fmt.print("Integer object value changed to: $d but still at address $#x.", i.value, i.address) |
http://rosettacode.org/wiki/Create_an_object_at_a_given_address | Create an object at a given address |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc.
Task
Show how language objects can be allocated at a specific machine addresses.
Since most OSes prohibit access to the physical memory if it is not mapped by the application, as an example, rather than a physical address, take the address of some existing object (using suitable address operations if necessary).
For example:
create an integer object
print the machine address of the object
take the address of the object and create another integer object at this address
print the value of this object to verify that it is same as one of the origin
change the value of the origin and verify it again
| #Z80_Assembly | Z80 Assembly | LD HL,&FFFF
LD (&C000),HL |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #mIRC_Scripting_Language | mIRC Scripting Language | echo -ag $asctime($calc($ctime(March 7 2009 7:30pm EST)+43200)) |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
import java.text.SimpleDateFormat
import java.text.ParseException
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method manipulateDate(sampleDate, dateFmt, dHours = 0) private static
formatter = SimpleDateFormat(dateFmt)
msHours = dHours * 60 * 60 * 1000 -- hours in milliseconds
day = formatter.parse(sampleDate)
day.setTime(day.getTime() + msHours)
formatted = formatter.format(day)
return formatted
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
do
sampleDate = 'March 7 2009 7:30pm EST'
dateFmt = "MMMM d yyyy h:mma z"
say sampleDate
say manipulateDate(sampleDate, dateFmt, 12)
catch ex = Exception
ex.printStackTrace()
end
return
|
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #Groovy | Groovy | def yuletide = { start, stop -> (start..stop).findAll { Date.parse("yyyy-MM-dd", "${it}-12-25").format("EEE") == "Sun" } } |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #Haskell | Haskell | import Data.Time (fromGregorian)
import Data.Time.Calendar.WeekDate (toWeekDate)
--------------------- DAY OF THE WEEK --------------------
isXmasSunday :: Integer -> Bool
isXmasSunday year = 7 == weekDay
where
(_, _, weekDay) = toWeekDate $ fromGregorian year 12 25
--------------------------- TEST -------------------------
main :: IO ()
main =
mapM_
putStrLn
[ "Sunday 25 December " <> show year
| year <- [2008 .. 2121],
isXmasSunday year
] |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #langur | langur | val .isCusip = f(.s) {
if not isString(.s) or len(.s) != 9 {
return false
}
val .basechars = cp2s('0'..'9') ~ cp2s('A'..'Z') ~ "*@#"
val .sum = for[=0] .i of 8 {
var .v = index(s2s(.s, .i), .basechars)
if not .v: return false
.v = .v[1]-1
if .i div 2: .v x= 2
_for += .v \ 10 + .v rem 10
}
.s[9]-'0' == (10-(.sum rem 10)) rem 10
}
val .candidates = w/037833100 17275R102 38259P508 594918104 68389X106 68389X105/
for .c in .candidates {
writeln .c, ": ", if(.isCusip(.c): "good" ; "bad")
} |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #Lua | Lua | function checkDigit (cusip)
if #cusip ~= 8 then return false end
local sum, c, v, p = 0
for i = 1, 8 do
c = cusip:sub(i, i)
if c:match("%d") then
v = tonumber(c)
elseif c:match("%a") then
p = string.byte(c) - 55
v = p + 9
elseif c == "*" then
v = 36
elseif c == "@" then
v = 37
elseif c == "#" then
v = 38
end
if i % 2 == 0 then
v = v * 2
end
sum = sum + math.floor(v / 10) + v % 10
end
return tostring((10 - (sum % 10)) % 10)
end
local testCases = {
"037833100",
"17275R102",
"38259P508",
"594918104",
"68389X106",
"68389X105"
}
for _, CUSIP in pairs(testCases) do
io.write(CUSIP .. ": ")
if checkDigit(CUSIP:sub(1, 8)) == CUSIP:sub(9, 9) then
print("VALID")
else
print("INVALID")
end
end |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #11l | 11l | V width = 3
V height = 5
V myarray = [[0] * width] * height
print(myarray[height-1][width-1]) |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Clojure | Clojure |
(defn stateful-std-deviation[x]
(letfn [(std-dev[x]
(let [v (deref (find-var (symbol (str *ns* "/v"))))]
(swap! v conj x)
(let [m (/ (reduce + @v) (count @v))]
(Math/sqrt (/ (reduce + (map #(* (- m %) (- m %)) @v)) (count @v))))))]
(when (nil? (resolve 'v))
(intern *ns* 'v (atom [])))
(std-dev x)))
|
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC.
For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string:
The quick brown fox jumps over the lazy dog
| #11l | 11l | V crc_table = [0] * 256
L(i) 256
UInt32 rem = i
L 8
I rem [&] 1 != 0
rem >>= 1
rem (+)= EDB8'8320
E
rem >>= 1
crc_table[i] = rem
F crc32(buf, =crc = UInt32(0))
crc = (-)crc
L(k) buf
crc = (crc >> 8) (+) :crc_table[(crc [&] F'F) (+) k.code]
R (-)crc
print(hex(crc32(‘The quick brown fox jumps over the lazy dog’))) |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Fortran | Fortran | PROGRAM DATE
IMPLICIT NONE
INTEGER :: dateinfo(8), day
CHARACTER(9) :: month, dayname
CALL DATE_AND_TIME(VALUES=dateinfo)
SELECT CASE(dateinfo(2))
CASE(1)
month = "January"
CASE(2)
month = "February"
CASE(3)
month = "March"
CASE(4)
month = "April"
CASE(5)
month = "May"
CASE(6)
month = "June"
CASE(7)
month = "July"
CASE(8)
month = "August"
CASE(9)
month = "September"
CASE(10)
month = "October"
CASE(11)
month = "November"
CASE(12)
month = "December"
END SELECT
day = Day_of_week(dateinfo(3), dateinfo(2), dateinfo(1))
SELECT CASE(day)
CASE(0)
dayname = "Saturday"
CASE(1)
dayname = "Sunday"
CASE(2)
dayname = "Monday"
CASE(3)
dayname = "Tuesday"
CASE(4)
dayname = "Wednesday"
CASE(5)
dayname = "Thursday"
CASE(6)
dayname = "Friday"
END SELECT
WRITE(*,"(I0,A,I0,A,I0)") dateinfo(1),"-", dateinfo(2),"-", dateinfo(3)
WRITE(*,"(4(A),I0,A,I0)") trim(dayname), ", ", trim(month), " ", dateinfo(3), ", ", dateinfo(1)
CONTAINS
FUNCTION Day_of_week(d, m, y)
INTEGER :: Day_of_week, j, k
INTEGER, INTENT(IN) :: d, m, y
j = y / 100
k = MOD(y, 100)
Day_of_week = MOD(d + (m+1)*26/10 + k + k/4 + j/4 + 5*j, 7)
END FUNCTION Day_of_week
END PROGRAM DATE |
http://rosettacode.org/wiki/CSV_data_manipulation | CSV data manipulation | CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.
The CSV format is flexible but somewhat ill-defined.
For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.
Task
Read a CSV file, change some values and save the changes back to a file.
For this task we will use the following CSV file:
C1,C2,C3,C4,C5
1,5,9,13,17
2,6,10,14,18
3,7,11,15,19
4,8,12,16,20
Suggestions
Show how to add a column, headed 'SUM', of the sums of the rows.
If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.
| #Clojure | Clojure |
(require '[clojure.data.csv :as csv]
'[clojure.java.io :as io])
(defn add-sum-column [coll]
(let [titles (first coll)
values (rest coll)]
(cons (conj titles "SUM")
(map #(conj % (reduce + (map read-string %))) values))))
(with-open [in-file (io/reader "test_in.csv")]
(doall
(let [out-data (add-sum-column (csv/read-csv in-file))]
(with-open [out-file (io/writer "test_out.csv")]
(csv/write-csv out-file out-data)))))
|
http://rosettacode.org/wiki/Damm_algorithm | Damm algorithm | The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.
The algorithm is named after H. Michael Damm.
Task
Verify the checksum, stored as last digit of an input.
| #JavaScript | JavaScript | const table = [
[0, 3, 1, 7, 5, 9, 8, 6, 4, 2],
[7, 0, 9, 2, 1, 5, 4, 8, 6, 3],
[4, 2, 0, 6, 8, 7, 1, 3, 5, 9],
[1, 7, 5, 0, 9, 8, 3, 4, 2, 6],
[6, 1, 2, 3, 0, 4, 5, 9, 7, 8],
[3, 6, 7, 4, 2, 0, 9, 5, 8, 1],
[5, 8, 6, 9, 7, 2, 0, 1, 3, 4],
[8, 9, 4, 5, 3, 6, 2, 0, 1, 7],
[9, 4, 3, 8, 6, 1, 7, 2, 0, 5],
[2, 5, 8, 1, 4, 3, 6, 7, 9, 0],
];
const lookup = (p, c) => table[p][parseInt(c, 10)]
const damm = input => [...input].reduce(lookup, 0) === 0;
// ----------------------------------------------------------[ Tests ]----
const test = () => ["5724", "5727", "112946", "112949"].forEach(e =>
console.log(`${e} => ${damm(e) ? 'Pass' : 'Fail'}`)
);
test();
|
http://rosettacode.org/wiki/Cuban_primes | Cuban primes | The name cuban has nothing to do with Cuba (the country), but has to do with the
fact that cubes (3rd powers) play a role in its definition.
Some definitions of cuban primes
primes which are the difference of two consecutive cubes.
primes of the form: (n+1)3 - n3.
primes of the form: n3 - (n-1)3.
primes p such that n2(p+n) is a cube for some n>0.
primes p such that 4p = 1 + 3n2.
Cuban primes were named in 1923 by Allan Joseph Champneys Cunningham.
Task requirements
show the first 200 cuban primes (in a multi─line horizontal format).
show the 100,000th cuban prime.
show all cuban primes with commas (if appropriate).
show all output here.
Note that cuban prime isn't capitalized (as it doesn't refer to the nation of Cuba).
Also see
Wikipedia entry: cuban prime.
MathWorld entry: cuban prime.
The OEIS entry: A002407. The 100,000th cuban prime can be verified in the 2nd example on this OEIS web page.
| #D | D | import std.math;
import std.stdio;
void main() {
long[] primes = [3, 5];
immutable cutOff = 200;
immutable bigUn = 100_000;
immutable chunks = 50;
immutable little = bigUn / chunks;
immutable tn = " cuban prime";
writefln("The first %s%ss:", cutOff, tn);
int c;
bool showEach = true;
long u;
long v = 1;
for (long i = 1; i > 0; ++i) {
bool found;
u += 6;
v += u;
int mx = cast(int)ceil(sqrt(cast(real)v));
foreach (item; primes) {
if (item > mx) break;
if (v % item == 0) {
found = true;
break;
}
}
if (!found) {
c++;
if (showEach) {
for (auto z = primes[$-1] + 2; z <= v - 2; z += 2) {
bool fnd;
foreach (item; primes) {
if (item > mx) break;
if (z % item == 0) {
fnd = true;
break;
}
}
if (!fnd) {
primes ~= z;
}
}
primes ~= v;
writef("%11d", v);
if (c % 10 == 0) writeln;
if (c == cutOff) {
showEach = false;
writef("\nProgress to the %sth%s: ", bigUn, tn);
}
}
if (c % little == 0) {
write('.');
if (c == bigUn) {
break;
}
}
}
}
writefln("\nThe %sth%s is %17s", c, tn, v);
} |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Ruby | Ruby | File.open("tape.file", "w") do |fh|
fh.syswrite("This code should be able to write a file to magnetic tape.\n")
end |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Rust | Rust | use std::io::Write;
use std::fs::File;
fn main() -> std::io::Result<()> {
File::open("/dev/tape")?.write_all(b"Hello from Rosetta Code!")
} |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Scala | Scala | object LinePrinter extends App {
import java.io.{ FileWriter, IOException }
{
val lp0 = new FileWriter("/dev/tape")
lp0.write("Hello, world!")
lp0.close()
}
} |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
var file: tapeFile is STD_NULL;
begin
tapeFile := open("/dev/tape", "w");
if tapeFile = STD_NULL then
tapeFile := open("tape.file", "w");
end if;
if tapeFile <> STD_NULL then
writeln(tapeFile, "Hello, world!");
close(tapeFile);
else
writeln(" ***** Cannot open tape file.");
end if;
end func; |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #Tcl | Tcl | cd /tmp
# Create the file
set f [open hello.jnk w]
puts $f "Hello World!"
close $f
# Archive to tape
set fin [open "|tar cf - hello.jnk" rb]
set fout [open /dev/tape wb]
fcopy $fin $fout
close $fin
close $fout |
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape | Create a file on magnetic tape | The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
| #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
STATUS = CREATE ("tape.file",tape-o,-std-)
PRINT STATUS |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
| #Maple | Maple |
Digits := 50;
tax := .0765;
burgersquantity := 4000000000000000;
burgersprice := 5.50;
burgerscost := burgersquantity * burgersprice;
milkshakesquantity := 2;
milkshakesprice := 2.86;
milkshakescost := milkshakesquantity * milkshakesprice;
total := burgerscost + milkshakescost;
printf("%.2f\n",total);
totaltax := total * tax;
printf("%.2f\n",totaltax);
totalprice := totaltax + total;
printf("%.2f\n",totalprice);
|
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | total = 4000000000000000 Rationalize[5.50] + 2 Rationalize[2.86];
AccountingForm[N[total, 20], {\[Infinity], 2}]
tax = total Rationalize[0.0765];
AccountingForm[N[tax, 20], {\[Infinity], 2}]
AccountingForm[N[total + tax, 20], {\[Infinity], 2}] |
http://rosettacode.org/wiki/Currency | Currency | Task
Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.
Note
The IEEE 754 binary floating point representations of numbers like 2.86 and .0765 are not exact.
For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.
Use the values:
4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)
2 milkshakes at $2.86 each, and
a tax rate of 7.65%.
(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naïve task solutions using 64 bit floating point types.)
Compute and output (show results on this page):
the total price before tax
the tax
the total with tax
The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.
The output must show dollars and cents with a decimal point.
The three results displayed should be:
22000000000000005.72
1683000000000000.44
23683000000000006.16
Dollar signs and thousands separators are optional.
| #Nim | Nim | import strutils
import bignum
type Currency = Int
#---------------------------------------------------------------------------------------------------
func currency(units, subunits: int): Currency =
## Build a currency from units and subunits.
## Units may be negative. Subunits must be in range 0..99.
if subunits notin 0..99:
raise newException(ValueError, "wrong value for subunits")
result = if units >= 0: newInt(units * 100 + subunits)
else: newInt(subunits * 100 - subunits)
#---------------------------------------------------------------------------------------------------
func currency(value: string): Currency =
## Build a currency from a string.
## Negative values are allowed. At most two digits are allowed for subunits.
const StartingChars = Digits + {'-'}
if value.len == 0 or value[0] notin StartingChars:
raise newException(ValueError, "wrong currency string")
# process sign and units.
var units = newInt(0)
var subunits = 0
let sign = if value[0] == '-': -1 else: 1
var idx = if sign == 1: 0 else: 1
while idx < value.len:
if value[idx] notin Digits: break
units = 10 * units + ord(value[idx]) - ord('0')
inc idx
# Process separator.
if idx <= value.high:
if value[idx] != '.':
raise newException(ValueError, "expected a separator")
inc idx
# Process subunits.
for _ in 0..1:
let c = if idx >= value.len: '0' else: value[idx]
if c notin Digits:
raise newException(ValueError, "wrong value for subunits")
subunits = 10 * subunits + ord(c) - ord('0')
inc idx
if idx <= value.high:
raise newException(ValueError, "extra characters after subunits digits")
result = sign * (units * 100 + subunits)
#---------------------------------------------------------------------------------------------------
func `//`(a, b: int): Rat =
## Create a rational value.
newRat(a, b)
#---------------------------------------------------------------------------------------------------
func percentage(a: Currency; p: Rat): Currency =
## Compute a percentage on currency value "a".
## Returned value is rounded to nearest integer.
(a * p.num * 10 div p.denom + 5) div 10
#---------------------------------------------------------------------------------------------------
func `$`(a: Currency): string =
## Build a string representation of a currency value.
result = bignum.`$`(a div 100) & '.' & ($(a mod 100).toInt).align(2, '0')
#———————————————————————————————————————————————————————————————————————————————————————————————————
let hamburgers = currency(5, 50) * int 4_000_000_000_000_000
let milkshakes = currency("2.86") * 2
let rate = 765 // 10_000
let beforeTax = hamburgers + milkshakes
let tax = beforeTax.percentage(rate)
let total = beforeTax + tax
# Find the maximum length of numerical value representations.
let beforeTaxStr = $beforeTax
let taxStr = $tax
let totalStr = $total
let length = max([beforeTaxStr.len, taxStr.len, totalStr.len])
# Display the results.
echo "Total price before tax: ", beforeTaxStr.align(length)
echo "Tax: ", taxStr.align(length)
echo "Total with tax: ", totalStr.align(length) |
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
| #Julia | Julia |
function addN(n::Number)::Function
adder(x::Number) = n + x
return adder
end
|
http://rosettacode.org/wiki/Currying | Currying |
This page uses content from Wikipedia. The original article was at Currying. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Create a simple demonstrative example of Currying in a specific language.
Add any historic details as to how the feature made its way into the language.
| #Kotlin | Kotlin | // version 1.1.2
fun curriedAdd(x: Int) = { y: Int -> x + y }
fun main(args: Array<String>) {
val a = 2
val b = 3
val sum = curriedAdd(a)(b)
println("$a + $b = $sum")
} |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #Nim | Nim | import times
const Date = "March 7 2009 7:30pm EST"
echo "Original date is: ", Date
var dt = Date.replace("EST", "-05:00").parse("MMMM d yyyy h:mmtt zzz")
echo "Original date in UTC is: ", dt.utc().format("MMMM d yyyy h:mmtt zzz")
dt = dt + initDuration(hours = 12)
echo "Date 12 hours later is: ", dt.utc().format("MMMM d yyyy h:mmtt zzz") |
http://rosettacode.org/wiki/Date_manipulation | Date manipulation | Task
Given the date string "March 7 2009 7:30pm EST",
output the time 12 hours later in any human-readable format.
As extra credit, display the resulting time in a time zone different from your own.
| #ooRexx | ooRexx |
sampleDate = 'March 7 2009 7:30pm EST'
Parse var sampleDate month day year time zone
basedate = .DateTime~fromNormalDate(day month~left(3) year)
basetime = .DateTime~fromCivilTime(time)
-- this will give us this in a merged format...now we can add in the
-- timezone informat
mergedTime = (basedate + basetime~timeofday)~isoDate
zone = .TimeZoneDataBase~getTimeZone(zone)
finalTime = .DateTime~fromIsoDate(mergedTime, zone~datetimeOffset)
say 'Original date:' finalTime~utcIsoDate
say 'Result after adding 12 hours:' finalTime~addHours(12)~utcIsoDate
say 'Result shifted to UTC:' finalTime~toTimeZone(0)~utcIsoDate
say 'Result shifted to Pacific Standard Time:' finalTime~toTimeZone(.TimeZoneDataBase~getTimeZone('PST')~datetimeOffset)~utcIsoDate
say 'Result shifted to NepalTime Time:' finalTime~toTimeZone(.TimeZoneDataBase~getTimeZone('NPT')~datetimeOffset)~utcIsoDate
-- a descriptor for timezone information
::class timezone
::method init
expose code name offset altname region
use strict arg code, name, offset, altname, region
code~upper
::attribute code GET
::attribute name GET
::attribute offset GET
::attribute altname GET
::attribute region GET
::attribute datetimeOffset GET
expose offset
return offset * 60
-- our database of timezones
::class timezonedatabase
-- initialize the class object. This occurs when the program is first loaded
::method init class
expose timezones
timezones = .directory~new
-- extract the timezone data which is conveniently stored in a method
data = self~instanceMethod('TIMEZONEDATA')~source
loop line over data
-- skip over the comment delimiters, blank lines, and the 'return'
-- lines that force the comments to be included in the source
if line = '/*' | line = '*/' | line = '' | line = 'return' then iterate
parse var line '{' region '}'
if region \= '' then do
zregion = region
iterate
end
else do
parse var line abbrev . '!' fullname '!' altname . '!' offset .
timezone = .timezone~new(abbrev, fullname, offset, altname, zregion)
timezones[timezone~code] = timezone
end
end
::method getTimezone class
expose timezones
use strict arg code
return timezones[code~upper]
-- this is a dummy method containing the timezone database data.
-- we'll access the source directly and extract the data held in comments
-- the two return statements force the comment lines to be included in the
-- source rather than processed as part of comments between directives
::method timeZoneData class private
return
/*
{Universal}
UTC ! Coordinated Universal Time ! ! 0
{Europe}
BST ! British Summer Time ! ! +1
CEST ! Central European Summer Time ! ! +2
CET ! Central European Time ! ! +1
EEST ! Eastern European Summer Time ! ! +3
EET ! Eastern European Time ! ! +2
GMT ! Greenwich Mean Time ! ! 0
IST ! Irish Standard Time ! ! +1
KUYT ! Kuybyshev Time ! ! +4
MSD ! Moscow Daylight Time ! ! +4
MSK ! Moscow Standard Time ! ! +3
SAMT ! Samara Time ! ! +4
WEST ! Western European Summer Time ! ! +1
WET ! Western European Time ! ! 0
{North America}
ADT ! Atlantic Daylight Time ! HAA ! -3
AKDT ! Alaska Daylight Time ! HAY ! -8
AKST ! Alaska Standard Time ! HNY ! -9
AST ! Atlantic Standard Time ! HNA ! -4
CDT ! Central Daylight Time ! HAC ! -5
CST ! Central Standard Time ! HNC ! -6
EDT ! Eastern Daylight Time ! HAE ! -4
EGST ! Eastern Greenland Summer Time ! ! 0
EGT ! East Greenland Time ! ! -1
EST ! Eastern Standard Time ! HNE,ET ! -5
HADT ! Hawaii-Aleutian Daylight Time ! ! -9
HAST ! Hawaii-Aleutian Standard Time ! ! -10
MDT ! Mountain Daylight Time ! HAR ! -6
MST ! Mountain Standard Time ! HNR ! -7
NDT ! Newfoundland Daylight Time ! HAT ! -2.5
NST ! Newfoundland Standard Time ! HNT ! -3.5
PDT ! Pacific Daylight Time ! HAP ! -7
PMDT ! Pierre & Miquelon Daylight Time ! ! -2
PMST ! Pierre & Miquelon Standard Time ! ! -3
PST ! Pacific Standard Time ! HNP,PT ! -8
WGST ! Western Greenland Summer Time ! ! -2
WGT ! West Greenland Time ! ! -3
{India and Indian Ocean}
IST ! India Standard Time ! ! +5.5
PKT ! Pakistan Standard Time ! ! +5
BST ! Bangladesh Standard Time ! ! +6 -- Note: collision with British Summer Time
NPT ! Nepal Time ! ! +5.75
BTT ! Bhutan Time ! ! +6
BIOT ! British Indian Ocean Territory Time ! IOT ! +6
MVT ! Maldives Time ! ! +5
CCT ! Cocos Islands Time ! ! +6.5
TFT ! French Southern and Antarctic Time ! ! +5
*/
return
|
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #HicEst | HicEst | DO year = 1, 1000000
TIME(Year=year, MOnth=12, Day=25, TO, WeekDay=weekday)
IF( weekday == 7) WRITE(StatusBar) year
ENDDO
END |
http://rosettacode.org/wiki/Day_of_the_week | Day of the week | A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January).
Task
In what years between 2008 and 2121 will the 25th of December be a Sunday?
Using any standard date handling libraries of your programming language;
compare the dates calculated with the output of other languages to discover any anomalies in the handling of dates which may be due to, for example, overflow in types used to represent dates/times similar to y2k type problems.
| #Icon_and_Unicon | Icon and Unicon | link datetime
procedure main()
writes("December 25th is a Sunday in: ")
every writes((dayoweek(25,12,y := 2008 to 2122)=="Sunday",y)," ")
end |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[Cusip]
rules = Thread[(ToString /@ Range[0, 9]) -> Range[0, 9]]~Join~
Thread[CharacterRange["A", "Z"] -> Range[26] + 9]~Join~
Thread[Characters["*@#"] -> {36, 37, 38}];
Cusip[cusip_String] := Module[{s = cusip, sum = 0, c, value, check},
If[StringLength[s] != 9,
Print["Cusip must be 9 characters!"];
False
,
s = Characters[ToUpperCase[s]];
Do[
c = s[[i]];
value = c /. rules;
If[EvenQ[i], value *= 2];
sum += Floor[value/10] + Mod[value, 10];
,
{i, 8}
];
check = Mod[(10 - Mod[sum, 10]), 10];
s[[-1]] === ToString[check]
]
]
Cusip /@ {"037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105"} |
http://rosettacode.org/wiki/CUSIP | CUSIP |
This page uses content from Wikipedia. The original article was at CUSIP. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
A CUSIP is a nine-character alphanumeric code that identifies a North American financial security for the purposes of facilitating clearing and settlement of trades. The CUSIP was adopted as an American National Standard under Accredited Standards X9.6.
Task
Ensure the last digit (i.e., the check digit) of the CUSIP code (the 1st column) is correct, against the following:
037833100 Apple Incorporated
17275R102 Cisco Systems
38259P508 Google Incorporated
594918104 Microsoft Corporation
68389X106 Oracle Corporation (incorrect)
68389X105 Oracle Corporation
Example pseudo-code below.
algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
sum := 0
for 1 ≤ i ≤ 8 do
c := the ith character of cusip
if c is a digit then
v := numeric value of the digit c
else if c is a letter then
p := ordinal position of c in the alphabet (A=1, B=2...)
v := p + 9
else if c = "*" then
v := 36
else if c = "@" then
v := 37
else if' c = "#" then
v := 38
end if
if i is even then
v := v × 2
end if
sum := sum + int ( v div 10 ) + v mod 10
repeat
return (10 - (sum mod 10)) mod 10
end function
See related tasks
SEDOL
ISIN
| #Modula-2 | Modula-2 | MODULE CUSIP;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE WriteInt(n : INTEGER);
VAR buf : ARRAY[0..10] OF CHAR;
BEGIN
FormatString("%i", buf, n);
WriteString(buf)
END WriteInt;
PROCEDURE cusipCheckDigit(cusip : ARRAY OF CHAR) : INTEGER;
VAR
i,v,sum : INTEGER;
BEGIN
i := 0;
sum := 0;
WHILE cusip[i] # 0C DO
IF ('0' <= cusip[i]) AND (cusip[i] <= '9') THEN
v := ORD(cusip[i]) - 48 (* 0 *)
ELSIF ('A' <= cusip[i]) AND (cusip[i] <= 'Z') THEN
v := ORD(cusip[i]) - 65 (* A *) + 10
ELSIF cusip[i] = '*' THEN
v := 36
ELSIF cusip[i] = '@' THEN
v := 37
ELSIF cusip[i] = '#' THEN
v := 38
ELSE
RETURN -1
END;
IF i MOD 2 = 1 THEN v := 2 * v END;
IF i < 8 THEN
sum := sum + (v DIV 10) + (v MOD 10);
END;
INC(i)
END;
IF i # 9 THEN RETURN -1 END;
RETURN (10 - (sum MOD 10)) MOD 10
END cusipCheckDigit;
PROCEDURE isValidCusip(cusip : ARRAY OF CHAR) : BOOLEAN;
VAR
check : INTEGER;
BEGIN
check := cusipCheckDigit(cusip);
IF check < 0 THEN RETURN FALSE END;
RETURN cusip[8] = CHR(48 (* 0 *) + check)
END isValidCusip;
PROCEDURE Print(cusip : ARRAY OF CHAR);
BEGIN
WriteString(cusip);
IF isValidCusip(cusip) THEN
WriteString(" : Valid")
ELSE
WriteString(" : Invalid")
END;
WriteLn
END Print;
(* main *)
BEGIN
WriteString("CUSIP Verdict");
WriteLn;
Print("037833100");
Print("17275R102");
Print("38259P508");
Print("594918104");
Print("68389X106");
Print("68389X105");
ReadChar
END CUSIP. |
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime | Create a two-dimensional array at runtime |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.
| #68000_Assembly | 68000 Assembly | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Array setup
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Create_2D_Array:
ARRAY_2D equ $100000
ARRAY_POINTER_VARIABLE equ $200000
; input: D0 = width, D1 = height
; assume the input is byte length and unsigned, ranging from 1 to FF.
AND.L #$000000FF,D0
AND.L #$000000FF,D1 ;sanitize the input to byte length.
LEA ARRAY_2D,A0 ;get base array address.
;The array's size will be measured in bytes, as this is how memory offsetting is measured.
;For this example the elements will all be 32-bit.
;Therefore, the dimensions need to be multiplied by the byte count of each element.
LSL.W #2,D0 ;four bytes per element = multiply by 4
LSL.W #2,D1
;Next, these values are multiplied to get the array's size.
MOVE.L D0,D2
MULU D1,D2
;D2 is the array's size (measured in bytes) and will be placed at the beginning.
;This does not count as an element of the array for the purposes of row/column indexing.
;The array's base address will be offset by 4 bytes prior to any indexing.
MOVE.L D2,(A0)+ ;store D2 in A0, add 4 to A0
MOVEA.L A0,[ARRAY_POINTER_VARIABLE]
;the brackets are optional, they show that this is a memory address label.
;this is still a move to a memory address with or without the brackets.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Storing a value in the array
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
LEA ARRAY_POINTER_VARIABLE,A1 ;load the address where the array's base address is stored.
MOVE.L (A1),A1 ;dereference the pointer and get ARRAY_2D+4 into A1.
; for this example the arbitrary row/column indices (2,5) will be used.
MOVE.L #2,D4
MULU D0,D4 ;there are D0 entries per row, multiply row index by elements per row.
MOVE.L #5,D5
MOVE.L #$00112233,D7 ;determine the value we want to store in the array.
; The bytes per element was factored into D0 when the array was created. So D4 is already where it should be.
LSL.L #2,D5 ;column index still needs to be scaled by the bytes per element.
LEA (A1,D4),A1 ;select the desired row.
;68000 doesn't allow you to use more than 1 data register at a time to offset. So we have to offset separately.
;Despite the use of parentheses this is NOT a dereference like it would be with "MOVE.L (A1),D7". D4 is merely added to the address in A1.
MOVE.L D7,(A1,D5) ;store #$00112233 in row 2, column 5 of the array.
;Loading a value is the same as storing it, except the operands in the last instruction are reversed, and MOVE.L #$00112233,D7
;is omitted.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Destroying the array
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; The array is destroyed by storing something else in its location. If you really want to reset it to zero, you can
; do so with the following:
LEA ARRAY_POINTER_VARIABLE,A1
MOVE.L (A1),A1
MOVE.L -(A1),D7
;get the array size into D7. Remember that the array's size was stored just before its data.
This value is potentially too large for a single DBRA, but it can be split up.
SWAP D7
MOVE.W D7,D6 ;get the top half of D7 into D6. D6 will be the outer loop's DBRA value.
SWAP D7
SUBQ.L #1,D7 ;D7 needs to be decremented by 1. D6 is fine the way it is.
MOVE.L (A0)+,D0 ;dummy move to increment the pointer back to the array base.
MOVEQ #0,D0 ;faster than MOVE.L #0,D0
loop_destroyArray:
MOVE.L D0,(A0)+
DBRA D7,loop_destroyArray ;loop using bottom 2 bytes of the array size as a loop counter
DBRA D6,loop_destroyArray ;decrement this, D7 is $FFFF each time execution gets here so this acts as a "carry" of sorts.
;if this value was 0 prior to the loop, the loop ends immediately. |
http://rosettacode.org/wiki/Cumulative_standard_deviation | Cumulative standard deviation | Task[edit]
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.
The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used.
Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Test case
Use this to compute the standard deviation of this demonstration set,
{
2
,
4
,
4
,
4
,
5
,
5
,
7
,
9
}
{\displaystyle \{2,4,4,4,5,5,7,9\}}
, which is
2
{\displaystyle 2}
.
Related tasks
Random numbers
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. run-stddev.
environment division.
input-output section.
file-control.
select input-file assign to "input.txt"
organization is line sequential.
data division.
file section.
fd input-file.
01 inp-record.
03 inp-fld pic 9(03).
working-storage section.
01 filler pic 9(01) value 0.
88 no-more-input value 1.
01 ws-tb-data.
03 ws-tb-size pic 9(03).
03 ws-tb-table.
05 ws-tb-fld pic s9(05)v9999 comp-3 occurs 0 to 100 times
depending on ws-tb-size.
01 ws-stddev pic s9(05)v9999 comp-3.
PROCEDURE DIVISION.
move 0 to ws-tb-size
open input input-file
read input-file
at end
set no-more-input to true
end-read
perform
test after
until no-more-input
add 1 to ws-tb-size
move inp-fld to ws-tb-fld (ws-tb-size)
call 'stddev' using by reference ws-tb-data
ws-stddev
display 'inp=' inp-fld ' stddev=' ws-stddev
read input-file at end set no-more-input to true end-read
end-perform
close input-file
stop run.
end program run-stddev.
IDENTIFICATION DIVISION.
PROGRAM-ID. stddev.
data division.
working-storage section.
01 ws-tbx pic s9(03) comp.
01 ws-tb-work.
03 ws-sum pic s9(05)v9999 comp-3 value +0.
03 ws-sumsq pic s9(05)v9999 comp-3 value +0.
03 ws-avg pic s9(05)v9999 comp-3 value +0.
linkage section.
01 ws-tb-data.
03 ws-tb-size pic 9(03).
03 ws-tb-table.
05 ws-tb-fld pic s9(05)v9999 comp-3 occurs 0 to 100 times
depending on ws-tb-size.
01 ws-stddev pic s9(05)v9999 comp-3.
PROCEDURE DIVISION using ws-tb-data ws-stddev.
compute ws-sum = 0
perform test before varying ws-tbx from 1 by +1 until ws-tbx > ws-tb-size
compute ws-sum = ws-sum + ws-tb-fld (ws-tbx)
end-perform
compute ws-avg rounded = ws-sum / ws-tb-size
compute ws-sumsq = 0
perform test before varying ws-tbx from 1 by +1 until ws-tbx > ws-tb-size
compute ws-sumsq = ws-sumsq
+ (ws-tb-fld (ws-tbx) - ws-avg) ** 2.0
end-perform
compute ws-stddev = ( ws-sumsq / ws-tb-size) ** 0.5
goback.
end program stddev.
|
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC.
For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string:
The quick brown fox jumps over the lazy dog
| #6502_Assembly | 6502 Assembly | PRHEX EQU $FDDA ; <= REPLACE THIS WITH THE PRHEX ROUTINE FOR YOUR MACHINE
string EQU $EC
length EQU $EE
crc0 EQU $FA
crc1 EQU $FB
crc2 EQU $FC
crc3 EQU $FD
table0 EQU $9200
table1 EQU $9300
table2 EQU $9400
table3 EQU $9500
ORG $9114
LDA #<text
STA string
LDA #>text
STA string+1
LDA #$2b ; length of text
STA length
LDA #$00
STA length+1
STA crc0
STA crc1
STA crc2
STA crc3
JSR crc32
LDA crc3
JSR PRHEX
LDA crc2
JSR PRHEX
LDA crc1
JSR PRHEX
LDA crc0
JMP PRHEX
text
ASC 'The quick brown fox jumps over the lazy dog'
; ORG $916E
crc32
JSR start
LDY string
STX string
loop
LDA length
BNE no_borrow
LDA length+1
BEQ ones_complement
DEC length+1
no_borrow
DEC length
LDA (string),Y
EOR crc0
TAX
LDA table0,X
EOR crc1
STA crc0
LDA table1,X
EOR crc2
STA crc1
LDA table2,X
EOR crc3
STA crc2
LDA table3,X
STA crc3
INY
BNE loop
INC string+1
BNE loop
start
have_table
LDX #$00
BNE loop4 ; LDX #$04 BNE ones_complement
loop256
LDA #$00
STA table3,X
STA table2,X
STA table1,X
TXA
STA table0,X
LDY #$08
loop8
LSR table3,X
ROR table2,X
ROR table1,X
ROR table0,X
BCC no_xor
LDA table3,X
EOR #$ED
STA table3,X
LDA table2,X
EOR #$B8
STA table2,X
LDA table1,X
EOR #$83
STA table1,X
LDA table0,X
EOR #$20
STA table0,X
no_xor
DEY
BNE loop8
INX
BNE loop256
ones_complement
LDX #$04
STX have_table+1 ; self-modify
loop4
DEX
LDA crc0,X
EOR #$FF
STA crc0,X
TXA
BNE loop4
RTS |
http://rosettacode.org/wiki/CRC-32 | CRC-32 |
Task
Demonstrate a method of deriving the Cyclic Redundancy Check from within the language.
The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG.
Algorithms are described on Computation of CRC in Wikipedia.
This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC.
For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string:
The quick brown fox jumps over the lazy dog
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with GNAT.CRC32; use GNAT.CRC32;
with Interfaces; use Interfaces;
procedure TestCRC is
package IIO is new Ada.Text_IO.Modular_IO (Unsigned_32);
crc : CRC32;
num : Unsigned_32;
str : String := "The quick brown fox jumps over the lazy dog";
begin
Initialize (crc);
Update (crc, str);
num := Get_Value (crc);
IIO.Put (num, Base => 16); New_Line;
end TestCRC; |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
#Include "vbcompat.bi"
Dim d As Long = Now
Print "This example was created on : "; Format(d, "yyyy-mm-dd")
Print "In other words on : "; Format(d, "dddd, mmmm d, yyyy")
Print
Print "Press any key to quit the program"
Sleep |
http://rosettacode.org/wiki/Date_format | Date format | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Task
Display the current date in the formats of:
2007-11-23 and
Friday, November 23, 2007
| #Free_Pascal | Free Pascal | program Format_Date_Time;
uses
SysUtils;
begin
WriteLn(FormatDateTime('yyyy-mm-dd', Now) +#13#10+ FormatDateTime('dddd, mmmm dd, yyyy', Now));
end.
|
http://rosettacode.org/wiki/CSV_to_HTML_translation | CSV to HTML translation | Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.
No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be escaped when converted to HTML
Task
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.
Use the following data as the CSV text to convert, and show your output.
Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!
Extra credit
Optionally allow special formatting for the first row of the table as if it is the tables header row
(via <thead> preferably; CSS if you must).
| #11l | 11l | V input_csv = ‘Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!’
print("<table>\n<tr><td>", end' ‘’)
L(c) input_csv
print(S c {
"\n"{"</td></tr>\n<tr><td>"}
‘,’ {‘</td><td>’}
‘<’ {‘<’}
‘>’ {‘>’}
‘&’ {‘&’}
E {c}
}, end' ‘’)
print("</td></tr>\n</table>") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.