CUSIP: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 17:
;Example pseudo-code below.
<syntaxhighlight lang=text>algorithm Cusip-Check-Digit(cusip) is
Input: an 8-character CUSIP
Line 43:
return (10 - (sum mod 10)) mod 10
end function</
;See related tasks:
Line 53:
{{trans|Python}}
<
I cusip.len != 9
X ValueError(‘CUSIP must be 9 characters’)
Line 88:
‘68389X105’]
L(code) codes
print(code‘: ’(I cusip_check(code) {‘valid’} E ‘invalid’))</
{{out}}
Line 101:
=={{header|360 Assembly}}==
<
CUSIP CSECT
USING CUSIP,R13 base register
Line 181:
PG DC CL80'CUSIP ......... is... valid'
YREGS
END CUSIP</
{{out}}
<pre>
Line 194:
=={{header|Action!}}==
{{libheader|Action! Tool Kit}}
<
BYTE FUNC Verify(CHAR ARRAY code)
Line 254:
Test("68389X106")
Test("68389X105")
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/CUSIP.png Screenshot from Atari 8-bit computer]
Line 267:
=={{header|Ada}}==
<
procedure Cusip_Test is
Line 320:
end if;
end loop;
end Cusip_Test;</
{{Out}}
<pre>037833100: valid
Line 331:
=={{header|ALGOL 68}}==
<
# returns TRUE if cusip is a valid CUSIP code #
OP ISCUSIP = ( STRING cusip )BOOL:
Line 379:
test cusip( "68389X106" );
test cusip( "68389X105" )
END</
{{out}}
<pre>
Line 392:
=={{header|ALGOL W}}==
Based on Algol 68
<
logical procedure isCusip ( string(9) value cusip ) ;
begin
Line 426:
testCusip( "68389X105" )
end testCases
end.</
{{out}}
<pre>
Line 438:
=={{header|AppleScript}}==
<
use framework "Foundation"
use scripting additions
Line 717:
return lst
end tell
end zipWith</
{{Out}}
<pre>037833100 -> true
Line 728:
=={{header|Arturo}}==
{{trans|Ruby}}
<
s: 0
alpha: `A`..`Z`
Line 754:
loop ["037833100" "17275R102" "38259P508" "594918104" "68389X106" "68389X105"] 'cusip [
print [cusip "=>" (validCUSIP? cusip)? -> "VALID" -> "INVALID"]
]</
{{out}}
Line 766:
=={{header|AutoHotkey}}==
<
sum := 0, i := 1, x := StrSplit(cusip)
while (i <= 8) {
Line 786:
}
return (Mod(10 - Mod(sum, 10), 10) = x[9])
}</
Examples:<
(
037833100
Line 800:
loop, Parse, data, `n, `r
output .= A_LoopField "`t" Cusip_Check_Digit(A_LoopField) "`n"
MsgBox % output</
{{out}}
<pre>Cusip Valid
Line 811:
=={{header|AWK}}==
<
# syntax: GAWK -f CUSIP.AWK
BEGIN {
Line 853:
return(substr(n,9,1) == x ? 1 : 0)
}
</syntaxhighlight>
{{out}}
<pre>
Line 865:
=={{header|BCPL}}==
<
let validcusip(c) = valof
Line 899:
show("68389X106")
show("68389X105")
$)</
{{out}}
<pre>037833100: valid
Line 910:
=={{header|C}}==
Reads CUSIP strings from a file and prints results to console, usage printed on incorrect invocation.
<syntaxhighlight lang=C>
#include<stdlib.h>
#include<stdio.h>
Line 964:
return 0;
}
</syntaxhighlight>
Input file :
<pre>
Line 990:
=={{header|C sharp|C#}}==
{{trans|Java}}
<
using System.Collections.Generic;
Line 1,037:
}
}
}</
{{out}}
<pre>037833100 -> correct
Line 1,048:
=={{header|C++}}==
{{trans|C#}}
<
#include <vector>
Line 1,096:
return 0;
}</
{{out}}
<pre>037833100 -> correct
Line 1,107:
=={{header|Caché ObjectScript}}==
<
{
Line 1,125:
}
}</
{{out|Examples}}
<pre>USER>For { Read s Quit:s="" Write ": "_##class(Utils.Check).CUSIP(s), ! }
Line 1,138:
=={{header|Clojure}}==
<
(defn- char->value
"convert the given char c to a value used to calculate the cusip check sum"
Line 1,185:
"EXTRACRD9" "BADCUSIP!" "683&9X106" "68389x105" "683$9X106" "68389}105" "87264ABE4"]]
(println cusip (if (is-valid-cusip9? cusip) "valid" "invalid"))))
</syntaxhighlight>
{{out}}
Line 1,207:
=={{header|CLU}}==
<
own chars: string := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#"
if string$size(s) ~= 9 then return(false) end
Line 1,239:
end
end
end start_up</
{{out}}
<pre>037833100: valid
Line 1,249:
=={{header|Common Lisp}}==
<
(cond ((digit-char-p c 36))
((char= c #\*) 36)
Line 1,271:
(defun main ()
(dolist (cusip '("037833100" "17275R102" "38259P508" "594918104" "68389X106" "68389X105"))
(format t "~A: ~A~%" cusip (cusip-p cusip))))</
{{out}}
<pre>037833100: T
Line 1,281:
=={{header|D}}==
<
void main(string[] args) {
Line 1,379:
}
/// Invoke with `cusip 037833100 17275R102 38259P508 594918104 68389X106 68389X105`</
{{out}}
Line 1,394:
{{trans|Go}}
<
if s.Length() != 9 { return false }
var sum = 0
Line 1,431:
}
print("\(candidate) -> \(b)")
}</
{{out}}
Line 1,449:
(See [https://www.microsoft.com/en-us/research/blog/lambda-the-ultimatae-excel-worksheet-function/ LAMBDA: The ultimate Excel worksheet function])
<
LET(
ns, VLOOKUP(
Line 1,487:
10;"B",11;"C",12;"D",13;"E",14;"F",15;"G",16;"H",17;"I",18;"J",19;"K",
20;"L",21;"M",22;"N",23;"O",24;"P",25;"Q",26;"R",27;"S",28;"T",29;"U",
30;"V",31;"W",32;"X",33;"Y",34;"Z",35;"*",36;"@",37;"#",38}</
and also assuming the following generic bindings in the Name Manager for the WorkBook:
<
=LAMBDA(s,
MID(
Line 1,521:
COLUMNS(xs)
)
)</
{{Out}}
Line 1,563:
=={{header|F_Sharp|F#}}==
<
// Validate CUSIP: Nigel Galloway. June 2nd., 2021
let fN=function n when n>47 && n<58->n-48 |n when n>64 && n<91->n-55 |42->36 |64->37 |_->38
let cD(n:string)=(10-(fst((n.[0..7])|>Seq.fold(fun(z,n)g->let g=(fN(int g))*(n+1) in (z+g/10+g%10,(n+1)%2))(0,0)))%10)%10=int(n.[8])-48
["037833100";"17275R102";"38259P508";"594918104";"68389X103";"68389X105"]|>List.iter(fun n->printfn "CUSIP %s is %s" n (if cD n then "valid" else "invalid"))
</syntaxhighlight>
{{out}}
<pre>
Line 1,580:
</pre>
=={{header|Factor}}==
<
math.parser qw regexp sequences unicode ;
IN: rosetta-code.cusip
Line 1,597:
qw{ 037833100 17275R102 38259P508 594918104 68389X106 68389X105 }
[ dup cusip? "correct" "incorrect" ? "%s -> %s\n" printf ] each</
{{out}}
<pre>
Line 1,613:
The source does not bother with the MODULE protocol of F90 and later, and so the type of function CUSIPCHECK must be declared in all routines wishing to invoke it. However, the F90 feature of having the END statement of a subroutine or function give its name is to valuable to ignore. The function returns a character code rather than an integer, since the presumption is that it is to be compared to the check character of the code being inspected, which is known as a character not an integer. This means some blather when extracting the eight characters to be presented to CUSIPCHECK and comparing the result to the ninth character, but the test can be done in one expression.
There is no checking that only valid characters are presented, nor that eight-character codes only are offered, though the compiler might complain if the function were to be invoked with a text literal of the wrong size. In the absence of such checks, there need be no added complications to support a scheme for reporting such errors. <
Committee on Uniform Security Identification Purposes, of the American (i.e. USA) Bankers' Association.
CHARACTER*8 TEXT !Specifically, an eight-symbol code.
Line 1,646:
END DO
END</
Output: standard output is to I/O unit 6, and free-format (the *) will suffice for this. Each line output starts with a space (in case it is to go to a lineprinter, with carriage control), which is convenient for layout here.
Line 1,659:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
Line 1,721:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>037833100 is valid
Line 1,731:
=={{header|Go}}==
<
import "fmt"
Line 1,781:
}
}
</syntaxhighlight>
{{out}}
Line 1,795:
=={{header|Groovy}}==
{{trans|Java}}
<
private static Boolean isCusip(String s) {
if (s.length() != 9) return false
Line 1,834:
}
}
}</
{{out}}
<pre>037833100 -> correct
Line 1,844:
=={{header|Haskell}}==
<
data Result = Valid | BadCheck | TooLong | TooShort | InvalidContent deriving Show
Line 1,887:
]
main = mapM_ putStrLn (fmap (\s -> s ++ ": " ++ show (checkCUSIP s)) testData)</
{{out}}
Line 1,899:
Or, picking some other possibilities from Haskell's rich libraries:
<
import Data.Maybe (fromMaybe)
Line 1,935:
"68389X106",
"68389X105"
]</
{{Out}}
<pre>("037833100",True)
Line 1,945:
=={{header|Icon}} and {{header|Unicon}}==
<
procedure main()
Line 1,984:
t[chars[n]] := (n - 1)
return t
end</
{{out}}<pre>037833100 : valid.
Line 1,996:
=={{header|J}}==
One-liner:
<
ccd '68389X10'
5</
More verbose version that checks for correct input:
<
assert. 8 = $ y NB. Only accept an 8-element long list
assert. */ y e. '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#' NB. Only accept characters from the list of 38
Line 2,010:
)
addCUSIPcheckdigit =: , CUSIPcheckdigit
verifyCUSIPcheckdigit =: {: = CUSIPcheckdigit@}:</
Examples:
<
68389X105
verifyCUSIPcheckdigit '68389X106'
Line 2,028:
│68389X106│0│
│68389X105│1│
└─────────┴─┘</
=={{header|Java}}==
{{trans|Kotlin}}
Uses Java 9
<
public class Cusip {
Line 2,071:
}
}
}</
{{out}}
<pre>037833100 -> correct
Line 2,090:
=={{header|JavaScript}}==
<
'use strict';
Line 2,518:
// MAIN ---
return main();
})();</
{{Out}}
<pre>037833100 -> true
Line 2,530:
{{works with|Julia|0.6}}
<
function _lastdigitcusip(input::AbstractString)
Line 2,562:
for code in ("037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105")
println("$code is ", CUSIP.checkdigit(code) ? "correct." : "not correct.")
end</
{{out}}
Line 2,573:
=={{header|Kotlin}}==
<
fun isCusip(s: String): Boolean {
Line 2,605:
for (candidate in candidates)
println("$candidate -> ${if(isCusip(candidate)) "correct" else "incorrect"}")
}</
{{out}}
Line 2,621:
{{works with|langur|0.8.5}}
<
if not isString(.s) or len(.s) != 9 {
return false
Line 2,643:
for .c in .candidates {
writeln .c, ": ", if(.isCusip(.c): "good" ; "bad")
}</
Following the pseudo-code would look more like the following.
Line 2,649:
{{works with|langur|0.8.5}}
{{trans|Go}}
<
if not isString(.s) or len(.s) != 9 {
return false
Line 2,685:
for .c in .candidates {
writeln .c, ": ", if(.isCusip(.c): "good" ; "bad")
}</
{{out}}
Line 2,697:
=={{header|Lua}}==
The checkDigit function is a line-for-line translation of the pseudo-code algorithm.
<
if #cusip ~= 8 then return false end
Line 2,740:
print("INVALID")
end
end</
{{out}}
<pre>037833100: VALID
Line 2,750:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
rules = Thread[(ToString /@ Range[0, 9]) -> Range[0, 9]]~Join~
Thread[CharacterRange["A", "Z"] -> Range[26] + 9]~Join~
Line 2,772:
]
]
Cusip /@ {"037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105"}</
{{out}}
<pre>{True, True, True, True, False, True}</pre>
=={{header|Modula-2}}==
<
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 2,852:
ReadChar
END CUSIP.</
{{out}}
<pre>CUSIP Verdict
Line 2,863:
=={{header|Nanoquery}}==
<
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
num = "0123456789"
Line 2,900:
end
end
end</
{{out}}
Line 2,911:
=={{header|Nim}}==
<
proc cusipCheck(cusip: string): bool =
Line 2,951:
echo code, ": ", if cusipCheck(code): "Valid" else: "Invalid"
main()</
{{out}}
Line 2,964:
=={{header|Objeck}}==
{{trans|Kotlin}}
<
function : native : IsCusip(s : String) ~ Bool {
if(s->Size() <> 9) {
Line 3,021:
};
}
}</
Output:
Line 3,035:
=={{header|Perl}}==
<
sub cusip_check_digit {
Line 3,061:
);
print "$_ $test_data{$_}" . cusip_check_digit($_) . "\n" for sort keys %test_data;</
{{out}}
<pre>037833100 Apple Incorporated
Line 3,071:
=={{header|Phix}}==
<!--<
<span style="color: #004080;">sequence</span> <span style="color: #000000;">cch</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
Line 3,112:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s : %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"invalid"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"valid"</span><span style="color: #0000FF;">}[</span><span style="color: #000000;">CusipCheckDigit</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 3,124:
=={{header|PHP}}==
<
if (strlen($s) != 9) return false;
$sum = 0;
Line 3,162:
"68389X105");
foreach ($cusips as $cusip) echo $cusip . " -> " . (IsCusip($cusip) ? "valid" : "invalid") . "\n";</
{{out}}
<pre>
Line 3,173:
=={{header|PicoLisp}}==
<
(let (Str (mapcar char (chop Str)) S 0)
(for (I . C) (head 8 Str)
Line 3,201:
"38259P508"
"68389X106"
"68389X105" ) ) )</
{{out}}
<pre>(T T T NIL T)</pre>
=={{header|PowerShell}}==
<
function Get-CheckDigitCUSIP {
[CmdletBinding()]
Line 3,255:
"@ -split "`n"
$data |%{ Test-IsCUSIP $_.Split("`t")[0] }
</
True
True
Line 3,268:
Requires Python 3.6 for the string template literal in the print statement.
<
import math
Line 3,310:
for code in codes:
print(f'{code} -> {cusip_check(code)}')
</syntaxhighlight>
Output:
<pre>037833100 -> True
Line 3,323:
{{Works with|Python|3.7}}
Composing a set of pure functions, including a number of general and reusable abstractions:
<
from itertools import (cycle, islice, starmap)
Line 3,482:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>Test for validity as a CUSIP string:
Line 3,495:
=={{header|Quackery}}==
<
swap 0 swap
witheach
Line 3,520:
$ "037833100 17275R102 38259P508 594918104 68389X106 68389X105"
nest$ witheach task</
{{out}}
Line 3,534:
=={{header|Racket}}==
<
(require srfi/14)
Line 3,570:
(check-true (CUSIP? "594918104"))
(check-false (CUSIP? "68389X106"))
(check-true (CUSIP? "68389X105")))</
no output indicates all tests passed.
Line 3,578:
{{works with|Rakudo|2017.01}}
<syntaxhighlight lang=raku
my %chr = (flat 0..9, 'A'..'Z', <* @ #>) Z=> 0..*;
Line 3,595:
68389X106
68389X105
></
{{out}}
<pre>037833100: True
Line 3,606:
=={{header|REXX}}==
===idiomatic===
<
@.=
parse arg @.1 .
Line 3,637:
$=$ + #%10 + #//10
end /*k*/
return (10- $//10) // 10</
'''output''' when using the default input:
<pre>
Line 3,649:
===conciser function===
<
@.=
parse arg @.1 .
Line 3,674:
$=$ + #%10 + #//10
end /*k*/
return (10-$//10) // 10</
'''output''' is the same as the idiomatic REXX version. <br><br>
=={{header|Ring}}==
<
# Project : CUSIP
Line 3,736:
see inputstr + " is invalid" + nl
ok
</syntaxhighlight>
Output:
<pre>
Line 3,749:
=={{header|Ruby}}==
===Following pseudocode===
<
#!/usr/bin/env ruby
Line 3,789:
end
</syntaxhighlight>
Output:
Line 3,802:
===More concise===
Since it uses methods like chain, to_h, sum, and infinite Range syntax (0..), this needs a Ruby version > 2.5
<
TABLE = ("0".."9").chain("A".."Z", %w(* @ #)).zip(0..).to_h
Line 3,814:
CUSIPs = %w(037833100 17275R102 38259P508 594918104 68389X106 68389X105)
CUSIPs.each{|cusip| puts "#{cusip}: #{valid_CUSIP? cusip}"}
</syntaxhighlight>
=={{header|Rust}}==
<
if cusip.len() != 9 {
return false;
Line 3,859:
println!("{} -> {}", code, cusip_check(code))
}
}</
Output:
Line 3,872:
=={{header|Scala}}==
{{Out}}See it running in your browser by [https://scalafiddle.io/sf/jwxwWpq/0 ScalaFiddle (JavaScript, non JVM)] or by [https://scastie.scala-lang.org/OBrz9l14Rm2C6tV8tiwhWg Scastie (JVM)].
<
val candidates = Seq("037833100", "17275R102", "38259P508", "594918104", "68389X106", "68389X105")
Line 3,899:
}
}</
=={{header|SNOBOL4}}==
<
* cusip.sno
* -- Committee on Uniform Security Identification Procedures
Line 3,951:
68389X10
68389X1059
68389x105</
{{out}}
<pre>037833100 valid.
Line 3,965:
=={{header|Swift}}==
<
var value: String
Line 4,031:
print("Valid")
}
}</
{{out}}
Line 4,044:
=={{header|Tcl}}==
=== Direct translation of pseudocode ===
<
lsearch {_ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z} [string toupper $c]
}
Line 4,081:
set cusip [string range $cusip 0 end-1]
expr {$last eq [Cusip-Check-Digit $cusip]}
}</
=== More idiomatic Tcl ===
<
if {[string length $code] != 9} {
return false
Line 4,100:
}
expr {$sum % 10 == 0}
}</
=== Common test harness ===
<
foreach {cusip name} {
037833100 "Apple Incorporated"
Line 4,116:
}
}
test</
=== Output ===
Line 4,128:
=={{header|VBA}}==
<
Dim Sum As Integer, c As String, v As Integer
For i = 1 To 8
Line 4,154:
Next i
Cusip_Check_Digit = (10 - (Sum Mod 10)) Mod 10
End Function</
<pre>037833100 is valid
17275R102 is valid
Line 4,164:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Function IsCUSIP(s As String) As Boolean
Line 4,211:
End Sub
End Module</
{{out}}
<pre>037833100 -> correct
Line 4,222:
=={{header|Vlang}}==
{{trans|Go}}
<
if s.len != 9 { return false }
mut sum := 0
Line 4,273:
println("$candidate -> $b")
}
}</
{{out}}
Line 4,287:
=={{header|Wren}}==
{{trans|Go}}
<
if (s.count != 9) return false
var sum = 0
Line 4,323:
var b = (isCusip.call(candidate)) ? "correct" : "incorrect"
System.print("%(candidate) -> %(b)")
}</
{{out}}
Line 4,336:
=={{header|XPL0}}==
<
func Valid(Cusip); \Return 'true' if valid CUSIP code
Line 4,374:
CrLf(0);
];
]</
{{out}}
Line 4,388:
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<
local i, v, sum, x$
Line 4,435:
cusip(inputStr$)
loop
</syntaxhighlight>
=={{header|Zig}}==
<
const print = std.debug.print;
Line 4,487:
}
}
</syntaxhighlight>
=={{header|zkl}}==
<
var [const] vs=[0..9].chain(["A".."Z"],T("*","@","#")).pump(String);
try{
Line 4,497:
((10 - sum%10)%10 == cusip[8].toInt()) and cusip.len()==9
}catch{ False }
}</
<
"38259P508", "594918104", "68389X106", "68389X105")){
println(cusip,": ",cusipCheckDigit(cusip));
}</
{{out}}
<pre>
|