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/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #Wren | Wren | import "/math" for Int
import "/seq" for Lst
import "/fmt" for Fmt
import "/str" for Str
var findFirst = Fn.new { |list|
var i = 0
for (n in list) {
if (n > 1e7) return [n, i]
i = i + 1
}
}
var ranges = [0..0, 101..909, 11011..99099, 1110111..9990999, 111101111..119101111]
var cyclops = []
for (r in ranges) {
var numDigits = r.from.toString.count
var center = (numDigits / 2).floor
for (i in r) {
var digits = Int.digits(i)
if (digits[center] == 0 && digits.count { |d| d == 0 } == 1) cyclops.add(i)
}
}
System.print("The first 50 cyclops numbers are:")
var candidates = cyclops[0...50]
var ni = findFirst.call(cyclops)
for (chunk in Lst.chunks(candidates, 10)) Fmt.print("$,6d", chunk)
Fmt.print("\nFirst such number > 10 million is $,d at zero-based index $,d", ni[0], ni[1])
System.print("\n\nThe first 50 prime cyclops numbers are:")
var primes = cyclops.where { |n| Int.isPrime(n) }
candidates = primes.take(50).toList
ni = findFirst.call(primes)
for (chunk in Lst.chunks(candidates, 10)) Fmt.print("$,6d", chunk)
Fmt.print("\nFirst such number > 10 million is $,d at zero-based index $,d", ni[0], ni[1])
System.print("\n\nThe first 50 blind prime cyclops numbers are:")
var bpcyclops = []
var ppcyclops = []
for (p in primes) {
var ps = p.toString
var numDigits = ps.count
var center = (numDigits/2).floor
var noMiddle = Num.fromString(Str.delete(ps, center))
if (Int.isPrime(noMiddle)) bpcyclops.add(p)
if (ps == ps[-1..0]) ppcyclops.add(p)
}
candidates = bpcyclops[0...50]
ni = findFirst.call(bpcyclops)
for (chunk in Lst.chunks(candidates, 10)) Fmt.print("$,6d", chunk)
Fmt.print("\nFirst such number > 10 million is $,d at zero-based index $,d", ni[0], ni[1])
System.print("\n\nThe first 50 palindromic prime cyclops numbers are:")
candidates = ppcyclops[0...50]
ni = findFirst.call(ppcyclops)
for (chunk in Lst.chunks(candidates, 8)) Fmt.print("$,9d", chunk)
Fmt.print("\nFirst such number > 10 million is $,d at zero-based index $,d", ni[0], ni[1]) |
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.
| #EchoLisp | EchoLisp |
(define my-date (string->date "March 7 2009 7:30 pm EST"))
→ Sun Mar 08 2009 01:30:00 GMT+0100 (CET)
(date-add! my-date (* 12 3600))
→ Sun Mar 08 2009 13:30:00 GMT+0100 (CET)
(string->date my-date)
(date->string my-date)
→ "8/3/2009 13:30:00" ;; human localized, Paris time.
|
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.
| #Erlang | Erlang |
-module( date_manipulation ).
-export( [task/0] ).
task() ->
{Date_time, TZ} = date_time_tz_from_string( "March 7 2009 7:30pm EST" ),
Seconds1 = calendar:datetime_to_gregorian_seconds( Date_time ),
Seconds2 = calendar:datetime_to_gregorian_seconds( {calendar:gregorian_days_to_date(0), {12, 0, 0}} ),
Date_time_later = calendar:gregorian_seconds_to_datetime( Seconds1 + Seconds2 ),
{Date_time_later, TZ}.
date_time_tz_from_string( String ) ->
[Month, Date, Year, Time, TZ] = string:tokens( String, " " ),
[Hour, Minute] = string:tokens( Time, ":" ),
{{date_from_strings(Year, Month, Date), time_from_strings(Hour, Minute)}, TZ}.
date_from_strings( Year, Month, Date ) ->
{erlang:list_to_integer(Year), date_from_strings_month(Month), erlang:list_to_integer(Date)}.
date_from_strings_month( "January" ) -> 1;
date_from_strings_month( "February" ) -> 2;
date_from_strings_month( "March" ) -> 3;
date_from_strings_month( "April" ) -> 4;
date_from_strings_month( "May" ) -> 5;
date_from_strings_month( "June" ) -> 6;
date_from_strings_month( "July" ) -> 7;
date_from_strings_month( "August" ) -> 8;
date_from_strings_month( "September" ) -> 9;
date_from_strings_month( "October" ) -> 10;
date_from_strings_month( "November" ) -> 11;
date_from_strings_month( "December" ) -> 12.
time_from_strings( Hour, Minute_12hours ) ->
{ok, [Minute], AM_PM} = io_lib:fread("~d", Minute_12hours ),
{time_from_strings_hour( Hour, string:to_lower(AM_PM) ), Minute, 0}.
time_from_strings_hour( Hour, "am" ) -> erlang:list_to_integer( Hour );
time_from_strings_hour( Hour, "pm" ) -> erlang:list_to_integer( Hour ) + 12.
|
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #PHP | PHP | class FreeCell_Deal {
protected $deck = array(
'AC', 'AD', 'AH', 'AS', '2C', '2D', '2H', '2S', '3C', '3D', '3H', '3S',
'4C', '4D', '4H', '4S', '5C', '5D', '5H', '5S', '6C', '6D', '6H', '6S',
'7C', '7D', '7H', '7S', '8C', '8D', '8H', '8S', '9C', '9D', '9H', '9S',
'TC', 'TD', 'TH', 'TS', 'JC', 'JD', 'JH', 'JS', 'QC', 'QD', 'QH', 'QS',
'KC', 'KD', 'KH', 'KS'
);
protected $game; // Freecell Game Number
protected $state; // Current state of the LCG
public $deal = array(); // Generated card sequence to deal
function __construct( $game ) {
$this->game = max( min( $game, 32000 ), 1 );
// seed RNG with game number
$this->state = $this->game;
while ( ! empty( $this->deck ) ) {
// choose random card
$i = $this->lcg_rnd() % count( $this->deck );
// move random card to game deal pile
$this->deal[] = $this->deck[ $i ];
// move last card to random card spot
$this->deck[ $i ] = end( $this->deck );
// remove last card from deck
array_pop( $this->deck );
}
}
protected function lcg_rnd() {
return ( $this->state = ( $this->state * 214013 + 2531011 ) % 2147483648 ) >> 16;
}
function print( $cols = 8 ) {
echo str_pad( " Game " . $this->game . " ", $cols * 3 - 1, '=', STR_PAD_BOTH ), PHP_EOL;
foreach ( array_chunk( $this->deal, $cols ) as $row ) {
echo implode( " ", $row ), PHP_EOL;
}
echo PHP_EOL;
}
}
$tests = array( 1, 617, 11982 );
foreach ( $tests as $game_num ) {
$deal = new FreeCell_Deal( $game_num );
$deal->print();
}
|
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Visual_Basic_.NET | Visual Basic .NET | Structure LimitedInt
Implements IComparable, IComparable(Of LimitedInt), IConvertible, IEquatable(Of LimitedInt), IFormattable
Private Const MIN_VALUE = 1
Private Const MAX_VALUE = 10
Shared ReadOnly MinValue As New LimitedInt(MIN_VALUE)
Shared ReadOnly MaxValue As New LimitedInt(MAX_VALUE)
Private Shared Function IsValidValue(value As Integer) As Boolean
Return value >= MIN_VALUE AndAlso value <= MAX_VALUE
End Function
Private ReadOnly _value As Integer
ReadOnly Property Value As Integer
Get
' Treat the default, 0, as being the minimum value.
Return If(Me._value = 0, MIN_VALUE, Me._value)
End Get
End Property
Sub New(value As Integer)
If Not IsValidValue(value) Then Throw New ArgumentOutOfRangeException(NameOf(value), value, $"Value must be between {MIN_VALUE} and {MAX_VALUE}.")
Me._value = value
End Sub
#Region "IComparable"
Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo
If TypeOf obj IsNot LimitedInt Then Throw New ArgumentException("Object must be of type " + NameOf(LimitedInt), NameOf(obj))
Return Me.CompareTo(DirectCast(obj, LimitedInt))
End Function
#End Region
#Region "IComparable(Of LimitedInt)"
Function CompareTo(other As LimitedInt) As Integer Implements IComparable(Of LimitedInt).CompareTo
Return Me.Value.CompareTo(other.Value)
End Function
#End Region
#Region "IConvertible"
Function GetTypeCode() As TypeCode Implements IConvertible.GetTypeCode
Return Me.Value.GetTypeCode()
End Function
Private Function ToBoolean(provider As IFormatProvider) As Boolean Implements IConvertible.ToBoolean
Return DirectCast(Me.Value, IConvertible).ToBoolean(provider)
End Function
Private Function ToByte(provider As IFormatProvider) As Byte Implements IConvertible.ToByte
Return DirectCast(Me.Value, IConvertible).ToByte(provider)
End Function
Private Function ToChar(provider As IFormatProvider) As Char Implements IConvertible.ToChar
Return DirectCast(Me.Value, IConvertible).ToChar(provider)
End Function
Private Function ToDateTime(provider As IFormatProvider) As Date Implements IConvertible.ToDateTime
Return DirectCast(Me.Value, IConvertible).ToDateTime(provider)
End Function
Private Function ToDecimal(provider As IFormatProvider) As Decimal Implements IConvertible.ToDecimal
Return DirectCast(Me.Value, IConvertible).ToDecimal(provider)
End Function
Private Function ToDouble(provider As IFormatProvider) As Double Implements IConvertible.ToDouble
Return DirectCast(Me.Value, IConvertible).ToDouble(provider)
End Function
Private Function ToInt16(provider As IFormatProvider) As Short Implements IConvertible.ToInt16
Return DirectCast(Me.Value, IConvertible).ToInt16(provider)
End Function
Private Function ToInt32(provider As IFormatProvider) As Integer Implements IConvertible.ToInt32
Return DirectCast(Me.Value, IConvertible).ToInt32(provider)
End Function
Private Function ToInt64(provider As IFormatProvider) As Long Implements IConvertible.ToInt64
Return DirectCast(Me.Value, IConvertible).ToInt64(provider)
End Function
Private Function ToSByte(provider As IFormatProvider) As SByte Implements IConvertible.ToSByte
Return DirectCast(Me.Value, IConvertible).ToSByte(provider)
End Function
Private Function ToSingle(provider As IFormatProvider) As Single Implements IConvertible.ToSingle
Return DirectCast(Me.Value, IConvertible).ToSingle(provider)
End Function
Private Overloads Function ToString(provider As IFormatProvider) As String Implements IConvertible.ToString
Return Me.Value.ToString(provider)
End Function
Private Function ToType(conversionType As Type, provider As IFormatProvider) As Object Implements IConvertible.ToType
Return DirectCast(Me.Value, IConvertible).ToType(conversionType, provider)
End Function
Private Function ToUInt16(provider As IFormatProvider) As UShort Implements IConvertible.ToUInt16
Return DirectCast(Me.Value, IConvertible).ToUInt16(provider)
End Function
Private Function ToUInt32(provider As IFormatProvider) As UInteger Implements IConvertible.ToUInt32
Return DirectCast(Me.Value, IConvertible).ToUInt32(provider)
End Function
Private Function ToUInt64(provider As IFormatProvider) As ULong Implements IConvertible.ToUInt64
Return DirectCast(Me.Value, IConvertible).ToUInt64(provider)
End Function
#End Region
#Region "IEquatable(Of LimitedInt)"
Overloads Function Equals(other As LimitedInt) As Boolean Implements IEquatable(Of LimitedInt).Equals
Return Me = other
End Function
#End Region
#Region "IFormattable"
Private Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString
Return Me.Value.ToString(format, formatProvider)
End Function
#End Region
#Region "Operators"
Shared Operator =(left As LimitedInt, right As LimitedInt) As Boolean
Return left.Value = right.Value
End Operator
Shared Operator <>(left As LimitedInt, right As LimitedInt) As Boolean
Return left.Value <> right.Value
End Operator
Shared Operator <(left As LimitedInt, right As LimitedInt) As Boolean
Return left.Value < right.Value
End Operator
Shared Operator >(left As LimitedInt, right As LimitedInt) As Boolean
Return left.Value > right.Value
End Operator
Shared Operator <=(left As LimitedInt, right As LimitedInt) As Boolean
Return left.Value <= right.Value
End Operator
Shared Operator >=(left As LimitedInt, right As LimitedInt) As Boolean
Return left.Value >= right.Value
End Operator
Shared Operator +(left As LimitedInt) As LimitedInt
Return CType(+left.Value, LimitedInt)
End Operator
Shared Operator -(left As LimitedInt) As LimitedInt
Return CType(-left.Value, LimitedInt)
End Operator
Shared Operator +(left As LimitedInt, right As LimitedInt) As LimitedInt
Return CType(left.Value + right.Value, LimitedInt)
End Operator
Shared Operator -(left As LimitedInt, right As LimitedInt) As LimitedInt
Return CType(left.Value - right.Value, LimitedInt)
End Operator
Shared Operator *(left As LimitedInt, right As LimitedInt) As LimitedInt
Return CType(left.Value * right.Value, LimitedInt)
End Operator
Shared Operator /(left As LimitedInt, right As LimitedInt) As Double
Return left.Value / right.Value
End Operator
Shared Operator \(left As LimitedInt, right As LimitedInt) As LimitedInt
Return CType(left.Value \ right.Value, LimitedInt)
End Operator
Shared Operator ^(left As LimitedInt, right As LimitedInt) As Double
Return left.Value ^ right.Value
End Operator
Shared Operator Mod(left As LimitedInt, right As LimitedInt) As LimitedInt
Return CType(left.Value Mod right.Value, LimitedInt)
End Operator
Shared Operator And(left As LimitedInt, right As LimitedInt) As LimitedInt
Return CType(left.Value And right.Value, LimitedInt)
End Operator
Shared Operator Or(left As LimitedInt, right As LimitedInt) As LimitedInt
Return CType(left.Value Or right.Value, LimitedInt)
End Operator
Shared Operator Xor(left As LimitedInt, right As LimitedInt) As LimitedInt
Return CType(left.Value Xor right.Value, LimitedInt)
End Operator
Shared Operator Not(left As LimitedInt) As LimitedInt
Return CType(Not left.Value, LimitedInt)
End Operator
Shared Operator >>(left As LimitedInt, right As Integer) As LimitedInt
Return CType(left.Value >> right, LimitedInt)
End Operator
Shared Operator <<(left As LimitedInt, right As Integer) As LimitedInt
Return CType(left.Value << right, LimitedInt)
End Operator
Shared Widening Operator CType(value As LimitedInt) As Integer
Return value.Value
End Operator
Shared Narrowing Operator CType(value As Integer) As LimitedInt
If Not IsValidValue(value) Then Throw New OverflowException()
Return New LimitedInt(value)
End Operator
#End Region
'Function TryFormat(destination As Span(Of Char), ByRef charsWritten As Integer, Optional format As ReadOnlySpan(Of Char) = Nothing, Optional provider As IFormatProvider = Nothing) As Boolean
' Return Me.Value.TryFormat(destination, charsWritten, format, provider)
'End Function
Overrides Function GetHashCode() As Integer
Return Me.Value.GetHashCode
End Function
Overrides Function Equals(obj As Object) As Boolean
Return TypeOf obj Is LimitedInt AndAlso Me.Equals(DirectCast(obj, LimitedInt))
End Function
Overrides Function ToString() As String
Return Me.Value.ToString()
End Function
#Region "Shared Methods"
'Shared Function TryParse(s As ReadOnlySpan(Of Char), ByRef result As Integer) As Boolean
' Return Integer.TryParse(s, result)
'End Function
'Shared Function TryParse(s As ReadOnlySpan(Of Char), style As Globalization.NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean
' Return Integer.TryParse(s, style, provider, result)
'End Function
Shared Function Parse(s As String, provider As IFormatProvider) As Integer
Return Integer.Parse(s, provider)
End Function
Shared Function Parse(s As String, style As Globalization.NumberStyles, provider As IFormatProvider) As Integer
Return Integer.Parse(s, style, provider)
End Function
Shared Function TryParse(s As String, style As Globalization.NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean
Return Integer.TryParse(s, style, provider, result)
End Function
Shared Function Parse(s As String) As Integer
Return Integer.Parse(s)
End Function
Shared Function Parse(s As String, style As Globalization.NumberStyles) As Integer
Return Integer.Parse(s, style)
End Function
'Shared Function Parse(s As ReadOnlySpan(Of Char), Optional style As Globalization.NumberStyles = Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As Integer
' Return Integer.Parse(s, style, provider)
'End Function
Shared Function TryParse(s As String, ByRef result As Integer) As Boolean
Return Integer.TryParse(s, result)
End Function
#End Region
End Structure |
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.
| #COBOL | COBOL |
program-id. dec25.
data division.
working-storage section.
1 work-date.
2 yr pic 9(4) value 2008.
2 mo-da pic 9(4) value 1225. *> Dec 25
1 wk-date redefines work-date pic 9(8).
1 binary.
2 int-date pic 9(8).
2 dow pic 9(4).
procedure division.
perform varying yr from 2008 by 1
until yr > 2121
compute int-date = function integer-of-date (wk-date)
compute dow = function mod ((int-date - 1) 7) + 1
if dow = 7 *> Sunday = 7 per ISO 8601 and ISO 1989
display yr
end-if
end-perform
stop run
.
end program dec25.
|
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
| #BCPL | BCPL | get "libhdr"
let validcusip(c) = valof
$( let sum = 0
unless c%0 = 9 resultis false
for i = 1 to 8 do
$( let v = ( 2 - (i & 1) ) * valof
$( test '0' <= c%i <= '9'
then resultis c%i - '0'
or test 'A' <= c%i <= 'Z'
then resultis 10 + c%i - 'A'
or test c%i = '**'
then resultis 36
or test c%i = '@'
then resultis 37
or test c%i = '#'
then resultis 38
else resultis -1
$)
sum := sum + v/10 + v rem 10
$)
resultis (10 - (sum rem 10)) rem 10 = c%9 - '0'
$)
let show(c) be
writef("%S: %Svalid*N", c, validcusip(c) -> "", "in")
let start() be
$( show("037833100")
show("17275R102")
show("38259P508")
show("594918104")
show("68389X106")
show("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
| #C | C |
#include<stdlib.h>
#include<stdio.h>
int cusipCheck(char str[10]){
int sum=0,i,v;
for(i=0;i<8;i++){
if(str[i]>='0'&&str[i]<='9')
v = str[i]-'0';
else if(str[i]>='A'&&str[i]<='Z')
v = (str[i] - 'A' + 10);
else if(str[i]=='*')
v = 36;
else if(str[i]=='@')
v = 37;
else if(str[i]=='#')
v = 38;
if(i%2!=0)
v*=2;
sum += ((int)(v/10) + v%10);
}
return ((10 - (sum%10))%10);
}
int main(int argC,char* argV[])
{
char cusipStr[10];
int i,numLines;
if(argC==1)
printf("Usage : %s <full path of CUSIP Data file>",argV[0]);
else{
FILE* fp = fopen(argV[1],"r");
fscanf(fp,"%d",&numLines);
printf("CUSIP Verdict\n");
printf("-------------------");
for(i=0;i<numLines;i++){
fscanf(fp,"%s",cusipStr);
printf("\n%s : %s",cusipStr,(cusipCheck(cusipStr)==(cusipStr[8]-'0'))?"Valid":"Invalid");
}
fclose(fp);
}
return 0;
}
|
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
| #AutoIt | AutoIt |
#include <Date.au3>
$iYear = 2007
$iMonth = 11
$iDay = 10
ConsoleWrite(StringFormat('%4d-%02d-%02d', $iYear, $iMonth, $iDay) & @LF)
$iWeekDay = _DateToDayOfWeekISO($iYear, $iMonth, $iDay)
ConsoleWrite(StringFormat('%s, %s %02d, %4d', _GetLongDayLocale($iWeekDay), _GetLongMonthLocale($iMonth), $iDay, $iYear) & @LF)
Func _GetLongDayLocale($_iWeekDay) ; 1..7 Monday=1
Local $aDayName[8] = [0, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30]
Return GetLocaleInfo($aDayName[$_iWeekDay])
EndFunc
Func _GetLongMonthLocale($_iMonth) ; 1..12 January=1
Local $aMonthName[13] = [0, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43]
Return GetLocaleInfo($aMonthName[$_iMonth])
EndFunc
Func GetLocaleInfo($_LCType)
Local $ret, $LCID, $sBuffer, $iLen
$ret = DllCall('kernel32', 'long', 'GetSystemDefaultLCID')
$LCID = $ret[0]
$ret = DllCall('kernel32', 'long', 'GetLocaleInfo', 'long', $LCID, 'long', $_LCType, 'str', $sBuffer, 'long', 0)
$iLen = $ret[0]
$ret = DllCall('kernel32', 'long', 'GetLocaleInfo', 'long', $LCID, 'long', $_LCType, 'str', $sBuffer, 'long', $iLen)
Return $ret[3]
EndFunc
|
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #ALGOL_68 | ALGOL 68 | BEGIN # find Cullen and Woodall numbers and determine which are prime #
# a Cullen number n is n2^2 + 1, Woodall number is n2^n - 1 #
PR read "primes.incl.a68" PR # include prime utilities #
PR precision 800 PR # set number of digits for Algol 68G LONG LONG INT #
# returns the nth Cullen number #
OP CULLEN = ( INT n )LONG LONG INT: n * LONG LONG INT(2)^n + 1;
# returns the nth Woodall number #
OP WOODALL = ( INT n )LONG LONG INT: CULLEN n - 2;
# show the first 20 Cullen numbers #
print( ( "1st 20 Cullen numbers:" ) );
FOR n TO 20 DO
print( ( " ", whole( CULLEN n, 0 ) ) )
OD;
print( ( newline ) );
# show the first 20 Woodall numbers #
print( ( "1st 20 Woodall numbers:" ) );
FOR n TO 20 DO
print( ( " ", whole( WOODALL n, 0 ) ) )
OD;
print( ( newline ) );
BEGIN # first 2 Cullen primes #
print( ( "Index of the 1st 2 Cullen primes:" ) );
LONG LONG INT power of 2 := 1;
INT prime count := 0;
FOR n WHILE prime count < 2 DO
power of 2 *:= 2;
LONG LONG INT c n = ( n * power of 2 ) + 1;
IF is probably prime( c n ) THEN
prime count +:= 1;
print( ( " ", whole( n, 0 ) ) )
FI
OD;
print( ( newline ) )
END;
BEGIN # first 12 Woodall primes #
print( ( "Index of the 1st 12 Woodall primes:" ) );
LONG LONG INT power of 2 := 1;
INT prime count := 0;
FOR n WHILE prime count < 12 DO
power of 2 *:= 2;
LONG LONG INT w n = ( n * power of 2 ) - 1;
IF is probably prime( w n ) THEN
prime count +:= 1;
print( ( " ", whole( n, 0 ) ) )
FI
OD;
print( ( newline ) )
END
END |
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.
| #C | C | #include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
bool damm(unsigned char *input, size_t length) {
static const unsigned char table[10][10] = {
{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},
};
unsigned char interim = 0;
for (size_t i = 0; i < length; i++) {
interim = table[interim][input[i]];
}
return interim == 0;
}
int main() {
unsigned char input[4] = {5, 7, 2, 4};
puts(damm(input, 4) ? "Checksum correct" : "Checksum incorrect");
return 0;
} |
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.
| #ALGOL_68 | ALGOL 68 | # Raising a function to a power #
MODE FUN = PROC (REAL) REAL;
PROC pow = (FUN f, INT n, REAL x) REAL: f(x) ** n;
OP ** = (FUN f, INT n) FUN: pow (f, n, );
# Example: sin (3 x) = 3 sin (x) - 4 sin^3 (x) (follows from DeMoivre's theorem) #
REAL x = read real;
print ((new line, sin (3 * x), 3 * sin (x) - 4 * (sin ** 3) (x))) |
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.
| #AppleScript | AppleScript | -- curry :: (Script|Handler) -> Script
on curry(f)
script
on |λ|(a)
script
on |λ|(b)
|λ|(a, b) of mReturn(f)
end |λ|
end script
end |λ|
end script
end curry
-- TESTS ----------------------------------------------------------------------
-- add :: Num -> Num -> Num
on add(a, b)
a + b
end add
-- product :: Num -> Num -> Num
on product(a, b)
a * b
end product
-- Test 1.
curry(add)
--> «script»
-- Test 2.
curry(add)'s |λ|(2)
--> «script»
-- Test 3.
curry(add)'s |λ|(2)'s |λ|(3)
--> 5
-- Test 4.
map(curry(product)'s |λ|(7), enumFromTo(1, 10))
--> {7, 14, 21, 28, 35, 42, 49, 56, 63, 70}
-- Combined:
{curry(add), ¬
curry(add)'s |λ|(2), ¬
curry(add)'s |λ|(2)'s |λ|(3), ¬
map(curry(product)'s |λ|(7), enumFromTo(1, 10))}
--> {«script», «script», 5, {7, 14, 21, 28, 35, 42, 49, 56, 63, 70}}
-- GENERIC FUNCTIONS ----------------------------------------------------------
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if n < m then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn |
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. | #Haskell | Haskell | import Data.List
import Data.Numbers.Primes (primeFactors)
negateVar p = zipWith (*) p $ reverse $ take (length p) $ cycle [1,-1]
lift p 1 = p
lift p n = intercalate (replicate (n-1) 0) (pure <$> p)
shortDiv :: [Integer] -> [Integer] -> [Integer]
shortDiv p1 (_:p2) = unfoldr go (length p1 - length p2, p1)
where
go (0, _) = Nothing
go (i, h:t) = Just (h, (i-1, zipWith (+) (map (h *) ker) t))
ker = negate <$> p2 ++ repeat 0
primePowerFactors = sortOn fst . map (\x-> (head x, length x)) . group . primeFactors
-- simple memoization
cyclotomics :: [[Integer]]
cyclotomics = cyclotomic <$> [0..]
cyclotomic :: Int -> [Integer]
cyclotomic 0 = [0]
cyclotomic 1 = [1, -1]
cyclotomic 2 = [1, 1]
cyclotomic n = case primePowerFactors n of
-- for n = 2^k
[(2,h)] -> 1 : replicate (2 ^ (h-1) - 1) 0 ++ [1]
-- for prime n
[(p,1)] -> replicate n 1
-- for power of prime n
[(p,m)] -> lift (cyclotomics !! p) (p^(m-1))
-- for n = 2*p and prime p
[(2,1),(p,1)] -> take (n `div` 2) $ cycle [1,-1]
-- for n = 2*m and odd m
(2,1):_ -> negateVar $ cyclotomics !! (n `div` 2)
-- general case
(p, m):ps -> let cm = cyclotomics !! (n `div` (p ^ m))
in lift (lift cm p `shortDiv` cm) (p^(m-1)) |
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.
| #Java | Java | import java.util.*;
public class CutRectangle {
private static int[][] dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
public static void main(String[] args) {
cutRectangle(2, 2);
cutRectangle(4, 3);
}
static void cutRectangle(int w, int h) {
if (w % 2 == 1 && h % 2 == 1)
return;
int[][] grid = new int[h][w];
Stack<Integer> stack = new Stack<>();
int half = (w * h) / 2;
long bits = (long) Math.pow(2, half) - 1;
for (; bits > 0; bits -= 2) {
for (int i = 0; i < half; i++) {
int r = i / w;
int c = i % w;
grid[r][c] = (bits & (1 << i)) != 0 ? 1 : 0;
grid[h - r - 1][w - c - 1] = 1 - grid[r][c];
}
stack.push(0);
grid[0][0] = 2;
int count = 1;
while (!stack.empty()) {
int pos = stack.pop();
int r = pos / w;
int c = pos % w;
for (int[] dir : dirs) {
int nextR = r + dir[0];
int nextC = c + dir[1];
if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) {
if (grid[nextR][nextC] == 1) {
stack.push(nextR * w + nextC);
grid[nextR][nextC] = 2;
count++;
}
}
}
}
if (count == half) {
printResult(grid);
}
}
}
static void printResult(int[][] arr) {
for (int[] a : arr)
System.out.println(Arrays.toString(a));
System.out.println();
}
} |
http://rosettacode.org/wiki/Cyclops_numbers | Cyclops numbers | A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology.
Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10.
There are many different classifications of cyclops numbers with minor differences in characteristics. In an effort to head off a whole series of tasks with tiny variations, we will cover several variants here.
Task
Find and display here on this page the first 50 cyclops numbers in base 10 (all of the sub tasks are restricted to base 10).
Find and display here on this page the first 50 prime cyclops numbers. (cyclops numbers that are prime.)
Find and display here on this page the first 50 blind prime cyclops numbers. (prime cyclops numbers that remain prime when "blinded"; the zero is removed from the center.)
Find and display here on this page the first 50 palindromic prime cyclops numbers. (prime cyclops numbers that are palindromes.)
Stretch
Find and display the first cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first blind prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
Find and display the first palindromic prime cyclops number greater than ten million (10,000,000) and the index (place) in the series where it is found.
(Note: there are no cyclops numbers between ten million and one hundred million, they need to have an odd number of digits)
See also
OEIS A134808 - Cyclops numbers
OEIS A134809 - Cyclops primes
OEIS A329737 - Cyclops primes that remain prime after being "blinded"
OEIS A136098 - Prime palindromic cyclops numbers
| #XPL0 | XPL0 | func IsCyclops(N); \Return 'true' if N is a cyclops number
int N, I, J, K;
char A(9);
[I:= 0; \parse digits into array A
repeat N:= N/10;
A(I):= rem(0);
I:= I+1;
until N=0;
if (I&1) = 0 then return false; \must have odd number of digits
K:= I>>1;
if A(K) # 0 then return false; \middle digit must be 0
for J:= 0 to I-1 do \other digits must not be 0
if A(J)=0 & J#K then return false;
return true;
];
func IsPrime(N); \Return 'true' if N > 2 is a prime number
int N, I;
[if (N&1) = 0 \even number\ then return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
func Blind(N); \Return blinded cyclops number
int N, I, J, K; \i.e. center zero removed
char A(9);
[I:= 0; \parse digits into array A
repeat N:= N/10;
A(I):= rem(0);
I:= I+1;
until N=0;
N:= A(I-1); \most significant digit
K:= I>>1;
for J:= I-2 downto 0 do
if J#K then \skip middle zero
N:= N*10 + A(J);
return N;
];
func Reverse(N); \Return N with its digits reversed
int N, M;
[M:= 0;
repeat N:= N/10;
M:= M*10 + rem(0);
until N=0;
return M;
];
func IntLen(N); \Return number of decimal digits in N
int N;
int P, I;
[P:= 10;
for I:= 1 to 9 do \assumes N is 32-bits
[if P>N then return I;
P:= P*10;
];
return 10;
];
int Count, N;
func Show; \Show results and return 'true' when done
[Count:= Count+1;
if Count <= 50 then
[IntOut(0, N);
if rem(Count/10) = 0 then CrLf(0) else ChOut(0, 9\tab\);
];
if N > 10_000_000 then
[Text(0, "First such number > 10,000,000: ");
IntOut(0, N);
Text(0, " at zero based index: ");
IntOut(0, Count-1);
CrLf(0);
return true;
];
return false;
];
proc Common(Filter); \Common code gathered here
int Filter;
[Count:= 0;
N:= 0;
loop [if IsCyclops(N) then
case Filter of
0: if Show then quit;
1: if IsPrime(N) then
if Show then quit;
2: if IsPrime(N) then if IsPrime(Blind(N)) then
if Show then quit;
3: if N=Reverse(N) then if IsPrime(N) then
if Show then quit
other [];
N:= N+1;
if (IntLen(N)&1) = 0 then N:= N*10; \must have odd number of digits
];
];
[Text(0, "First 50 cyclops numbers:
");
Common(0);
Text(0, "
First 50 prime cyclops numbers:
");
Common(1);
Text(0, "
First 50 blind prime cyclops numbers:
");
Common(2);
Text(0, "
First 50 palindromic prime cyclops numbers:
");
Common(3);
] |
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.
| #Euphoria | Euphoria |
--Date Manipulation task from Rosetta Code wiki
--User:Lnettnay
include std/datetime.e
datetime dt
dt = new(2009, 3, 7, 19, 30)
dt = add(dt, 12, HOURS)
printf(1, "%s EST\n", {format(dt, "%B %d %Y %I:%M %p")})
|
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.
| #F.23 | F# | open System
let main() =
let est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")
let date = DateTime.Parse("March 7 2009 7:30pm -5" )
let date_est = TimeZoneInfo.ConvertTime( date, est)
let date2 = date.AddHours(12.0)
let date2_est = TimeZoneInfo.ConvertTime( date2, est)
Console.WriteLine( "Original date in local time : {0}", date )
Console.WriteLine( "Original date in EST : {0}", date_est )
Console.WriteLine( "12 hours later in local time: {0}", date2 )
Console.WriteLine( "12 hours later in EST : {0}", date2_est )
main() |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #PicoLisp | PicoLisp | (setq *MsSeed 11982)
(de msRand ()
(>> 16
(setq *MsSeed
(& (+ 2531011 (* 214013 *MsSeed)) `(dec (** 2 31))) ) ) )
(let L
(make
(for Num (range 13 1)
(for Suit '((32 . "♠") (31 . "♥") (31 . "♦") (32 . "♣"))
(link (cons (get '`(chop "A23456789TJQK") Num) Suit)) ) ) )
(for I 51
(xchg
(nth L I)
(nth L (- 52 (% (msRand) (- 53 I)))) ) )
(for C L
(prin " ^[[" (cadr C) "m" (cddr C) "^[[m" (car C))
(at (0 . 8) (prinl)) )
(prinl) ) |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #PureBasic | PureBasic | #MaxCardNum = 51 ;zero-based count of cards in a deck
Global deckSize
Global Dim cards(#MaxCardNum) ;card with highest index is at the top of deck
Procedure RNG(seed.q = -1)
Static state.q
If seed >= 0
state = seed
Else
state = (state * 214013 + 2531011) % (1 << 31)
ProcedureReturn state >> 16
EndIf
EndProcedure
Procedure makeDeck(hand)
Protected i, c
For i = 0 To #MaxCardNum: cards(i) = i: Next
RNG(hand) ;set seed value
deckSize = #MaxCardNum
While deckSize
c = RNG() % (deckSize + 1)
Swap cards(c), cards(deckSize)
deckSize - 1
Wend
deckSize = #MaxCardNum
EndProcedure
Procedure showDeck(hand)
Protected i, c
PrintN("Hand #" + Str(hand))
makeDeck(hand)
For i = 0 To #MaxCardNum
c = cards(#MaxCardNum - i)
Print(" " + Mid("A23456789TJQK", (c / 4) + 1, 1) + Mid("CDHS",(c % 4) + 1, 1))
If (i + 1) % 8 = 0 Or i = #MaxCardNum: PrintN(""): EndIf
Next
EndProcedure
If OpenConsole()
showDeck(1)
showDeck(617)
showDeck(11982)
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Visual_FoxPro | Visual FoxPro | LOCAL o As BoundedInt
o = NEWOBJECT("BoundedInt")
DO WHILE NOT o.lHasError
o.nValue = o.nValue + 2 && will get as far as 9.
? o.nValue
ENDDO
DEFINE CLASS BoundedInt As Custom
nValue = 1 && default value
lHasError = .F.
PROCEDURE nValue_Assign(tnValue)
*!* This method will check the parameter and if
*!* it is out of bounds, the value will remain unchanged
*!* and an error generated.
tnValue = CAST(tnValue As I)
IF BETWEEN(tnValue, 1, 10)
THIS.nValue = tnValue
ELSE
ERROR "Value must be between 1 and 10."
ENDIF
ENDPROC
PROCEDURE Error(nError, cMethod, nLine)
IF nError = 1098
MESSAGEBOX(MESSAGE(), 0, "Error")
ELSE
DODEFAULT()
ENDIF
THIS.lHasError = .T.
ENDDEFINE |
http://rosettacode.org/wiki/Define_a_primitive_data_type | Define a primitive data type | Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you.
| #Wren | Wren | class TinyInt {
construct new(n) {
if (!(n is Num && n.isInteger && n >= 1 && n <= 10)) {
Fiber.abort("Argument must be an integer between 1 and 10.")
}
_n = n
}
n { _n }
+(other) { TinyInt.new(_n + other.n) }
-(other) { TinyInt.new(_n - other.n) }
*(other) { TinyInt.new(_n * other.n) }
/(other) { TinyInt.new((_n / other.n).truncate) }
==(other) { _n == other.n }
!=(other) { _n != other.n }
toString { _n.toString }
}
var a = TinyInt.new(1)
var b = TinyInt.new(2)
var c = a + b
System.print("%(a) + %(b) = %(c)")
var d = c - a
System.print("%(c) - %(a) = %(d)")
var e = d / d
System.print("%(d) / %(d) = %(e)")
var f = c * c
System.print("%(c) * %(c) = %(f)")
System.print("%(a) != %(b) -> %(a != b)")
System.print("%(a) + %(a) == %(b) -> %((a + a) == b)")
var g = f + b // out of range error here |
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.
| #CoffeeScript | CoffeeScript | december = 11 # gotta love Date APIs :)
sunday = 0
for year in [2008..2121]
xmas = new Date year, december, 25
console.log year if xmas.getDay() is sunday |
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
| #C.23 | C# | using System;
using System.Collections.Generic;
namespace CUSIP {
class Program {
static bool IsCusip(string s) {
if (s.Length != 9) return false;
int sum = 0;
for (int i = 0; i <= 7; i++) {
char c = s[i];
int v;
if (c >= '0' && c <= '9') {
v = c - 48;
}
else if (c >= 'A' && c <= 'Z') {
v = c - 55; // lower case letters apparently invalid
}
else if (c == '*') {
v = 36;
}
else if (c == '#') {
v = 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] - 48 == (10 - (sum % 10)) % 10;
}
static void Main(string[] args) {
List<string> candidates = new List<string>() {
"037833100",
"17275R102",
"38259P508",
"594918104",
"68389X106",
"68389X105"
};
foreach (var candidate in candidates) {
Console.WriteLine("{0} -> {1}", candidate, IsCusip(candidate) ? "correct" : "incorrect");
}
}
}
} |
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
| #AWK | AWK | $ awk 'BEGIN{t=systime();print strftime("%Y-%m-%d",t)"\n"strftime("%A, %B %d, %Y",t)}'
2009-05-15
Friday, May 15, 2009 |
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
| #BaCon | BaCon | ' Date format
n = NOW
PRINT YEAR(n), MONTH(n), DAY(n) FORMAT "%ld-%02ld-%02ld\n"
PRINT WEEKDAY$(n), MONTH$(n), DAY(n), YEAR(n) FORMAT "%s, %s %02ld, %ld\n" |
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #Arturo | Arturo | cullen: function [n]->
inc n * 2^n
woodall: function [n]->
dec n * 2^n
print ["First 20 cullen numbers:" join.with:" " to [:string] map 1..20 => cullen]
print ["First 20 woodall numbers:" join.with:" " to [:string] map 1..20 => woodall] |
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #AWK | AWK |
# syntax: GAWK -f CULLEN_AND_WOODALL_NUMBERS.AWK
BEGIN {
start = 1
stop = 20
printf("Cullen %d-%d:",start,stop)
for (n=start; n<=stop; n++) {
printf(" %d",n*(2^n)+1)
}
printf("\n")
printf("Woodall %d-%d:",start,stop)
for (n=start; n<=stop; n++) {
printf(" %d",n*(2^n)-1)
}
printf("\n")
exit(0)
}
|
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #BASIC | BASIC | print "First 20 Cullen numbers:"
for n = 1 to 20
num = n * (2^n)+1
print int(num); " ";
next
print : print
print "First 20 Woodall numbers:"
for n = 1 to 20
num = n * (2^n)-1
print int(num); " ";
next n
end |
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.
| #C.23 | C# | using System;
namespace DammAlgorithm {
class Program {
static 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},
};
static bool Damm(string s) {
int interim = 0;
foreach (char c in s) {
interim = table[interim, c - '0'];
}
return interim == 0;
}
static void Main(string[] args) {
int[] numbers = { 5724, 5727, 112946, 112949 };
foreach (int number in numbers) {
bool isValid = Damm(number.ToString());
if (isValid) {
Console.WriteLine("{0,6} is valid", number);
}
else {
Console.WriteLine("{0,6} is invalid", number);
}
}
}
}
} |
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.
| #BQN | BQN | Plus3 ← 3⊸+
Plus3_1 ← +⟜3
•Show Plus3 1
•Show Plus3_1 1 |
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.
| #C | C |
#include<stdarg.h>
#include<stdio.h>
long int factorial(int n){
if(n>1)
return n*factorial(n-1);
return 1;
}
long int sumOfFactorials(int num,...){
va_list vaList;
long int sum = 0;
va_start(vaList,num);
while(num--)
sum += factorial(va_arg(vaList,int));
va_end(vaList);
return sum;
}
int main()
{
printf("\nSum of factorials of [1,5] : %ld",sumOfFactorials(5,1,2,3,4,5));
printf("\nSum of factorials of [3,5] : %ld",sumOfFactorials(3,3,4,5));
printf("\nSum of factorials of [1,3] : %ld",sumOfFactorials(3,1,2,3));
return 0;
}
|
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. | #J | J | cyclo=: {{<.-:1+(++) p. 1;^0j2p1* y%~1+I.1=y+.1+i.y}} |
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.
| #Julia | Julia |
const count = [0]
const dir = [[0, -1], [-1, 0], [0, 1], [1, 0]]
function walk(y, x, h, w, grid, len, next)
if y == 0 || y == h || x == 0 || x == w
count[1] += 2
return
end
t = y * (w + 1) + x
grid[t + 1] += UInt8(1)
grid[len - t + 1] += UInt8(1)
for i in 1:4
if grid[t + next[i] + 1] == 0
walk(y + dir[i][1], x + dir[i][2], h, w, grid, len, next)
end
end
grid[t + 1] -= 1
grid[len - t + 1] -= 1
end
function cutrectangle(hh, ww, recur)
if isodd(hh)
h, w = ww, hh
else
h, w = hh, ww
end
if isodd(h)
return 0
elseif w == 1
return 1
elseif w == 2
return h
elseif h == 2
return w
end
cy = div(h, 2)
cx = div(w, 2)
len = (h + 1) * (w + 1)
grid = zeros(UInt8, len)
len -= 1
next = [-1, -w - 1, 1, w + 1]
if recur
count[1] = 0
end
for x in cx + 1:w - 1
t = cy * (w + 1) + x
grid[t + 1] = 1
grid[len - t + 1] = 1
walk(cy - 1, x, h, w, grid, len, next)
end
count[1] += 1
if h == w
count[1] *= 2
elseif iseven(w) && recur
cutrectangle(w, h, false)
end
return count[1]
end
function runtest()
for y in 1:10, x in 1:y
if iseven(x) || iseven(y)
println("$y x $x: $(cutrectangle(y, x, true))")
end
end
end
runtest()
|
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.
| #Factor | Factor | USING: calendar calendar.english calendar.format calendar.parser
combinators io kernel math math.parser sequences splitting
unicode ;
IN: rosetta-code.date-manipulation
! e.g. "7:30pm" -> 19 30
: parse-hm ( str -- hours minutes )
":" split first2 [ digit? ] partition
[ [ string>number ] bi@ ] dip "pm" = [ [ 12 + ] dip ] when ;
! Parse a date in the format "March 7 2009 7:30pm EST"
: parse-date ( str -- timestamp )
" " split {
[ first month-names index 1 + ]
[ second string>number ]
[ third string>number -rot ]
[ fourth parse-hm 0 ]
[ last parse-rfc822-gmt-offset ]
} cleave <timestamp> ;
"March 7 2009 7:30pm EST" parse-date dup 12 hours time+
[ timestamp>rfc822 print ] bi@ |
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.
| #Fantom | Fantom |
fansh> d := DateTime.fromLocale("March 7 2009 7:30pm EST", "MMMM D YYYY h:mmaa zzz")
fansh> d
2009-03-07T19:30:00-05:00 EST
fansh> d + 12hr
2009-03-08T07:30:00-05:00 EST
fansh> (d+12hr).toTimeZone(TimeZone("London")) // the extra credit!
2009-03-08T12:30:00Z London
|
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #Python | Python |
def randomGenerator(seed=1):
max_int32 = (1 << 31) - 1
seed = seed & max_int32
while True:
seed = (seed * 214013 + 2531011) & max_int32
yield seed >> 16
def deal(seed):
nc = 52
cards = list(range(nc - 1, -1, -1))
rnd = randomGenerator(seed)
for i, r in zip(range(nc), rnd):
j = (nc - 1) - r % (nc - i)
cards[i], cards[j] = cards[j], cards[i]
return cards
def show(cards):
l = ["A23456789TJQK"[int(c/4)] + "CDHS"[c%4] for c in cards]
for i in range(0, len(cards), 8):
print(" ".join(l[i : i+8]))
if __name__ == '__main__':
from sys import argv
seed = int(argv[1]) if len(argv) == 2 else 11982
print("Hand {}".format(seed))
deck = deal(seed)
show(deck) |
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.
| #ColdFusion | ColdFusion |
<cfloop from = "2008" to = "2121" index = "i">
<cfset myDate = createDate(i, 12, 25) />
<cfif dayOfWeek(myDate) eq 1>
December 25th falls on a Sunday in <cfoutput>#i#</cfoutput><br />
</cfif>
</cfloop>
|
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.
| #Common_Lisp | Common Lisp | (loop for year from 2008 upto 2121
when (= 6 (multiple-value-bind
(second minute hour date month year day-of-week dst-p tz)
(decode-universal-time (encode-universal-time 0 0 0 25 12 year))
(declare (ignore second minute hour date month year dst-p tz))
day-of-week))
collect 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
| #C.2B.2B | C++ | #include <iostream>
#include <vector>
bool isCusip(const std::string& s) {
if (s.size() != 9) return false;
int sum = 0;
for (int i = 0; i <= 7; ++i) {
char c = s[i];
int v;
if ('0' <= c && c <= '9') {
v = c - '0';
} else if ('A' <= c && c <= 'Z') {
v = c - '@';
} else if (c = '*') {
v = 36;
} else if (c = '#') {
v = 38;
} else {
return false;
}
if (i % 2 == 1) {
v *= 2;
}
sum += v / 10 + v % 10;
}
return s[8] - '0' == (10 - (sum % 10)) % 10;
}
int main() {
using namespace std;
vector<string> candidates{
"037833100",
"17275R102",
"38259P508",
"594918104",
"68389X106",
"68389X105"
};
for (auto str : candidates) {
auto res = isCusip(str) ? "correct" : "incorrect";
cout << str.c_str() << " -> " << res << "\n";
}
return 0;
} |
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
| #11l | 11l | T SD
sum = 0.0
sum2 = 0.0
n = 0.0
F ()(x)
.sum += x
.sum2 += x ^ 2
.n += 1.0
R sqrt(.sum2 / .n - (.sum / .n) ^ 2)
V sd_inst = SD()
L(value) [2, 4, 4, 4, 5, 5, 7, 9]
print(value‘ ’sd_inst(value)) |
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
| #BASIC | BASIC | #include "vbcompat.bi"
DIM today As Double = Now()
PRINT Format(today, "yyyy-mm-dd")
PRINT Format(today, "dddd, mmmm d, yyyy") |
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
| #Batch_File | Batch File |
@echo off
setlocal enabledelayedexpansion
:: Define arrays of days/months we'll need
set daynames=Monday Tuesday Wednesday Thursday Friday Saturday Sunday
set monthnames=January February March April May June July August September October November December
:: Separate the output of the 'date /t' command (outputs in the format of "Sun 16/04/2017") into 4 variables
for /f "tokens=1,2,3,4 delims=/ " %%i in ('date /t') do (
set dayname=%%i
set day=%%j
set month=%%k
set year=%%l
)
:: Crosscheck the first 3 letters of every word in %daynames% to the 3 letter day name found previously
for %%i in (%daynames%) do (
set tempdayname=%%i
set comparedayname=!tempdayname:~0,3!
if "%dayname%"=="!comparedayname!" set fulldayname=%%i
)
:: Variables starting with "0" during the 'set /a' command are treated as octal numbers. To avoid this, if the first character of %month% is "0", it is removed
if "%month:~0,1%"=="0" set monthtemp=%month:~1,1%
set monthcount=0
:: Iterates through %monthnames% and when it reaches the amount of iterations dictated by %month%, sets %monthname% as the current month being iterated through
for %%i in (%monthnames%) do (
set /a monthcount+=1
if %monthtemp%==!monthcount! set monthname=%%i
)
echo %year%-%month%-%day%
echo %fulldayname%, %monthname% %day%, %year%
pause>nul
|
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #F.23 | F# |
// Cullen and Woodall numbers. Nigel Galloway: January 14th., 2022
let Cullen,Woodall=let fG n (g:int)=(bigint g)*2I**g+n in fG 1I, fG -1I
Seq.initInfinite((+)1>>Cullen)|>Seq.take 20|>Seq.iter(printf "%A "); printfn ""
Seq.initInfinite((+)1>>Woodall)|>Seq.take 20|>Seq.iter(printf "%A "); printfn ""
Seq.initInfinite((+)1)|>Seq.filter(fun n->let mutable n=Woodall n in Open.Numeric.Primes.MillerRabin.IsProbablePrime &n)|>Seq.take 12|>Seq.iter(printf "%A "); printfn ""
Seq.initInfinite((+)1)|>Seq.filter(fun n->let mutable n=Cullen n in Open.Numeric.Primes.MillerRabin.IsProbablePrime &n)|>Seq.take 5|>Seq.iter(printf "%A "); printfn ""
|
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #Factor | Factor | USING: arrays kernel math math.vectors prettyprint ranges
sequences ;
20 [1..b] [ dup 2^ * 1 + ] map dup 2 v-n 2array simple-table. |
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #Go | Go | package main
import (
"fmt"
big "github.com/ncw/gmp"
)
func cullen(n uint) *big.Int {
one := big.NewInt(1)
bn := big.NewInt(int64(n))
res := new(big.Int).Lsh(one, n)
res.Mul(res, bn)
return res.Add(res, one)
}
func woodall(n uint) *big.Int {
res := cullen(n)
return res.Sub(res, big.NewInt(2))
}
func main() {
fmt.Println("First 20 Cullen numbers (n * 2^n + 1):")
for n := uint(1); n <= 20; n++ {
fmt.Printf("%d ", cullen(n))
}
fmt.Println("\n\nFirst 20 Woodall numbers (n * 2^n - 1):")
for n := uint(1); n <= 20; n++ {
fmt.Printf("%d ", woodall(n))
}
fmt.Println("\n\nFirst 5 Cullen primes (in terms of n):")
count := 0
for n := uint(1); count < 5; n++ {
cn := cullen(n)
if cn.ProbablyPrime(15) {
fmt.Printf("%d ", n)
count++
}
}
fmt.Println("\n\nFirst 12 Woodall primes (in terms of n):")
count = 0
for n := uint(1); count < 12; n++ {
cn := woodall(n)
if cn.ProbablyPrime(15) {
fmt.Printf("%d ", n)
count++
}
}
fmt.Println()
} |
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.
| #C.2B.2B | C++ | #include <sstream>
const int TABLE[][10] = {
{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},
};
using std::string;
bool damm(string s) {
int interim = 0;
for (char c : s) {
interim = TABLE[interim][c - '0'];
}
return interim == 0;
}
int main() {
auto numbers = { 5724, 5727, 112946, 112949 };
for (int num : numbers) {
using std::stringstream;
stringstream ss;
ss << num;
bool isValid = damm(ss.str());
if (isValid) {
printf("%6d is valid\n", num);
} else {
printf("%6d is invalid\n", num);
}
}
return 0;
} |
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.
| #C.23 | C# | public delegate int Plus(int y);
public delegate Plus CurriedPlus(int x);
public static CurriedPlus plus =
delegate(int x) {return delegate(int y) {return x + y;};};
static void Main()
{
int sum = plus(3)(4); // sum = 7
int sum2= plus(2)(plus(3)(4)) // sum2 = 9
} |
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.
| #C.2B.2B | C++ | shared void run() {
function divide(Integer x, Integer y) => x / y;
value partsOf120 = curry(divide)(120);
print("half of 120 is ``partsOf120(2)``
a third is ``partsOf120(3)``
and a quarter is ``partsOf120(4)``");
} |
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. | #Java | Java |
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class CyclotomicPolynomial {
@SuppressWarnings("unused")
private static int divisions = 0;
private static int algorithm = 2;
public static void main(String[] args) throws Exception {
System.out.println("Task 1: cyclotomic polynomials for n <= 30:");
for ( int i = 1 ; i <= 30 ; i++ ) {
Polynomial p = cyclotomicPolynomial(i);
System.out.printf("CP[%d] = %s%n", i, p);
}
System.out.println("Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:");
int n = 0;
for ( int i = 1 ; i <= 10 ; i++ ) {
while ( true ) {
n++;
Polynomial cyclo = cyclotomicPolynomial(n);
if ( cyclo.hasCoefficientAbs(i) ) {
System.out.printf("CP[%d] has coefficient with magnitude = %d%n", n, i);
n--;
break;
}
}
}
}
private static final Map<Integer, Polynomial> COMPUTED = new HashMap<>();
private static Polynomial cyclotomicPolynomial(int n) {
if ( COMPUTED.containsKey(n) ) {
return COMPUTED.get(n);
}
//System.out.println("COMPUTE: n = " + n);
if ( n == 1 ) {
// Polynomial: x - 1
Polynomial p = new Polynomial(1, 1, -1, 0);
COMPUTED.put(1, p);
return p;
}
Map<Integer,Integer> factors = getFactors(n);
if ( factors.containsKey(n) ) {
// n prime
List<Term> termList = new ArrayList<>();
for ( int index = 0 ; index < n ; index++ ) {
termList.add(new Term(1, index));
}
Polynomial cyclo = new Polynomial(termList);
COMPUTED.put(n, cyclo);
return cyclo;
}
else if ( factors.size() == 2 && factors.containsKey(2) && factors.get(2) == 1 && factors.containsKey(n/2) && factors.get(n/2) == 1 ) {
// n = 2p
int prime = n/2;
List<Term> termList = new ArrayList<>();
int coeff = -1;
for ( int index = 0 ; index < prime ; index++ ) {
coeff *= -1;
termList.add(new Term(coeff, index));
}
Polynomial cyclo = new Polynomial(termList);
COMPUTED.put(n, cyclo);
return cyclo;
}
else if ( factors.size() == 1 && factors.containsKey(2) ) {
// n = 2^h
int h = factors.get(2);
List<Term> termList = new ArrayList<>();
termList.add(new Term(1, (int) Math.pow(2, h-1)));
termList.add(new Term(1, 0));
Polynomial cyclo = new Polynomial(termList);
COMPUTED.put(n, cyclo);
return cyclo;
}
else if ( factors.size() == 1 && ! factors.containsKey(n) ) {
// n = p^k
int p = 0;
for ( int prime : factors.keySet() ) {
p = prime;
}
int k = factors.get(p);
List<Term> termList = new ArrayList<>();
for ( int index = 0 ; index < p ; index++ ) {
termList.add(new Term(1, index * (int) Math.pow(p, k-1)));
}
Polynomial cyclo = new Polynomial(termList);
COMPUTED.put(n, cyclo);
return cyclo;
}
else if ( factors.size() == 2 && factors.containsKey(2) ) {
// n = 2^h * p^k
int p = 0;
for ( int prime : factors.keySet() ) {
if ( prime != 2 ) {
p = prime;
}
}
List<Term> termList = new ArrayList<>();
int coeff = -1;
int twoExp = (int) Math.pow(2, factors.get(2)-1);
int k = factors.get(p);
for ( int index = 0 ; index < p ; index++ ) {
coeff *= -1;
termList.add(new Term(coeff, index * twoExp * (int) Math.pow(p, k-1)));
}
Polynomial cyclo = new Polynomial(termList);
COMPUTED.put(n, cyclo);
return cyclo;
}
else if ( factors.containsKey(2) && ((n/2) % 2 == 1) && (n/2) > 1 ) {
// CP(2m)[x] = CP(-m)[x], n odd integer > 1
Polynomial cycloDiv2 = cyclotomicPolynomial(n/2);
List<Term> termList = new ArrayList<>();
for ( Term term : cycloDiv2.polynomialTerms ) {
termList.add(term.exponent % 2 == 0 ? term : term.negate());
}
Polynomial cyclo = new Polynomial(termList);
COMPUTED.put(n, cyclo);
return cyclo;
}
// General Case
if ( algorithm == 0 ) {
// Slow - uses basic definition.
List<Integer> divisors = getDivisors(n);
// Polynomial: ( x^n - 1 )
Polynomial cyclo = new Polynomial(1, n, -1, 0);
for ( int i : divisors ) {
Polynomial p = cyclotomicPolynomial(i);
cyclo = cyclo.divide(p);
}
COMPUTED.put(n, cyclo);
return cyclo;
}
else if ( algorithm == 1 ) {
// Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor
List<Integer> divisors = getDivisors(n);
int maxDivisor = Integer.MIN_VALUE;
for ( int div : divisors ) {
maxDivisor = Math.max(maxDivisor, div);
}
List<Integer> divisorsExceptMax = new ArrayList<Integer>();
for ( int div : divisors ) {
if ( maxDivisor % div != 0 ) {
divisorsExceptMax.add(div);
}
}
// Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor
Polynomial cyclo = new Polynomial(1, n, -1, 0).divide(new Polynomial(1, maxDivisor, -1, 0));
for ( int i : divisorsExceptMax ) {
Polynomial p = cyclotomicPolynomial(i);
cyclo = cyclo.divide(p);
}
COMPUTED.put(n, cyclo);
return cyclo;
}
else if ( algorithm == 2 ) {
// Fastest
// Let p ; q be primes such that p does not divide n, and q q divides n.
// Then CP(np)[x] = CP(n)[x^p] / CP(n)[x]
int m = 1;
Polynomial cyclo = cyclotomicPolynomial(m);
List<Integer> primes = new ArrayList<>(factors.keySet());
Collections.sort(primes);
for ( int prime : primes ) {
// CP(m)[x]
Polynomial cycloM = cyclo;
// Compute CP(m)[x^p].
List<Term> termList = new ArrayList<>();
for ( Term t : cycloM.polynomialTerms ) {
termList.add(new Term(t.coefficient, t.exponent * prime));
}
cyclo = new Polynomial(termList).divide(cycloM);
m = m * prime;
}
// Now, m is the largest square free divisor of n
int s = n / m;
// Compute CP(n)[x] = CP(m)[x^s]
List<Term> termList = new ArrayList<>();
for ( Term t : cyclo.polynomialTerms ) {
termList.add(new Term(t.coefficient, t.exponent * s));
}
cyclo = new Polynomial(termList);
COMPUTED.put(n, cyclo);
return cyclo;
}
else {
throw new RuntimeException("ERROR 103: Invalid algorithm.");
}
}
private static final List<Integer> getDivisors(int number) {
List<Integer> divisors = new ArrayList<Integer>();
long sqrt = (long) Math.sqrt(number);
for ( int i = 1 ; i <= sqrt ; i++ ) {
if ( number % i == 0 ) {
divisors.add(i);
int div = number / i;
if ( div != i && div != number ) {
divisors.add(div);
}
}
}
return divisors;
}
private static final Map<Integer,Map<Integer,Integer>> allFactors = new TreeMap<Integer,Map<Integer,Integer>>();
static {
Map<Integer,Integer> factors = new TreeMap<Integer,Integer>();
factors.put(2, 1);
allFactors.put(2, factors);
}
public static Integer MAX_ALL_FACTORS = 100000;
public static final Map<Integer,Integer> getFactors(Integer number) {
if ( allFactors.containsKey(number) ) {
return allFactors.get(number);
}
Map<Integer,Integer> factors = new TreeMap<Integer,Integer>();
if ( number % 2 == 0 ) {
Map<Integer,Integer> factorsdDivTwo = getFactors(number/2);
factors.putAll(factorsdDivTwo);
factors.merge(2, 1, (v1, v2) -> v1 + v2);
if ( number < MAX_ALL_FACTORS )
allFactors.put(number, factors);
return factors;
}
boolean prime = true;
long sqrt = (long) Math.sqrt(number);
for ( int i = 3 ; i <= sqrt ; i += 2 ) {
if ( number % i == 0 ) {
prime = false;
factors.putAll(getFactors(number/i));
factors.merge(i, 1, (v1, v2) -> v1 + v2);
if ( number < MAX_ALL_FACTORS )
allFactors.put(number, factors);
return factors;
}
}
if ( prime ) {
factors.put(number, 1);
if ( number < MAX_ALL_FACTORS )
allFactors.put(number, factors);
}
return factors;
}
private static final class Polynomial {
private List<Term> polynomialTerms;
// Format - coeff, exp, coeff, exp, (repeating in pairs) . . .
public Polynomial(int ... values) {
if ( values.length % 2 != 0 ) {
throw new IllegalArgumentException("ERROR 102: Polynomial constructor. Length must be even. Length = " + values.length);
}
polynomialTerms = new ArrayList<>();
for ( int i = 0 ; i < values.length ; i += 2 ) {
Term t = new Term(values[i], values[i+1]);
polynomialTerms.add(t);
}
Collections.sort(polynomialTerms, new TermSorter());
}
public Polynomial() {
// zero
polynomialTerms = new ArrayList<>();
polynomialTerms.add(new Term(0,0));
}
private boolean hasCoefficientAbs(int coeff) {
for ( Term term : polynomialTerms ) {
if ( Math.abs(term.coefficient) == coeff ) {
return true;
}
}
return false;
}
private Polynomial(List<Term> termList) {
if ( termList.size() == 0 ) {
// zero
termList.add(new Term(0,0));
}
else {
// Remove zero terms if needed
for ( int i = 0 ; i < termList.size() ; i++ ) {
if ( termList.get(i).coefficient == 0 ) {
termList.remove(i);
}
}
}
if ( termList.size() == 0 ) {
// zero
termList.add(new Term(0,0));
}
polynomialTerms = termList;
Collections.sort(polynomialTerms, new TermSorter());
}
public Polynomial divide(Polynomial v) {
//long start = System.currentTimeMillis();
divisions++;
Polynomial q = new Polynomial();
Polynomial r = this;
long lcv = v.leadingCoefficient();
long dv = v.degree();
while ( r.degree() >= v.degree() ) {
long lcr = r.leadingCoefficient();
long s = lcr / lcv; // Integer division
Term term = new Term(s, r.degree() - dv);
q = q.add(term);
r = r.add(v.multiply(term.negate()));
}
//long end = System.currentTimeMillis();
//System.out.printf("Divide: Elapsed = %d, Degree 1 = %d, Degree 2 = %d%n", (end-start), this.degree(), v.degree());
return q;
}
public Polynomial add(Polynomial polynomial) {
List<Term> termList = new ArrayList<>();
int thisCount = polynomialTerms.size();
int polyCount = polynomial.polynomialTerms.size();
while ( thisCount > 0 || polyCount > 0 ) {
Term thisTerm = thisCount == 0 ? null : polynomialTerms.get(thisCount-1);
Term polyTerm = polyCount == 0 ? null : polynomial.polynomialTerms.get(polyCount-1);
if ( thisTerm == null ) {
termList.add(polyTerm.clone());
polyCount--;
}
else if (polyTerm == null ) {
termList.add(thisTerm.clone());
thisCount--;
}
else if ( thisTerm.degree() == polyTerm.degree() ) {
Term t = thisTerm.add(polyTerm);
if ( t.coefficient != 0 ) {
termList.add(t);
}
thisCount--;
polyCount--;
}
else if ( thisTerm.degree() < polyTerm.degree() ) {
termList.add(thisTerm.clone());
thisCount--;
}
else {
termList.add(polyTerm.clone());
polyCount--;
}
}
return new Polynomial(termList);
}
public Polynomial add(Term term) {
List<Term> termList = new ArrayList<>();
boolean added = false;
for ( int index = 0 ; index < polynomialTerms.size() ; index++ ) {
Term currentTerm = polynomialTerms.get(index);
if ( currentTerm.exponent == term.exponent ) {
added = true;
if ( currentTerm.coefficient + term.coefficient != 0 ) {
termList.add(currentTerm.add(term));
}
}
else {
termList.add(currentTerm.clone());
}
}
if ( ! added ) {
termList.add(term.clone());
}
return new Polynomial(termList);
}
public Polynomial multiply(Term term) {
List<Term> termList = new ArrayList<>();
for ( int index = 0 ; index < polynomialTerms.size() ; index++ ) {
Term currentTerm = polynomialTerms.get(index);
termList.add(currentTerm.clone().multiply(term));
}
return new Polynomial(termList);
}
public Polynomial clone() {
List<Term> clone = new ArrayList<>();
for ( Term t : polynomialTerms ) {
clone.add(new Term(t.coefficient, t.exponent));
}
return new Polynomial(clone);
}
public long leadingCoefficient() {
// long coefficient = 0;
// long degree = Integer.MIN_VALUE;
// for ( Term t : polynomialTerms ) {
// if ( t.degree() > degree ) {
// coefficient = t.coefficient;
// degree = t.degree();
// }
// }
return polynomialTerms.get(0).coefficient;
}
public long degree() {
// long degree = Integer.MIN_VALUE;
// for ( Term t : polynomialTerms ) {
// if ( t.degree() > degree ) {
// degree = t.degree();
// }
// }
return polynomialTerms.get(0).exponent;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
boolean first = true;
for ( Term term : polynomialTerms ) {
if ( first ) {
sb.append(term);
first = false;
}
else {
sb.append(" ");
if ( term.coefficient > 0 ) {
sb.append("+ ");
sb.append(term);
}
else {
sb.append("- ");
sb.append(term.negate());
}
}
}
return sb.toString();
}
}
private static final class TermSorter implements Comparator<Term> {
@Override
public int compare(Term o1, Term o2) {
return (int) (o2.exponent - o1.exponent);
}
}
// Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage.
private static final class Term {
long coefficient;
long exponent;
public Term(long c, long e) {
coefficient = c;
exponent = e;
}
public Term clone() {
return new Term(coefficient, exponent);
}
public Term multiply(Term term) {
return new Term(coefficient * term.coefficient, exponent + term.exponent);
}
public Term add(Term term) {
if ( exponent != term.exponent ) {
throw new RuntimeException("ERROR 102: Exponents not equal.");
}
return new Term(coefficient + term.coefficient, exponent);
}
public Term negate() {
return new Term(-coefficient, exponent);
}
public long degree() {
return exponent;
}
@Override
public String toString() {
if ( coefficient == 0 ) {
return "0";
}
if ( exponent == 0 ) {
return "" + coefficient;
}
if ( coefficient == 1 ) {
if ( exponent == 1 ) {
return "x";
}
else {
return "x^" + exponent;
}
}
if ( exponent == 1 ) {
return coefficient + "x";
}
return coefficient + "x^" + exponent;
}
}
}
|
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.
| #Kotlin | Kotlin | // version 1.0.6
object RectangleCutter {
private var w: Int = 0
private var h: Int = 0
private var len: Int = 0
private var cnt: Long = 0
private lateinit var grid: ByteArray
private val next = IntArray(4)
private val dir = arrayOf(
intArrayOf(0, -1),
intArrayOf(-1, 0),
intArrayOf(0, 1),
intArrayOf(1, 0)
)
private fun walk(y: Int, x: Int) {
if (y == 0 || y == h || x == 0 || x == w) {
cnt += 2
return
}
val t = y * (w + 1) + x
grid[t]++
grid[len - t]++
(0..3).filter { grid[t + next[it]] == 0.toByte() }
.forEach { walk(y + dir[it][0], x + dir[it][1]) }
grid[t]--
grid[len - t]--
}
fun solve(hh: Int, ww: Int, recur: Boolean): Long {
var t: Int
h = hh
w = ww
if ((h and 1) != 0) {
t = w
w = h
h = t
}
if ((h and 1) != 0) return 0L
if (w == 1) return 1L
if (w == 2) return h.toLong()
if (h == 2) return w.toLong()
val cy = h / 2
val cx = w / 2
len = (h + 1) * (w + 1)
grid = ByteArray(len)
len--
next[0] = -1
next[1] = -w - 1
next[2] = 1
next[3] = w + 1
if (recur) cnt = 0L
for (x in cx + 1 until w) {
t = cy * (w + 1) + x
grid[t] = 1
grid[len - t] = 1
walk(cy - 1, x)
}
cnt++
if (h == w) cnt *= 2
else if ((w and 1) == 0 && recur) solve(w, h, false)
return cnt
}
}
fun main(args: Array<String>) {
for (y in 1..10) {
for (x in 1..y) {
if ((x and 1) == 0 || (y and 1) == 0) {
println("${"%2d".format(y)} x ${"%2d".format(x)}: ${RectangleCutter.solve(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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
#include "vbcompat.bi"
Sub split (s As String, sepList As String, result() As String, removeEmpty As Boolean = False)
If s = "" OrElse sepList = "" Then
Redim result(0)
result(0) = s
Return
End If
Dim As Integer i, j, count = 0, empty = 0, length
Dim As Integer position(Len(s) + 1)
position(0) = 0
For i = 0 To len(s) - 1
For j = 0 to Len(sepList) - 1
If s[i] = sepList[j] Then
count += 1
position(count) = i + 1
End If
Next j
Next i
Redim result(count)
If count = 0 Then
result(0) = s
Return
End If
position(count + 1) = len(s) + 1
For i = 1 To count + 1
length = position(i) - position(i - 1) - 1
result(i - 1 - empty) = Mid(s, position(i - 1) + 1, length)
If removeEmpty Andalso CBool(length = 0) Then empty += 1
Next
If empty > 0 Then Redim Preserve result(count - empty)
End Sub
Function parseDate(dt As String, zone As String) As Double
Dim result() As String
split dt, " ", result(), True
Dim As Long m, d, y, h, mn
Dim am As Boolean
Dim index As Integer
Select Case Lcase(result(0))
Case "january" : m = 1
Case "february" : m = 2
Case "march" : m = 3
Case "april" : m = 4
Case "may" : m = 5
Case "june" : m = 6
Case "july" : m = 7
Case "august" : m = 8
Case "september" : m = 9
Case "october" : m = 10
Case "november" : m = 11
Case "december" : m = 12
End Select
d = ValInt(result(1))
y = ValInt(result(2))
result(3) = LCase(result(3))
am = (Right(result(3), 2) = "am")
index = Instr(result(3), ":")
h = ValInt(Left(result(3), index - 1))
If Not am Then
h = h + 12
If h = 24 Then h = 12
End If
mn = ValInt(Mid(result(3), index + 1, 2))
zone = result(4)
Return DateSerial(y, m, d) + TimeSerial(h, mn, 0)
End Function
Dim zone As String
Dim ds As Double = parseDate("March 7 2009 7:30pm EST", zone)
Print "Original Date/Time : "; Format(ds, "mmmm d yyyy h:nnam/pm ") + " " + zone
ds = DateAdd("h", 12, ds)
Print "12 hours later : "; Format(ds, "mmmm d yyyy h:nnam/pm ") + " " + zone
' add 5 hours to convert EST to UTC
ds = DateAdd("h", 5, ds)
Print "Equiv to Date/Time : "; Format(ds, "mmmm d yyyy h:nnam/pm ") + " UTC"
Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #R | R | ## Linear congruential generator code not original -
## copied from
## http://www.rosettacode.org/wiki/Linear_congruential_generator#R
## altered to allow seed as an argument
library(gmp) # for big integers
rand_MS <- function(n = 1, seed = 1) {
a <- as.bigz(214013)
c <- as.bigz(2531011)
m <- as.bigz(2^31)
x <- rep(as.bigz(0), n)
x[1] <- (a * as.bigz(seed) + c) %% m
i <- 1
while (i < n) {
x[i+1] <- (a * x[i] + c) %% m
i <- i + 1
}
as.integer(x / 2^16)
}
## =============================
## New code follows:
## =============================
dealFreeCell <- function(seedNum) {
deck <- paste(rep(c("A",2,3,4,5,6,7,8,9,10,"J","Q","K"), each = 4), c("C","D","H","S"), sep = "")
cards = rand_MS(52,seedNum)
for (i in 52:1) {
cardToPick <- (cards[53-i]%% i)+1 # R indexes from 1, not 0
deck[c(cardToPick,i)] <- deck[c(i, cardToPick)]
}
deck <- rev(deck) # flip the deck to deal
deal = matrix(c(deck,NA,NA,NA,NA),ncol = 8, byrow = TRUE)
# using a matrix for simple printing, but requires filling with NA
# if implementing as a game, a list for each pile would make more sense
print(paste("Hand numer:",seedNum), quote = FALSE)
print(deal, quote = FALSE, na.print = "")
}
|
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #Racket | Racket | #lang racket
(module Linear_congruential_generator racket
;; taken from http://rosettacode.org/wiki/Linear_congruential_generator#Racket
;; w/o BSD generator
(require racket/generator)
(provide ms-rand)
(define (ms-update state_n)
(modulo (+ (* 214013 state_n) 2531011)
(expt 2 31)))
(define ((rand update ->rand) seed)
(generator () (let loop ([state_n seed])
(define state_n+1 (update state_n))
(yield (->rand state_n+1))
(loop state_n+1))))
(define ms-rand (rand ms-update (lambda (x) (quotient x (expt 2 16))))))
(require (submod "." Linear_congruential_generator))
;; Personally I prefer CDHS to the unicode characters (on an aesthetic basis,
;; rather than anything else. Plus it helps match with the examples given at the
;; head of the task.
(define suits "CDHS")
(define (initial-deck)
(for*/vector #:length 52
((face "A23456789TJQK")
(suit suits))
(cons face suit)))
;; srfi/43 has one of these, but is quick enough to reimplement!
(define (vector-swap! v i j)
(let ((t (vector-ref v i)))
(vector-set! v i (vector-ref v j))
(vector-set! v j t)))
(define (deal hand)
(define pack (initial-deck))
(define rnd (ms-rand hand))
(define (deal-nth-card pack-sz card-no deal)
(vector-swap! pack card-no (sub1 pack-sz))
(cons (vector-ref pack (sub1 pack-sz)) deal))
(let inner-deal ((pack-sz (vector-length pack)) (deal null))
(if (zero? pack-sz) (reverse deal) ;; we accumulated this backwards!
(inner-deal (sub1 pack-sz)
(deal-nth-card pack-sz (modulo (rnd) pack-sz) deal)))))
(define (present-deal hand)
(printf "Game #~a~%" hand)
(let inner-present-deal ((pile 0) (deck (deal hand)))
(unless (null? deck)
(printf "~a~a~a" (caar deck) (cdar deck)
(if (or (null? (cdr deck)) (= 7 (modulo pile 8))) "\n" " "))
(inner-present-deal (add1 pile) (cdr deck)))))
;; Run it so we get some output:
(present-deal 1)
(newline)
(present-deal 617) |
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.
| #Component_Pascal | Component Pascal |
MODULE DayOfWeek;
IMPORT DevCommanders, TextMappers, Dates, StdLog;
PROCEDURE XmastOnSun(s,e: INTEGER);
VAR
i: INTEGER;
d: Dates.Date;
BEGIN
i := s;d.day := 25;d.month := 12;
WHILE i < e DO
d.year := i;
IF Dates.DayOfWeek(d) = Dates.sunday THEN
StdLog.Int(i);StdLog.Ln
END;
INC(i)
END
END XmastOnSun;
PROCEDURE Do*;
VAR
s: TextMappers.Scanner;
r: ARRAY 2 OF INTEGER;
i: INTEGER;
BEGIN
s.ConnectTo(DevCommanders.par.text);
s.SetPos(DevCommanders.par.beg);
s.Scan;i := 0;
WHILE ~s.rider.eot DO
IF s.type = TextMappers.int THEN
r[i] := s.int; INC(i)
END;
s.Scan
END;
XmastOnSun(r[0],r[1]);
END Do;
END DayOfWeek.
|
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
| #Cach.C3.A9_ObjectScript | Caché ObjectScript | Class Utils.Check [ Abstract ]
{
ClassMethod CUSIP(x As %String) As %Boolean
{
SET x=$TRANSLATE(x," ")
// https://leiq.bus.umich.edu/res_codes_cusip.htm
IF x'?8UNP1N QUIT 0
SET cd=$EXTRACT(x,*), x=$EXTRACT(x,1,*-1), t=0
FOR i=1:1:$LENGTH(x) {
SET n=$EXTRACT(x,i)
IF n'=+n SET n=$CASE(n,"*":36,"@":37,"#":38,:$ASCII(n)-55)
IF i#2=0 SET n=n*2
SET t=t+(n\10)+(n#10)
}
QUIT cd=((10-(t#10))#10)
}
} |
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
| #Clojure | Clojure |
(defn- char->value
"convert the given char c to a value used to calculate the cusip check sum"
[c]
(let [int-char (int c)]
(cond
(and (>= int-char (int \0)) (<= int-char (int \9))) (- int-char 48)
(and (>= int-char (int \A)) (<= int-char (int \Z))) (- int-char 55)
(= c \*) 36
(= c \@) 37
(= c \#) 38
:else nil)))
(defn- calc-sum
"Calculate cusip sum. nil is returned for an invalid cusip."
[cusip]
(reduce
(fn [sum [i c]]
(if-let [v (char->value c)]
(let [v (if (= (mod i 2) 1) (* v 2) v)]
(+ sum (int (+ (/ v 10) (mod v 10)))))
(reduced nil)))
0
(map-indexed vector (subs cusip 0 8))))
(defn calc-cusip-checksum
"Given a valid 8 or 9 digit cusip, return the 9th checksum digit"
[cusip]
(when (>= (count cusip) 8)
(let [sum (calc-sum cusip)]
(when sum
(mod (- 10 (mod sum 10)) 10)))))
(defn is-valid-cusip9?
"predicate validating a 9 digit cusip."
[cusip9]
(when-let [checksum (and (= (count cusip9) 9)
(calc-cusip-checksum cusip9))]
(= (- (int (nth cusip9 8)) 48)
checksum)))
(defn rosetta-output
"show some nice output for the Rosetta Wiki"
[]
(doseq [cusip ["037833100" "17275R102" "38259P508" "594918104" "68389X106" "68389X105" "EXTRACRD8"
"EXTRACRD9" "BADCUSIP!" "683&9X106" "68389x105" "683$9X106" "68389}105" "87264ABE4"]]
(println cusip (if (is-valid-cusip9? cusip) "valid" "invalid"))))
|
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
| #360_Assembly | 360 Assembly | ******** Standard deviation of a population
STDDEV CSECT
USING STDDEV,R13
SAVEAREA B STM-SAVEAREA(R15)
DC 17F'0'
DC CL8'STDDEV'
STM STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15
SR R8,R8 s=0
SR R9,R9 ss=0
SR R4,R4 i=0
LA R6,1
LH R7,N
LOOPI BXH R4,R6,ENDLOOPI
LR R1,R4 i
BCTR R1,0
SLA R1,1
LH R5,T(R1)
ST R5,WW ww=t(i)
MH R5,=H'1000' w=ww*1000
AR R8,R5 s=s+w
LR R15,R5
MR R14,R5 w*w
AR R9,R15 ss=ss+w*w
LR R14,R8 s
SRDA R14,32
DR R14,R4 /i
ST R15,AVG avg=s/i
LR R14,R9 ss
SRDA R14,32
DR R14,R4 ss/i
LR R2,R15 ss/i
LR R15,R8 s
MR R14,R8 s*s
LR R3,R15
LR R15,R4 i
MR R14,R4 i*i
LR R1,R15
LA R14,0
LR R15,R3
DR R14,R1 (s*s)/(i*i)
SR R2,R15
LR R10,R2 std=ss/i-(s*s)/(i*i)
LR R11,R10 std
SRA R11,1 x=std/2
LR R12,R10 px=std
LOOPWHIL EQU *
CR R12,R11 while px<>=x
BE ENDWHILE
LR R12,R11 px=x
LR R15,R10 std
LA R14,0
DR R14,R12 /px
LR R1,R12 px
AR R1,R15 px+std/px
SRA R1,1 /2
LR R11,R1 x=(px+std/px)/2
B LOOPWHIL
ENDWHILE EQU *
LR R10,R11
CVD R4,P8 i
MVC C17,MASK17
ED C17,P8
MVC BUF+2(1),C17+15
L R1,WW
CVD R1,P8
MVC C17,MASK17
ED C17,P8
MVC BUF+10(1),C17+15
L R1,AVG
CVD R1,P8
MVC C18,MASK18
ED C18,P8
MVC BUF+17(5),C18+12
CVD R10,P8 std
MVC C18,MASK18
ED C18,P8
MVC BUF+31(5),C18+12
WTO MF=(E,WTOMSG)
B LOOPI
ENDLOOPI EQU *
L R13,4(0,R13)
LM R14,R12,12(R13)
XR R15,R15
BR R14
DS 0D
N DC H'8'
T DC H'2',H'4',H'4',H'4',H'5',H'5',H'7',H'9'
WW DS F
AVG DS F
P8 DS PL8
MASK17 DC C' ',13X'20',X'2120',C'-'
MASK18 DC C' ',10X'20',X'2120',C'.',3X'20',C'-'
C17 DS CL17
C18 DS CL18
WTOMSG DS 0F
DC H'80',XL2'0000'
BUF DC CL80'N=1 ITEM=1 AVG=1.234 STDDEV=1.234 '
YREGS
END STDDEV |
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
| #BBC_BASIC | BBC BASIC | daysow$ = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday"
months$ = "January February March April May June " + \
\ "July August September October November December"
date$ = TIME$
dayow% = (INSTR(daysow$, MID$(date$,1,3)) + 9) DIV 10
month% = (INSTR(months$, MID$(date$,8,3)) + 9) DIV 10
PRINT MID$(date$,12,4) "-" RIGHT$("0"+STR$month%,2) + "-" + MID$(date$,5,2)
PRINT FNrtrim(MID$(daysow$, dayow%*10-9, 10)) ", " ;
PRINT FNrtrim(MID$(months$, month%*10-9, 10)) " " ;
PRINT MID$(date$,5,2) ", " MID$(date$,12,4)
END
DEF FNrtrim(A$)
WHILE RIGHT$(A$) = " " A$ = LEFT$(A$) : ENDWHILE
= A$ |
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
| #Beads | Beads | // time_to_str(format, time, city, lang)
// format directives:
// [sun] - abbreviated weekday, e.g. Sun
// [sunday] - full weekday name, e.g. Sunday
// [jan] - abbrev month
// [january] - full month
// [day] - day of the month 1, 2, ..31
// [day2] - day of the month as two digits 01, 02, ..31
// [hour] - hour 00, 01, 03..23
// [hour12] - hour 1..12
// [julian] - day of the year 1..366
// [month] - month 1..12
// [month2] - month as two digits 01, 02, ..12
// [minute] - Minute 00, 01, 02..59
// [am] - AM or PM
// [sec] - second 00, 01, 02..61
// [msec] - millisecond 000...999
// [week sun] - week number of the year, sunday based (ranges 01-53, per ISO spec)
// [week mon] - week number of the year, monday based
// [year] - year with century 2024
// [year2] - year without century 00, 01, ..99
// [date] - default date format (e.g. Jan 14, 2015 )
// [date time] - (e.g. Jan 14, 2015 3:45 PM)
// [iso date] = [year]-[month2]-[day2], e.g. 2015-02-22
// [iso time] = [hour]:[minute]:[second], e.g. 18:06:05
|
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #Haskell | Haskell | findCullen :: Int -> Integer
findCullen n = toInteger ( n * 2 ^ n + 1 )
cullens :: [Integer]
cullens = map findCullen [1 .. 20]
woodalls :: [Integer]
woodalls = map (\i -> i - 2 ) cullens
main :: IO ( )
main = do
putStrLn "First 20 Cullen numbers:"
print cullens
putStrLn "First 20 Woodall numbers:"
print woodalls |
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #Julia | Julia | using Lazy
using Primes
cullen(n, two = BigInt(2)) = n * two^n + 1
woodall(n, two = BigInt(2)) = n * two^n - 1
primecullens = @>> Lazy.range() filter(n -> isprime(cullen(n)))
primewoodalls = @>> Lazy.range() filter(n -> isprime(woodall(n)))
println("First 20 Cullen numbers: ( n × 2**n + 1)\n", [cullen(n, 2) for n in 1:20]) # A002064
println("First 20 Woodall numbers: ( n × 2**n - 1)\n", [woodall(n, 2) for n in 1:20]) # A003261
println("\nFirst 5 Cullen primes: (in terms of n)\n", take(5, primecullens)) # A005849
println("\nFirst 12 Woodall primes: (in terms of n)\n", Int.(collect(take(12, primewoodalls)))) # A002234
|
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #Lua | Lua | function T(t) return setmetatable(t, {__index=table}) end
table.range = function(t,n) local s=T{} for i=1,n do s[i]=i end return s end
table.map = function(t,f) local s=T{} for i=1,#t do s[i]=f(t[i]) end return s end
function cullen(n) return (n<<n)+1 end
print("First 20 Cullen numbers:")
print(T{}:range(20):map(cullen):concat(" "))
function woodall(n) return (n<<n)-1 end
print("First 20 Woodall numbers:")
print(T{}:range(20):map(woodall):concat(" ")) |
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.
| #Cach.C3.A9_ObjectScript | Caché ObjectScript | Class Utils.Check [ Abstract ]
{
ClassMethod Damm(num As %Integer, mode As %Integer = 1) As %Integer
{
TRY {
I mode=0 RETURN ..Damm(num,2)=0
S res=0, str=num
S 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]
]
F i=1:1:$L(str) S res=table.%Get(res).%Get($E(str,i))
I mode=1 S res=num_res
} CATCH {
S res=""
}
Q res
}
} |
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.
| #Clojure | Clojure | (def tbl [[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]])
(defn damm? [digits]
(= 0 (reduce #(nth (nth tbl %1) %2) 0
(map #(Character/getNumericValue %) (seq digits))))) |
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.
| #11l | 11l | F currency(units, subunits)
R BigInt(units) * 100 + subunits
F currency_from_str(s)
V (units, subunits) = s.split(‘.’)
R BigInt(units) * 100 + Int(subunits)
F percentage(a, num, denom)
R (a * num * 10 I/ denom + 5) I/ 10
F to_str(c)
R String(c I/ 100)‘’‘.#02’.format(c % 100)
V hamburgers = currency(5, 50) * 4'000'000'000'000'000
V milkshakes = currency_from_str(‘2.86’) * 2
V beforeTax = hamburgers + milkshakes
V tax = percentage(beforeTax, 765, 10'000)
V total = beforeTax + tax
V maxlen = max(to_str(beforeTax).len, to_str(tax).len, to_str(total).len)
print(‘Total price before tax: ’to_str(beforeTax).rjust(maxlen))
print(‘Tax: ’to_str(tax).rjust(maxlen))
print(‘Total with tax: ’to_str(total).rjust(maxlen)) |
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.
| #Ceylon | Ceylon | shared void run() {
function divide(Integer x, Integer y) => x / y;
value partsOf120 = curry(divide)(120);
print("half of 120 is ``partsOf120(2)``
a third is ``partsOf120(3)``
and a quarter is ``partsOf120(4)``");
} |
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.
| #Clojure | Clojure | (def plus-a-hundred (partial + 100))
(assert (=
(plus-a-hundred 1)
101))
|
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
| #6502_Assembly | 6502 Assembly | sta $1900
stx $1901
sty $1902 |
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. | #Julia | Julia | using Primes, Polynomials
# memoize cache for recursive calls
const cyclotomics = Dict([1 => Poly([big"-1", big"1"]), 2 => Poly([big"1", big"1"])])
# get all integer divisors of an integer, except itself
function divisors(n::Integer)
f = [one(n)]
for (p, e) in factor(n)
f = reduce(vcat, [f * p^j for j in 1:e], init=f)
end
return resize!(f, length(f) - 1)
end
"""
cyclotomic(n::Integer)
Calculate the n -th cyclotomic polynomial.
See wikipedia article at bottom of section /wiki/Cyclotomic_polynomial#Fundamental_tools
The algorithm is reliable but slow for large n > 1000.
"""
function cyclotomic(n::Integer)
if haskey(cyclotomics, n)
c = cyclotomics[n]
elseif isprime(n)
c = Poly(ones(BigInt, n))
cyclotomics[n] = c
else # recursive formula seen in wikipedia article
c = Poly([big"-1"; zeros(BigInt, n - 1); big"1"])
for d in divisors(n)
c ÷= cyclotomic(d)
end
cyclotomics[n] = c
end
return c
end
println("First 30 cyclotomic polynomials:")
for i in 1:30
println(rpad("$i: ", 5), cyclotomic(BigInt(i)))
end
const dig = zeros(BigInt, 10)
for i in 1:1000000
if all(x -> x != 0, dig)
break
end
for coef in coeffs(cyclotomic(i))
x = abs(coef)
if 0 < x < 11 && dig[Int(x)] == 0
dig[Int(x)] = coef < 0 ? -i : i
end
end
end
for (i, n) in enumerate(dig)
println("The cyclotomic polynomial Φ(", abs(n), ") has a coefficient that is ", n < 0 ? -i : i)
end
|
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.
| #Lua | Lua | function array1D(w, d)
local t = {}
for i=1,w do
table.insert(t, d)
end
return t
end
function array2D(h, w, d)
local t = {}
for i=1,h do
table.insert(t, array1D(w, d))
end
return t
end
function push(s, v)
s[#s + 1] = v
end
function pop(s)
return table.remove(s, #s)
end
function empty(s)
return #s == 0
end
DIRS = {
{0, -1},
{-1, 0},
{0, 1},
{1, 0}
}
function printResult(aa)
for i,u in pairs(aa) do
io.write("[")
for j,v in pairs(u) do
if j > 1 then
io.write(", ")
end
io.write(v)
end
print("]")
end
end
function cutRectangle(w, h)
if w % 2 == 1 and h % 2 == 1 then
return nil
end
local grid = array2D(h, w, 0)
local stack = {}
local half = math.floor((w * h) / 2)
local bits = 2 ^ half - 1
while bits > 0 do
for i=1,half do
local r = math.floor((i - 1) / w)
local c = (i - 1) % w
if (bits & (1 << (i - 1))) ~= 0 then
grid[r + 1][c + 1] = 1
else
grid[r + 1][c + 1] = 0
end
grid[h - r][w - c] = 1 - grid[r + 1][c + 1]
end
push(stack, 0)
grid[1][1] = 2
local count = 1
while not empty(stack) do
local pos = pop(stack)
local r = math.floor(pos / w)
local c = pos % w
for i,dir in pairs(DIRS) do
local nextR = r + dir[1]
local nextC = c + dir[2]
if nextR >= 0 and nextR < h and nextC >= 0 and nextC < w then
if grid[nextR + 1][nextC + 1] == 1 then
push(stack, nextR * w + nextC)
grid[nextR + 1][nextC + 1] = 2
count = count + 1
end
end
end
end
if count == half then
printResult(grid)
print()
end
-- loop end
bits = bits - 2
end
end
cutRectangle(2, 2)
cutRectangle(4, 3) |
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.
| #Frink | Frink |
### MMM dd yyyy h:mma ###
d = parseDate["March 7 2009 7:30pm EST"]
println[d + 12 hours -> Eastern]
println[d + 12 hours -> Switzerland] // Extra credit
|
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.
| #FunL | FunL | import time.{TimeZone, Date, SimpleDateFormat, Hour}
pattern = SimpleDateFormat( 'MMMM d yyyy h:mma zzz' )
date = pattern.parse( 'March 7 2009 7:30pm EST' )
later = Date( date.getTime() + 12 Hour )
println( pattern.format(later) ) // Eastern Daylight Time
pattern.setTimeZone( TimeZone.getTimeZone('America/Los_Angeles') )
println( pattern.format(later) ) // U.S. Pacific Time |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #Raku | Raku | sub dealgame ($game-number = 1) {
sub ms-lcg-method($seed = $game-number) { ( 214013 * $seed + 2531011 ) % 2**31 }
# lazy list of the random sequence
my @ms-lcg = |(&ms-lcg-method ... *).map: * +> 16;
constant CardBlock = '🂠'.ord;
my @deck = gather for flat(1..11,13,14) X+ (48,32...0) -> $off {
take chr CardBlock + $off;
}
my @game = gather while @deck {
@deck[@ms-lcg.shift % @deck, @deck-1] .= reverse;
take @deck.pop;
}
say "Game #$game-number";
say @game.splice(0, 8 min +@game) while @game;
}
dealgame;
dealgame 617; |
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.
| #Cowgol | Cowgol | include "cowgol.coh";
sub weekday(year: uint16, month: uint8, day: uint8): (wd: uint8) is
if month < 3 then
month := month + 10;
year := year - 1;
else
month := month - 2;
end if;
var c := year / 100;
var y := year % 100;
var z := (26 * month as uint16 - 2) / 10;
z := z + day as uint16 + y + (y / 4) + (c / 4) - 2 * c + 777;
wd := (z % 7) as uint8;
end sub;
var year: uint16 := 2008;
while year <= 2121 loop
if weekday(year, 12, 25) == 0 then
print_i16(year);
print_nl();
end if;
year := year + 1;
end loop; |
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.
| #D | D | void main() {
import std.stdio, std.range, std.algorithm, std.datetime;
writeln("Christmas comes on a Sunday in the years:\n",
iota(2008, 2122)
.filter!(y => Date(y, 12, 25).dayOfWeek == DayOfWeek.sun));
} |
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
| #CLU | CLU | valid_cusip = proc (s: string) returns (bool)
own chars: string := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#"
if string$size(s) ~= 9 then return(false) end
sum: int := 0
for i: int in int$from_to(1,8) do
v: int := string$indexc(s[i], chars)-1
if v<0 then return(false) end
if i//2=0 then v := v*2 end
sum := sum + v/10 + v//10
end
check: int := (10 - sum // 10) // 10
return(check = string$indexc(s[9], chars)-1)
end valid_cusip
start_up = proc ()
po: stream := stream$primary_output()
cusips: array[string] := array[string]$[
"037833100",
"17275R102",
"38259P508",
"594918104",
"68389X106",
"68389X105"
]
for cusip: string in array[string]$elements(cusips) do
stream$puts(po, cusip || ": ")
if valid_cusip(cusip)
then stream$putl(po, "valid")
else stream$putl(po, "invalid")
end
end
end start_up |
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
| #Common_Lisp | Common Lisp | (defun char->value (c)
(cond ((digit-char-p c 36))
((char= c #\*) 36)
((char= c #\@) 37)
((char= c #\#) 38)
(t (error "Invalid character: ~A" c))))
(defun cusip-p (cusip)
(and (= 9 (length cusip))
(loop for i from 1 to 8
for c across cusip
for v = (char->value c)
when (evenp i)
do (setf v (* 2 v))
sum (multiple-value-bind (quot rem) (floor v 10)
(+ quot rem))
into sum
finally (return (eql (digit-char-p (char cusip 8))
(mod (- 10 (mod sum 10)) 10))))))
(defun main ()
(dolist (cusip '("037833100" "17275R102" "38259P508" "594918104" "68389X106" "68389X105"))
(format t "~A: ~A~%" cusip (cusip-p cusip)))) |
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
| #Action.21 | Action! | INCLUDE "H6:REALMATH.ACT"
REAL sum,sum2
INT count
PROC Calc(REAL POINTER x,sd)
REAL tmp1,tmp2,tmp3
RealAdd(sum,x,tmp1) ;tmp1=sum+x
RealAssign(tmp1,sum) ;sum=sum+x
RealMult(x,x,tmp1) ;tmp1=x*x
RealAdd(sum2,tmp1,tmp2) ;tmp2=sum2+x*x
RealAssign(tmp2,sum2) ;sum2=sum2+x*x
count==+1
IF count=0 THEN
IntToReal(0,sd) ;sd=0
ELSE
IntToReal(count,tmp1)
RealMult(sum,sum,tmp2) ;tmp2=sum*sum
RealDiv(tmp2,tmp1,tmp3) ;tmp3=sum*sum/count
RealDiv(tmp3,tmp1,tmp2) ;tmp2=sum*sum/count/count
RealDiv(sum2,tmp1,tmp3) ;tmp3=sum2/count
RealSub(tmp3,tmp2,tmp1) ;tmp1=sum2/count-sum*sum/count/count
Sqrt(tmp1,sd) ;sd=sqrt(sum2/count-sum*sum/count/count)
FI
RETURN
PROC Main()
INT ARRAY values=[2 4 4 4 5 5 7 9]
INT i
REAL x,sd
Put(125) PutE() ;clear screen
MathInit()
IntToReal(0,sum)
IntToReal(0,sum2)
count=0
FOR i=0 TO 7
DO
IntToReal(values(i),x)
Calc(x,sd)
Print("x=") PrintR(x)
Print(" sum=") PrintR(sum)
Print(" sd=") PrintRE(sd)
OD
RETURN |
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
| #C | C | #include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define MAX_BUF 50
int main(void)
{
char buf[MAX_BUF];
time_t seconds = time(NULL);
struct tm *now = localtime(&seconds);
const char *months[] = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
const char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday","Thursday","Friday","Saturday"};
(void) printf("%d-%d-%d\n", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday);
(void) printf("%s, %s %d, %d\n",days[now->tm_wday], months[now->tm_mon],
now->tm_mday, now->tm_year + 1900);
/* using the strftime (the result depends on the locale) */
(void) strftime(buf, MAX_BUF, "%A, %B %e, %Y", now);
(void) printf("%s\n", buf);
return EXIT_SUCCESS;
} |
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #Perl | Perl | use strict;
use warnings;
use bigint;
use ntheory 'is_prime';
use constant Inf => 1e10;
sub cullen {
my($n,$c) = @_;
($n * 2**$n) + $c;
}
my($m,$n);
($m,$n) = (20,0);
print "First $m Cullen numbers:\n";
print do { $n < $m ? (++$n and cullen($_,1) . ' ') : last } for 1 .. Inf;
($m,$n) = (20,0);
print "\n\nFirst $m Woodall numbers:\n";
print do { $n < $m ? (++$n and cullen($_,-1) . ' ') : last } for 1 .. Inf;
($m,$n) = (5,0);
print "\n\nFirst $m Cullen primes: (in terms of n)\n";
print do { $n < $m ? (!!is_prime(cullen $_,1) and ++$n and "$_ ") : last } for 1 .. Inf;
($m,$n) = (12,0);
print "\n\nFirst $m Woodall primes: (in terms of n)\n";
print do { $n < $m ? (!!is_prime(cullen $_,-1) and ++$n and "$_ ") : last } for 1 .. Inf; |
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.
| #CLU | CLU | % Verify that the Damm check digit of a string of digits is correct.
% Signals 'bad_format' if the string contains non-digits.
damm = proc (s: string) returns (bool) signals (bad_format)
ai = array[int]
aai = array[ai]
own damm_table: aai := aai$[0:
ai$[0: 0,3,1,7,5,9,8,6,4,2],
ai$[0: 7,0,9,2,1,5,4,8,6,3],
ai$[0: 4,2,0,6,8,7,1,3,5,9],
ai$[0: 1,7,5,0,9,8,3,4,2,6],
ai$[0: 6,1,2,3,0,4,5,9,7,8],
ai$[0: 3,6,7,4,2,0,9,5,8,1],
ai$[0: 5,8,6,9,7,2,0,1,3,4],
ai$[0: 8,9,4,5,3,6,2,0,1,7],
ai$[0: 9,4,3,8,6,1,7,2,0,5],
ai$[0: 2,5,8,1,4,3,6,7,9,0]
]
interim: int := 0
for c: char in string$chars(s) do
d: int := int$parse(string$c2s(c)) resignal bad_format
interim := damm_table[interim][d]
end
return(interim = 0)
end damm
% Checks
start_up = proc ()
po: stream := stream$primary_output()
tests: sequence[string] := sequence[string]$[
"5724", "5727", "112946", "112949"
]
for test: string in sequence[string]$elements(tests) do
stream$puts(po, test || ": ")
if damm(test) then
stream$putl(po, "pass")
else
stream$putl(po, "fail")
end
end
end start_up |
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.
| #Cowgol | Cowgol | include "cowgol.coh";
# Damm test on number given as ASCII string
# Returns check digit
sub damm(num: [uint8]): (chk: uint8) is
var table: uint8[] := {
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
};
chk := 0;
while [num] != 0 loop
chk := table[(chk<<1) + (chk<<3) + ([num] - '0')];
num := @next num;
end loop;
end sub;
# Test and print
sub test(num: [uint8]) is
print(num);
print(":");
if damm(num) == 0 then
print("Pass\n");
else
print("Fail\n");
end if;
end sub;
test("5724");
test("5727");
test("112946");
test("112949"); |
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.
| #Ada | Ada | with Ada.Text_IO;
procedure Currency is
type Dollar is delta 0.01 range 0.0 .. 24_000_000_000_000_000.0;
package Dollar_IO is new Ada.Text_IO.Fixed_IO(Dollar);
hamburger_cost : constant := 5.50;
milkshake_cost : constant := 2.86;
tax_rate : constant := 0.0765;
total_cost : constant := hamburger_cost * 4_000_000_000_000_000.0 + milkshake_cost * 2;
total_tax : constant := total_cost * tax_rate;
total_with_tax : constant := total_cost + total_tax;
begin
Ada.Text_IO.Put("Price before tax:");
Dollar_IO.Put(total_cost);
Ada.Text_IO.New_Line;
Ada.Text_IO.Put("Tax: ");
Dollar_IO.Put(total_tax);
Ada.Text_IO.New_Line;
Ada.Text_IO.Put("Total: ");
Dollar_IO.Put(total_with_tax);
Ada.Text_IO.New_Line;
end Currency; |
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.
| #ALGOL_68 | ALGOL 68 | BEGIN
# currency calculations #
# simple fixed point type, LONG INT is 64-bit in Algol 68G #
MODE FIXED = STRUCT( LONG INT value
, INT decimals
, INT fraction modulus
);
# make CURRENCY a synonym for FIXED #
MODE CURRENCY = FIXED;
# dyadic operator so we can write e.g. 5 DOLLARS 50 to construct #
# a CURRENCY value with 2 decimal places #
PRIO DOLLARS = 9;
OP DOLLARS = ( LONG INT v, INT dp )CURRENCY: ( ( v * 100 ) + dp, 2, 100 );
OP DOLLARS = ( INT v, INT dp )CURRENCY: LENG v DOLLARS dp;
# issues an error message and stops the program if a has a different #
# number of decimal places to b #
PROC check compatible = ( CURRENCY a, b )VOID:
IF decimals OF a /= decimals OF b THEN print( ( "Incompatible CURRENCY values", newline ) ); stop FI;
# operators to multiply CURRENCY values by integers #
OP * = ( CURRENCY v, LONG INT m )CURRENCY: ( value OF v * m, decimals OF v, fraction modulus OF v );
OP * = ( CURRENCY v, INT m )CURRENCY: v * LENG m;
# returns the CURRENCY value a + b #
OP + = ( CURRENCY a, CURRENCY b )CURRENCY:
BEGIN
check compatible( a, b );
( value OF a + value OF b, decimals OF a, fraction modulus OF a )
END # + # ;
# multiplies the CURRENCY value a by the FIXED value b, #
# rounding the result to the decimal places of a #
OP * = ( CURRENCY a, FIXED b )CURRENCY:
BEGIN
LONG INT result := ( value OF a * value OF b );
IF decimals OF b > 0 THEN
INT d = fraction modulus OF b;
LONG INT abs result := ABS result;
INT extra places = SHORTEN ( abs result MOD d );
abs result OVERAB d;
IF extra places >= d OVER 2 THEN abs result +:= 1 FI;
IF result < 0 THEN result := - abs result ELSE result := abs result FI
FI;
( result, decimals OF a, fraction modulus OF a )
END # * # ;
# converts a FIXED value to a STRING with the appropriate number of #
# decimal places #
OP TOSTRING = ( FIXED v )STRING:
IF decimals OF v < 1 THEN
whole( value OF v, 0 )
ELSE
INT d = fraction modulus OF v;
STRING result := whole( value OF v OVER d, 0 );
STRING dp := whole( ( ABS value OF v ) MOD d, - decimals OF v );
FOR i FROM LWB dp TO UPB dp DO IF dp[ i ] = " " THEN dp[ i ] := "0" FI OD;
result + "." + dp
FI # TOSTRING # ;
# Task calculations #
CURRENCY hb = 5 DOLLARS 50 * LONG 4000000000000000;
CURRENCY ms = 2 DOLLARS 86 * 2;
FIXED rate = ( 765, 4, 10 000 ); # 0.0765 #
CURRENCY net = hb + ms;
CURRENCY tax = net * rate;
CURRENCY total = net + tax;
print( ( "before tax: ", TOSTRING net, newline ) );
print( ( "tax: ", TOSTRING tax, newline ) );
print( ( "total: ", TOSTRING total, newline ) )
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.
| #Common_Lisp | Common Lisp | (defun curry (function &rest args-1)
(lambda (&rest args-2)
(apply function (append args-1 args-2))))
|
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.
| #Crystal | Crystal | add_things = ->(x1 : Int32, x2 : Int32, x3 : Int32) { x1 + x2 + x3 }
add_curried = add_things.partial(2, 3)
add_curried.call(4) #=> 9
def add_two_things(x1)
return ->(x2 : Int32) {
->(x3 : Int32) { x1 + x2 + x3 }
}
end
add13 = add_two_things(3).call(10)
add13.call(5) #=> 18 |
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
| #68000_Assembly | 68000 Assembly | MOVE.L #$12345678,$100000 |
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
| #8086_Assembly | 8086 Assembly | .model small ;specify memory model to use
.stack 1024 ;set up stack
.data ;data segment
UserRam BYTE 256 DUP (0) ;allocate 256 bytes of user RAM, initialized to zero.
tempByte equ UserRam ;define a few labels for clarity
tempWord equ UserRam+2
tempLong_LoWord equ UserRam+4
tempLong_HiWord equ UserRam+6
.code ;code segment
mov ax, @data
mov ds, ax
mov ax, @code
mov es, ax ;load segment registers with the appropriate segments.
; now there is no need to use "mov ax, seg UserRam" since we've already loaded the data segment into DS
;store an integer value into memory
mov ax, 1000h ;load the value 0x1000 into AX
mov word ptr [ds:tempLong_LoWord],ax ;store 0x1000 into tempLong_LoWord
mov ax, 0040h ;the 8086 is 16-bit so we have to load the pieces separately.
mov word ptr [ds:tempLong_HiWord],ax ;store 0x0040 into tempLong_HiWord
;get the address of a variable
mov ax, tempLong_LoWord ;without "word ptr" and brackets, the assembler interprets a label as a constant. |
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
| #Action.21 | Action! | DEFINE FIRST="12345"
DEFINE SECOND="54321"
DEFINE PTR="CARD"
PROC Main()
PTR base,copy=base
PrintF("Address of base variable: %H%E",@base)
PrintF("Address of copy variable: %H%E",@copy)
PutE()
PrintF("Assign %U value to base variable%E",FIRST)
base=FIRST
PrintF("Value of base variable: %U%E",base)
PrintF("Value of copy variable: %U%E",copy)
PutE()
PrintF("Assign %U value to base variable%E",SECOND)
base=SECOND
PrintF("Value of base variable: %U%E",base)
PrintF("Value of copy variable: %U%E",copy)
RETURN |
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. | #Kotlin | Kotlin | import java.util.TreeMap
import kotlin.math.abs
import kotlin.math.pow
import kotlin.math.sqrt
private const val algorithm = 2
fun main() {
println("Task 1: cyclotomic polynomials for n <= 30:")
for (i in 1..30) {
val p = cyclotomicPolynomial(i)
println("CP[$i] = $p")
}
println()
println("Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:")
var n = 0
for (i in 1..10) {
while (true) {
n++
val cyclo = cyclotomicPolynomial(n)
if (cyclo!!.hasCoefficientAbs(i)) {
println("CP[$n] has coefficient with magnitude = $i")
n--
break
}
}
}
}
private val COMPUTED: MutableMap<Int, Polynomial> = HashMap()
private fun cyclotomicPolynomial(n: Int): Polynomial? {
if (COMPUTED.containsKey(n)) {
return COMPUTED[n]
}
if (n == 1) {
// Polynomial: x - 1
val p = Polynomial(1, 1, -1, 0)
COMPUTED[1] = p
return p
}
val factors = getFactors(n)
if (factors.containsKey(n)) {
// n prime
val termList: MutableList<Term> = ArrayList()
for (index in 0 until n) {
termList.add(Term(1, index.toLong()))
}
val cyclo = Polynomial(termList)
COMPUTED[n] = cyclo
return cyclo
} else if (factors.size == 2 && factors.containsKey(2) && factors[2] == 1 && factors.containsKey(n / 2) && factors[n / 2] == 1) {
// n = 2p
val prime = n / 2
val termList: MutableList<Term> = ArrayList()
var coeff = -1
for (index in 0 until prime) {
coeff *= -1
termList.add(Term(coeff.toLong(), index.toLong()))
}
val cyclo = Polynomial(termList)
COMPUTED[n] = cyclo
return cyclo
} else if (factors.size == 1 && factors.containsKey(2)) {
// n = 2^h
val h = factors[2]!!
val termList: MutableList<Term> = ArrayList()
termList.add(Term(1, 2.0.pow((h - 1).toDouble()).toLong()))
termList.add(Term(1, 0))
val cyclo = Polynomial(termList)
COMPUTED[n] = cyclo
return cyclo
} else if (factors.size == 1 && !factors.containsKey(n)) {
// n = p^k
var p = 0
for (prime in factors.keys) {
p = prime
}
val k = factors[p]!!
val termList: MutableList<Term> = ArrayList()
for (index in 0 until p) {
termList.add(Term(1, (index * p.toDouble().pow(k - 1.toDouble()).toInt()).toLong()))
}
val cyclo = Polynomial(termList)
COMPUTED[n] = cyclo
return cyclo
} else if (factors.size == 2 && factors.containsKey(2)) {
// n = 2^h * p^k
var p = 0
for (prime in factors.keys) {
if (prime != 2) {
p = prime
}
}
val termList: MutableList<Term> = ArrayList()
var coeff = -1
val twoExp = 2.0.pow((factors[2]!!) - 1.toDouble()).toInt()
val k = factors[p]!!
for (index in 0 until p) {
coeff *= -1
termList.add(Term(coeff.toLong(), (index * twoExp * p.toDouble().pow(k - 1.toDouble()).toInt()).toLong()))
}
val cyclo = Polynomial(termList)
COMPUTED[n] = cyclo
return cyclo
} else if (factors.containsKey(2) && n / 2 % 2 == 1 && n / 2 > 1) {
// CP(2m)[x] = CP(-m)[x], n odd integer > 1
val cycloDiv2 = cyclotomicPolynomial(n / 2)
val termList: MutableList<Term> = ArrayList()
for (term in cycloDiv2!!.polynomialTerms) {
termList.add(if (term.exponent % 2 == 0L) term else term.negate())
}
val cyclo = Polynomial(termList)
COMPUTED[n] = cyclo
return cyclo
}
// General Case
return when (algorithm) {
0 -> {
// Slow - uses basic definition.
val divisors = getDivisors(n)
// Polynomial: ( x^n - 1 )
var cyclo = Polynomial(1, n, -1, 0)
for (i in divisors) {
val p = cyclotomicPolynomial(i)
cyclo = cyclo.divide(p)
}
COMPUTED[n] = cyclo
cyclo
}
1 -> {
// Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor
val divisors = getDivisors(n)
var maxDivisor = Int.MIN_VALUE
for (div in divisors) {
maxDivisor = maxDivisor.coerceAtLeast(div)
}
val divisorsExceptMax: MutableList<Int> = ArrayList()
for (div in divisors) {
if (maxDivisor % div != 0) {
divisorsExceptMax.add(div)
}
}
// Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor
var cyclo = Polynomial(1, n, -1, 0).divide(Polynomial(1, maxDivisor, -1, 0))
for (i in divisorsExceptMax) {
val p = cyclotomicPolynomial(i)
cyclo = cyclo.divide(p)
}
COMPUTED[n] = cyclo
cyclo
}
2 -> {
// Fastest
// Let p ; q be primes such that p does not divide n, and q q divides n.
// Then CP(np)[x] = CP(n)[x^p] / CP(n)[x]
var m = 1
var cyclo = cyclotomicPolynomial(m)
val primes = factors.keys.toMutableList()
primes.sort()
for (prime in primes) {
// CP(m)[x]
val cycloM = cyclo
// Compute CP(m)[x^p].
val termList: MutableList<Term> = ArrayList()
for (t in cycloM!!.polynomialTerms) {
termList.add(Term(t.coefficient, t.exponent * prime))
}
cyclo = Polynomial(termList).divide(cycloM)
m *= prime
}
// Now, m is the largest square free divisor of n
val s = n / m
// Compute CP(n)[x] = CP(m)[x^s]
val termList: MutableList<Term> = ArrayList()
for (t in cyclo!!.polynomialTerms) {
termList.add(Term(t.coefficient, t.exponent * s))
}
cyclo = Polynomial(termList)
COMPUTED[n] = cyclo
cyclo
}
else -> {
throw RuntimeException("ERROR 103: Invalid algorithm.")
}
}
}
private fun getDivisors(number: Int): List<Int> {
val divisors: MutableList<Int> = ArrayList()
val sqrt = sqrt(number.toDouble()).toLong()
for (i in 1..sqrt) {
if (number % i == 0L) {
divisors.add(i.toInt())
val div = (number / i).toInt()
if (div.toLong() != i && div != number) {
divisors.add(div)
}
}
}
return divisors
}
private fun crutch(): MutableMap<Int, Map<Int, Int>> {
val allFactors: MutableMap<Int, Map<Int, Int>> = TreeMap()
val factors: MutableMap<Int, Int> = TreeMap()
factors[2] = 1
allFactors[2] = factors
return allFactors
}
private val allFactors = crutch()
var MAX_ALL_FACTORS = 100000
fun getFactors(number: Int): Map<Int, Int> {
if (allFactors.containsKey(number)) {
return allFactors[number]!!
}
val factors: MutableMap<Int, Int> = TreeMap()
if (number % 2 == 0) {
val factorsDivTwo = getFactors(number / 2)
factors.putAll(factorsDivTwo)
factors.merge(2, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
if (number < MAX_ALL_FACTORS) allFactors[number] = factors
return factors
}
val sqrt = sqrt(number.toDouble()).toLong()
var i = 3
while (i <= sqrt) {
if (number % i == 0) {
factors.putAll(getFactors(number / i))
factors.merge(i, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
if (number < MAX_ALL_FACTORS) {
allFactors[number] = factors
}
return factors
}
i += 2
}
factors[number] = 1
if (number < MAX_ALL_FACTORS) {
allFactors[number] = factors
}
return factors
}
private class Polynomial {
val polynomialTerms: MutableList<Term>
// Format - coeff, exp, coeff, exp, (repeating in pairs) . . .
constructor(vararg values: Int) {
require(values.size % 2 == 0) { "ERROR 102: Polynomial constructor. Length must be even. Length = " + values.size }
polynomialTerms = mutableListOf()
var i = 0
while (i < values.size) {
val t = Term(values[i].toLong(), values[i + 1].toLong())
polynomialTerms.add(t)
i += 2
}
polynomialTerms.sortWith(TermSorter())
}
constructor() {
// zero
polynomialTerms = ArrayList()
polynomialTerms.add(Term(0, 0))
}
fun hasCoefficientAbs(coeff: Int): Boolean {
for (term in polynomialTerms) {
if (abs(term.coefficient) == coeff.toLong()) {
return true
}
}
return false
}
constructor(termList: MutableList<Term>) {
if (termList.isEmpty()) {
// zero
termList.add(Term(0, 0))
} else {
// Remove zero terms if needed
termList.removeIf { t -> t.coefficient == 0L }
}
if (termList.size == 0) {
// zero
termList.add(Term(0, 0))
}
polynomialTerms = termList
polynomialTerms.sortWith(TermSorter())
}
fun divide(v: Polynomial?): Polynomial {
var q = Polynomial()
var r = this
val lcv = v!!.leadingCoefficient()
val dv = v.degree()
while (r.degree() >= v.degree()) {
val lcr = r.leadingCoefficient()
val s = lcr / lcv // Integer division
val term = Term(s, r.degree() - dv)
q = q.add(term)
r = r.add(v.multiply(term.negate()))
}
return q
}
fun add(polynomial: Polynomial): Polynomial {
val termList: MutableList<Term> = ArrayList()
var thisCount = polynomialTerms.size
var polyCount = polynomial.polynomialTerms.size
while (thisCount > 0 || polyCount > 0) {
val thisTerm = if (thisCount == 0) null else polynomialTerms[thisCount - 1]
val polyTerm = if (polyCount == 0) null else polynomial.polynomialTerms[polyCount - 1]
when {
thisTerm == null -> {
termList.add(polyTerm!!.clone())
polyCount--
}
polyTerm == null -> {
termList.add(thisTerm.clone())
thisCount--
}
thisTerm.degree() == polyTerm.degree() -> {
val t = thisTerm.add(polyTerm)
if (t.coefficient != 0L) {
termList.add(t)
}
thisCount--
polyCount--
}
thisTerm.degree() < polyTerm.degree() -> {
termList.add(thisTerm.clone())
thisCount--
}
else -> {
termList.add(polyTerm.clone())
polyCount--
}
}
}
return Polynomial(termList)
}
fun add(term: Term): Polynomial {
val termList: MutableList<Term> = ArrayList()
var added = false
for (currentTerm in polynomialTerms) {
if (currentTerm.exponent == term.exponent) {
added = true
if (currentTerm.coefficient + term.coefficient != 0L) {
termList.add(currentTerm.add(term))
}
} else {
termList.add(currentTerm.clone())
}
}
if (!added) {
termList.add(term.clone())
}
return Polynomial(termList)
}
fun multiply(term: Term): Polynomial {
val termList: MutableList<Term> = ArrayList()
for (currentTerm in polynomialTerms) {
termList.add(currentTerm.clone().multiply(term))
}
return Polynomial(termList)
}
fun leadingCoefficient(): Long {
return polynomialTerms[0].coefficient
}
fun degree(): Long {
return polynomialTerms[0].exponent
}
override fun toString(): String {
val sb = StringBuilder()
var first = true
for (term in polynomialTerms) {
if (first) {
sb.append(term)
first = false
} else {
sb.append(" ")
if (term.coefficient > 0) {
sb.append("+ ")
sb.append(term)
} else {
sb.append("- ")
sb.append(term.negate())
}
}
}
return sb.toString()
}
}
private class TermSorter : Comparator<Term> {
override fun compare(o1: Term, o2: Term): Int {
return (o2.exponent - o1.exponent).toInt()
}
}
// Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage.
private class Term(var coefficient: Long, var exponent: Long) {
fun clone(): Term {
return Term(coefficient, exponent)
}
fun multiply(term: Term): Term {
return Term(coefficient * term.coefficient, exponent + term.exponent)
}
fun add(term: Term): Term {
if (exponent != term.exponent) {
throw RuntimeException("ERROR 102: Exponents not equal.")
}
return Term(coefficient + term.coefficient, exponent)
}
fun negate(): Term {
return Term(-coefficient, exponent)
}
fun degree(): Long {
return exponent
}
override fun toString(): String {
if (coefficient == 0L) {
return "0"
}
if (exponent == 0L) {
return "" + coefficient
}
if (coefficient == 1L) {
return if (exponent == 1L) {
"x"
} else {
"x^$exponent"
}
}
return if (exponent == 1L) {
coefficient.toString() + "x"
} else coefficient.toString() + "x^" + exponent
}
} |
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.
| #Nim | Nim | import strformat
var
w, h: int
grid: seq[byte]
next: array[4, int]
count: int
const Dirs = [[0, -1], [-1, 0], [0, 1], [1, 0]]
template odd(n: int): bool = (n and 1) != 0
#------------------------------------------------------------------------------
proc walk(y, x: int) =
if y == 0 or y == h or x == 0 or x == w:
inc count, 2
return
let t = y * (w + 1) + x
inc grid[t]
inc grid[grid.high - t]
for i, dir in Dirs:
if grid[t + next[i]] == 0:
walk(y + dir[0], x + dir[1])
dec grid[t]
dec grid[grid.high - t]
#------------------------------------------------------------------------------
proc solve(y, x: int; recursive: bool): int =
h = y
w = x
if odd(h): swap w, h
if odd(h): return 0
if w == 1: return 1
if w == 2: return h
if h == 2: return w
let cy = h div 2
let cx = w div 2
grid = newSeq[byte]((w + 1) * (h + 1))
next[0] = -1
next[1] = -w - 1
next[2] = 1
next[3] = w + 1
if recursive: count = 0
for x in (cx + 1)..<w:
let t = cy * (w + 1) + x
grid[t] = 1
grid[grid.high - t] = 1
walk(cy - 1, x)
inc count
if h == w:
count *= 2
elif not odd(w) and recursive:
discard solve(w, h, false)
result = count
#——————————————————————————————————————————————————————————————————————————————
for y in 1..10:
for x in 1..y:
if not odd(x) or not odd(y):
echo &"{y:2d} x {x:2d}: {solve(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.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"time"
)
const taskDate = "March 7 2009 7:30pm EST"
const taskFormat = "January 2 2006 3:04pm MST"
func main() {
if etz, err := time.LoadLocation("US/Eastern"); err == nil {
time.Local = etz
}
fmt.Println("Input: ", taskDate)
t, err := time.Parse(taskFormat, taskDate)
if err != nil {
fmt.Println(err)
return
}
t = t.Add(12 * time.Hour)
fmt.Println("+12 hrs: ", t)
if _, offset := t.Zone(); offset == 0 {
fmt.Println("No time zone info.")
return
}
atz, err := time.LoadLocation("US/Arizona")
if err == nil {
fmt.Println("+12 hrs in Arizona:", t.In(atz))
}
} |
http://rosettacode.org/wiki/Deal_cards_for_FreeCell | Deal cards for FreeCell | Free Cell is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for DOS, then Windows.
This version introduced 32000 numbered deals. (The FreeCell FAQ tells this history.)
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals.
These deals are numbered from 1 to 32000.
Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
The algorithm uses this linear congruential generator from Microsoft C:
s
t
a
t
e
n
+
1
≡
214013
×
s
t
a
t
e
n
+
2531011
(
mod
2
31
)
{\displaystyle state_{n+1}\equiv 214013\times state_{n}+2531011{\pmod {2^{31}}}}
r
a
n
d
n
=
s
t
a
t
e
n
÷
2
16
{\displaystyle rand_{n}=state_{n}\div 2^{16}}
r
a
n
d
n
{\displaystyle rand_{n}}
is in range 0 to 32767.
Rosetta Code has another task, linear congruential generator, with code for this RNG in several languages.
The algorithm follows:
Seed the RNG with the number of the deal.
Create an array of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.
Until the array is empty:
Choose a random card at index ≡ next random number (mod array length).
Swap this random card with the last card of the array.
Remove this random card from the array. (Array length goes down by 1.)
Deal this random card.
Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.
Order to deal cards
Game #1
Game #617
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52
JD 2D 9H JC 5D 7H 7C 5H
KD KC 9S 5S AD QC KH 3H
2S KS 9D QD JS AS AH 3C
4C 5C TS QH 4H AC 4D 7S
3S TD 4S TH 8H 2C JH 7D
6D 8S 8D QS 6C 3D 8C TC
6S 9C 2H 6H
7D AD 5C 3S 5S 8C 2D AH
TD 7S QD AC 6D 8H AS KH
TH QC 3H 9D 6S 8D 3D TC
KD 5H 9S 3C 8S 7H 4D JS
4C QS 9C 9H 7C 6H 2C 2S
4S TS 2H 5D JC 6C JH QH
JD KS KC 4H
Deals can also be checked against FreeCell solutions to 1000000 games.
(Summon a video solution, and it displays the initial deal.)
Write a program to take a deal number and deal cards in the same order as this algorithm.
The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way.
Related tasks:
Playing cards
Card shuffles
War Card_Game
Poker hand_analyser
Go Fish
| #REXX | REXX | /*REXX program deals cards for a specific FreeCell solitaire card game (0 ──► 32767).*/
numeric digits 15 /*ensure enough digits for the random #*/
parse arg game cols . /*obtain optional arguments from the CL*/
if game=='' | game=="," then game=1 /*No game specified? Then use default.*/
if cols=='' | cols=="," then cols=8 /* " cols " " " " */
state=game /*seed random # generator with game num*/
if 8=='f8'x then suit= "cdhs" /*EBCDIC? Then use letters for suits.*/
else suit= "♣♦♥♠" /* ASCII? " " symbols " " */
rank= 'A23456789tJQK' /*t in the rank represents a ten (10).*/
pad=left('', 13) /*used for indentation for the tableau.*/
say center('tableau for FreeCell game' game, 50, "─") /*show title for FreeCell game #*/
say /* [↓] @ is an array of all 52 cards.*/
#=-1; do r=1 for length(rank) /*build the deck first by the rank. */
do s=1 for length(suit); #=#+1 /* " " " secondly " " suit. */
@.#=substr(rank, r,1)substr(suit, s,1) /*build the $ array one card at at time*/
end /*s*/ /* [↑] first card is number 0 (zero).*/
end /*r*/ /* [↑] build deck per FreeCell rules. */
$=pad /*@: cards to be dealt, eight at a time*/
do cards=51 by -1 for 52 /* [↓] deal the cards for the tableau.*/
?=rand() // (cards+1) /*get next rand#; card # is remainder.*/
$=$ @.?; @[email protected] /*swap two cards: use random and last.*/
if words($)==cols then do; say $; $=pad /*deal FreeCell cards for the tableau. */
end
end /*cards*/ /*normally, 8 cards are dealt to a row.*/
/* [↓] residual cards may exist. */
if $\='' then say $ /*Any residual cards in the tableau ? */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
rand: state=(214013*state + 2531011) // 2**31; return state % 2**16 /*FreeCell rand#*/ |
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.
| #Delphi | Delphi | procedure IsXmasSunday(fromyear, toyear: integer);
var
i: integer;
TestDate: TDateTime;
outputyears: string;
begin
outputyears := '';
for i:= fromyear to toyear do
begin
TestDate := EncodeDate(i,12,25);
if dayofweek(TestDate) = 1 then
begin
outputyears := outputyears + inttostr(i) + ' ';
end;
end;
//CONSOLE
//writeln(outputyears);
//GUI
form1.label1.caption := outputyears;
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
| #D | D | import std.stdio;
void main(string[] args) {
writeln("CUSIP Verdict");
foreach(arg; args[1..$]) {
writefln("%9s : %s", arg, isValidCusip(arg) ? "Valid" : "Invalid");
}
}
class IllegalCharacterException : Exception {
this(string msg) {
super(msg);
}
}
bool isValidCusip(string cusip) in {
assert(cusip.length == 9, "Incorrect cusip length");
} body {
try {
auto check = cusipCheckDigit(cusip);
return cusip[8] == ('0' + check);
} catch (IllegalCharacterException e) {
return false;
}
}
unittest {
// Oracle Corporation
assertEquals(isValidCusip("68389X105"), true);
// Oracle Corporation (invalid)
assertEquals(isValidCusip("68389X106"), false);
}
int cusipCheckDigit(string cusip) in {
assert(cusip.length == 9, "Incorrect cusip length");
} body {
int sum;
for (int i=0; i<8; ++i) {
char c = cusip[i];
int v;
switch(c) {
case '0': .. case '9':
v = c - '0';
break;
case 'A': .. case 'Z':
v = c - 'A' + 10;
break;
case '*':
v = 36;
break;
case '@':
v = 37;
break;
case '#':
v = 38;
break;
default:
throw new IllegalCharacterException("Saw character: " ~ c);
}
if (i%2 == 1) {
v = 2 * v;
}
sum = sum + (v / 10) + (v % 10);
}
return (10 - (sum % 10)) % 10;
}
unittest {
// Apple Incorporated
assertEquals(cusipCheckDigit("037833100"), 0);
// Cisco Systems
assertEquals(cusipCheckDigit("17275R102"), 2);
// Google Incorporated
assertEquals(cusipCheckDigit("38259P508"), 8);
// Microsoft Corporation
assertEquals(cusipCheckDigit("594918104"), 4);
// Oracle Corporation
assertEquals(cusipCheckDigit("68389X105"), 5);
}
version(unittest) {
void assertEquals(T)(T actual, T expected) {
import core.exception;
import std.conv;
if (actual != expected) {
throw new AssertError("Actual [" ~ to!string(actual) ~ "]; Expected [" ~ to!string(expected) ~ "]");
}
}
}
/// Invoke with `cusip 037833100 17275R102 38259P508 594918104 68389X106 68389X105` |
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
| #Ada | Ada |
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Test_Deviation is
type Sample is record
N : Natural := 0;
Sum : Float := 0.0;
SumOfSquares : Float := 0.0;
end record;
procedure Add (Data : in out Sample; Point : Float) is
begin
Data.N := Data.N + 1;
Data.Sum := Data.Sum + Point;
Data.SumOfSquares := Data.SumOfSquares + Point ** 2;
end Add;
function Deviation (Data : Sample) return Float is
begin
return Sqrt (Data.SumOfSquares / Float (Data.N) - (Data.Sum / Float (Data.N)) ** 2);
end Deviation;
Data : Sample;
Test : array (1..8) of Integer := (2, 4, 4, 4, 5, 5, 7, 9);
begin
for Index in Test'Range loop
Add (Data, Float(Test(Index)));
Put("N="); Put(Item => Index, Width => 1);
Put(" ITEM="); Put(Item => Test(Index), Width => 1);
Put(" AVG="); Put(Item => Float(Data.Sum)/Float(Index), Fore => 1, Aft => 3, Exp => 0);
Put(" STDDEV="); Put(Item => Deviation (Data), Fore => 1, Aft => 3, Exp => 0);
New_line;
end loop;
end Test_Deviation;
|
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
| #C.23 | C# | using System;
namespace RosettaCode.DateFormat
{
class Program
{
static void Main(string[] args)
{
DateTime today = DateTime.Now.Date;
Console.WriteLine(today.ToString("yyyy-MM-dd"));
Console.WriteLine(today.ToString("dddd, MMMMM d, yyyy"));
}
}
} |
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
| #C.2B.2B | C++ | // Display the current date in the formats of "2007-11-10"
// and "Sunday, November 10, 2007".
#include <vector>
#include <string>
#include <iostream>
#include <ctime>
/** Return the current date in a string, formatted as either ISO-8601
* or "Weekday-name, Month-name Day, Year".
*
* The date is initialized when the object is created and will return
* the same date for the lifetime of the object. The date returned
* is the date in the local timezone.
*/
class Date
{
struct tm ltime;
public:
/// Default constructor.
Date()
{
time_t t = time(0);
localtime_r(&t, <ime);
}
/** Return the date based on a format string. The format string is
* fed directly into strftime(). See the strftime() documentation
* for information on the proper construction of format strings.
*
* @param[in] fmt is a valid strftime() format string.
*
* @return a string containing the formatted date, or a blank string
* if the format string was invalid or resulted in a string that
* exceeded the internal buffer length.
*/
std::string getDate(const char* fmt)
{
char out[200];
size_t result = strftime(out, sizeof out, fmt, <ime);
return std::string(out, out + result);
}
/** Return the date in ISO-8601 date format.
*
* @return a string containing the date in ISO-8601 date format.
*/
std::string getISODate() {return getDate("%F");}
/** Return the date formatted as "Weekday-name, Month-name Day, Year".
*
* @return a string containing the date in the specified format.
*/
std::string getTextDate() {return getDate("%A, %B %d, %Y");}
};
int main()
{
Date d;
std::cout << d.getISODate() << std::endl;
std::cout << d.getTextDate() << std::endl;
return 0;
} |
http://rosettacode.org/wiki/Cullen_and_Woodall_numbers | Cullen and Woodall numbers | A Cullen number is a number of the form n × 2n + 1 where n is a natural number.
A Woodall number is very similar. It is a number of the form n × 2n - 1 where n is a natural number.
So for each n the associated Cullen number and Woodall number differ by 2.
Woodall numbers are sometimes referred to as Riesel numbers or Cullen numbers of the second kind.
Cullen primes are Cullen numbers that are prime. Similarly, Woodall primes are Woodall numbers that are prime.
It is common to list the Cullen and Woodall primes by the value of n rather than the full evaluated expression. They tend to get very large very quickly. For example, the third Cullen prime, n == 4713, has 1423 digits when evaluated.
Task
Write procedures to find Cullen numbers and Woodall numbers.
Use those procedures to find and show here, on this page the first 20 of each.
Stretch
Find and show the first 5 Cullen primes in terms of n.
Find and show the first 12 Woodall primes in terms of n.
See also
OEIS:A002064 - Cullen numbers: a(n) = n*2^n + 1
OEIS:A003261 - Woodall (or Riesel) numbers: n*2^n - 1
OEIS:A005849 - Indices of prime Cullen numbers: numbers k such that k*2^k + 1 is prime
OEIS:A002234 - Numbers k such that the Woodall number k*2^k - 1 is prime
| #Phix | Phix | with javascript_semantics
atom t0 = time()
include mpfr.e
procedure cullen(mpz r, integer n)
mpz_ui_pow_ui(r,2,n)
mpz_mul_si(r,r,n)
mpz_add_si(r,r,1)
end procedure
procedure woodall(mpz r, integer n)
cullen(r,n)
mpz_sub_si(r,r,2)
end procedure
sequence c = {}, w = {}
mpz z = mpz_init()
for i=1 to 20 do
cullen(z,i)
c = append(c,mpz_get_str(z))
mpz_sub_si(z,z,2)
w = append(w,mpz_get_str(z))
end for
printf(1," Cullen[1..20]:%s\nWoodall[1..20]:%s\n",{join(c),join(w)})
atom t1 = time()+1
c = {}
integer n = 1
while length(c)<iff(platform()=JS?2:5) do
cullen(z,n)
if mpz_prime(z) then c = append(c,sprint(n)) end if
n += 1
if time()>t1 and platform()!=JS then
progress("c(%d) [needs to get to 6611], %d found\r",{n,length(c)})
t1 = time()+2
end if
end while
if platform()!=JS then progress("") end if
printf(1,"First 5 Cullen primes (in terms of n):%s\n",{join(c)})
w = {}
n = 1
while length(w)<12 do
woodall(z,n)
if mpz_prime(z) then w = append(w,sprint(n)) end if
n += 1
end while
printf(1,"First 12 Woodall primes (in terms of n):%s\n",{join(w)})
?elapsed(time()-t0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.