Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate this program into Pascal but keep the logic exactly as in Go.
package main import ( "fmt" "sort" "strings" ) const stx = "\002" const etx = "\003" func bwt(s string) (string, error) { if strings.Index(s, stx) >= 0 || strings.Index(s, etx) >= 0 { return "", fmt.Errorf("String can't contain STX or ETX") } s = stx + s + etx le := len(s) tab...
program BurrowsWheeler; uses SysUtils; const STR_BASE = 1; type TComparison = -1..1; procedure Encode( const input : string; out encoded : string; out index : integer); var n : integer; perm : array of integer; i, j, k : integer; incr, v : integer; ...
Please provide an equivalent version of this Go code in Pascal.
package main import ( "fmt" "math/big" ) func bernoulli(n uint) *big.Rat { a := make([]big.Rat, n+1) z := new(big.Rat) for m := range a { a[m].SetFrac64(1, int64(m+1)) for j := m; j >= 1; j-- { d := &a[j-1] d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j])) ...
program FaulhaberTriangle; uses uIntX, uEnums, SysUtils; function RationalToString( num, den : TIntX; minWidth : integer) : string; var num1, den1, divisor : TIntX; w : integer; begin divisor := TIntX.GCD( num, den); num1 := TIntx.Divide( num, divisor, uEnums.dmClassic); ...
Transform the following Go implementation into Pascal, maintaining the same output and logic.
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > ...
Program Paraffins; uses gmp; const max_n = 500; branch = 4; var rooted, unrooted: array [0 .. max_n-1] of mpz_t; c: array [0 .. branch-1] of mpz_t; cnt, tmp: mpz_t; n: integer; fmt: pchar; sum: integer; procedure tree(br, n, l: integer; sum: integer; cnt: mpz_t); var b, m: integer; begin...
Translate the given Go code snippet into Pascal without altering its behavior.
package main import ( "fmt" "math/big" ) const branches = 4 const nMax = 500 var rooted, unrooted [nMax + 1]big.Int var c [branches]big.Int var tmp = new(big.Int) var one = big.NewInt(1) func tree(br, n, l, sum int, cnt *big.Int) { for b := br + 1; b <= branches; b++ { sum += n if sum > ...
Program Paraffins; uses gmp; const max_n = 500; branch = 4; var rooted, unrooted: array [0 .. max_n-1] of mpz_t; c: array [0 .. branch-1] of mpz_t; cnt, tmp: mpz_t; n: integer; fmt: pchar; sum: integer; procedure tree(br, n, l: integer; sum: integer; cnt: mpz_t); var b, m: integer; begin...
Produce a functionally identical Pascal code for the snippet given in Go.
package main import ( "fmt" "math/big" ) func bernoulli(z *big.Rat, n int64) *big.Rat { if z == nil { z = new(big.Rat) } a := make([]big.Rat, n+1) for m := range a { a[m].SetFrac64(1, int64(m+1)) for j := m; j >= 1; j-- { d := &a[j-1] d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j])) } } return z.Set...
program Faulhaber; uses SysUtils; type TRational = record Num, Den : integer; end; const ZERO : TRational = ( Num: 0; Den : 1); HALF : TRational = ( Num: 1; Den : 2); function Rational( const a, b : integer) : TRational; var t, x, y : integer; begin if b <= 0 then raise SysUtils.Exc...
Ensure the translated Pascal code behaves exactly like the original Go snippet.
package main import ( "fmt" "sort" ) func sieve(limit uint64) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := uint64(3) for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } for { p += 2 if !c[p] { break } } ...
program primCons; const PrimeLimit = 2038074748 DIV 2; type tLimit = 0..PrimeLimit; tCntTransition = array[0..9,0..9] of NativeInt; tCntTransRec = record CTR_CntTrans:tCntTransition; CTR_primCnt, CTR_Limit : NativeInt; end; tCntTr...
Generate a Pascal translation of this Go snippet without changing its computational steps.
package main import "fmt" const n = 64 func pow2(x uint) uint64 { return uint64(1) << x } func evolve(state uint64, rule int) { for p := 0; p < 10; p++ { b := uint64(0) for q := 7; q >= 0; q-- { st := state b |= (st & 1) << uint(q) state = 0 fo...
Program Rule30; uses SysUtils; const maxRounds = 2*1000*1000; rounds = 10; var Rule30_State : Uint64; function GetCPU_Time: int64; type TCpu = record HiCpu, LoCpu : Dword; end; var Cput : TCpu; begin asm RDTSC; MOV Dword Ptr [CpuT.LoCpu],EAX MOV D...
Can you help me rewrite this code in Pascal instead of Go, keeping it the same logically?
package main import ( "fmt" "math" "math/rand" "strings" ) func norm2() (s, c float64) { r := math.Sqrt(-2 * math.Log(rand.Float64())) s, c = math.Sincos(2 * math.Pi * rand.Float64()) return s * r, c * r } func main() { const ( n = 10000 bins = 12 sig =...
Program Example40; Uses Math; type tTestData = extended; ttstfunc = function (mean, sd: tTestData): tTestData; tExArray = Array of tTestData; tSolution = record SolExArr : tExArray; SollowVal, SolHighVal, SolMean, SolStdDiv...
Write a version of this Go function in Pascal with identical behavior.
package main import ( "fmt" "github.com/shabbyrobe/go-num" "strings" "time" ) func b10(n int64) { if n == 1 { fmt.Printf("%4d: %28s  %-24d\n", 1, "1", 1) return } n1 := n + 1 pow := make([]int64, n1) val := make([]int64, n1) var count, ten, x int64 = 0, 1, 1 ...
program B10_num; uses sysutils,gmp; const Limit = 256*256*8; B10_4 = 10*10*10*10; B10_5 = 10*B10_4; B10_9 = B10_5*B10_4; HexB10 : array[0..15] of NativeUint = (0000,0001,0010,0011,0100,0101,0110,0111, 1000,1001,1010,1011,1100,1101,1110,1111); va...
Produce a language-to-language conversion: from Go to Pascal, same semantics.
package main import ( "bufio" "fmt" "log" "os" "strings" ) type state int const ( ready state = iota waiting exit dispense refunding ) func check(err error) { if err != nil { log.Fatal(err) } } func fsm() { fmt.Println("Please enter your option when promp...
program fsm1.pas; uses sysutils; type state = (Null,Ready,Waiting,Refund,Dispense,Stop); event = (Epsilon := 1,Deposit,Select,Cancel,Remove,Quit,Error); Item = record Name : string[12]; Stock: shortint; price: currency; end; var amountPaid, itemPrice , changeDue: currency; I,J ...
Port the provided Go code into Pascal while preserving the original functionality.
package main import "fmt" var g = [][]int{ 0: {1}, 1: {2}, 2: {0}, 3: {1, 2, 4}, 4: {3, 5}, 5: {2, 6}, 6: {5}, 7: {4, 6, 7}, } func main() { fmt.Println(kosaraju(g)) } func kosaraju(g [][]int) []int { vis := make([]bool, len(g)) L := make([]int, len(g)) x := len(...
program Kosaraju_SCC; type TDigraph = array of array of Integer; procedure PrintComponents(const g: TDigraph); var Visited: array of Boolean = nil; RevPostOrder: array of Integer = nil; gr: TDigraph = nil; Counter, Next: Integer; FirstItem: Boolean; procedure Dfs1(aNode: Integer); begin Visited...
Transform the following Go implementation into Pascal, maintaining the same output and logic.
package main import ( "crypto/sha256" "fmt" "io" "log" "os" ) func main() { const blockSize = 1024 f, err := os.Open("title.png") if err != nil { log.Fatal(err) } defer f.Close() var hashes [][]byte buffer := make([]byte, blockSize) h := sha256.New() fo...
program SHA256_Merkle_tree; uses System.SysUtils, System.Classes, DCPsha256; type TmyByte = TArray<Byte>; TmyHashes = TArray<TArray<byte>>; uses SysUtils, Classes, DCPsha256; type TmyByte = array of byte; TmyHashes = array of TmyByte; function SHA256(const Input: TmyByte; ...
Transform the following Go implementation into Pascal, maintaining the same output and logic.
package main import "fmt" func sumDivisors(n int) int { sum := 1 k := 2 if n%2 == 0 { k = 1 } for i := 1 + k; i*i <= n; i += k { if n%i == 0 { sum += i j := n / i if j != i { sum += j } } } return sum }...
program UntouchableNumbers; program UntouchableNumbers; uses sysutils,strutils ,Windows ; const MAXPRIME = 1742537; LIMIT = 5*1000*1000; LIMIT_mul = trunc(exp(ln(LIMIT)/3))+1; const SizePrDeFe = 16*8192; type tdigits = array [0..31] of Uint32; tprimeFac = packed record ...
Please provide an equivalent version of this Go code in Pascal.
package main import "fmt" func main() { const maxNumber = 100000000 dsum := make([]int, maxNumber+1) dcount := make([]int, maxNumber+1) for i := 0; i <= maxNumber; i++ { dsum[i] = 1 dcount[i] = 1 } for i := 2; i <= maxNumber; i++ { for j := i + i; j <= maxNumber; j += i { if dsum[j] == j { fmt.Prin...
program ErdoesNumb; uses sysutils ,Windows ; const HCN_DivCnt = 4096; type tItem = Uint64; tDivisors = array [0..HCN_DivCnt] of tItem; tpDivisor = pUint64; const SizePrDeFe = 32768; type tdigits = array [0..31] of Uint32; tprimeFac = packed record pfSu...
Convert this Go block to Pascal, preserving its control flow and logic.
package main import ( "github.com/fogleman/gg" "math/rand" "time" ) const c = 0.00001 func linear(x float64) float64 { return x*0.7 + 40 } type trainer struct { inputs []float64 answer int } func newTrainer(x, y float64, a int) *trainer { return &trainer{[]float64{x, y, 1}, a} } type p...
program Perceptron; function targetOutput( a, b : integer ) : integer; begin if a * 2 + 1 < b then targetOutput := 1 else targetOutput := -1 end; procedure showTargetOutput; var x, y : integer; begin for y := 10 downto -9 do begin for x := -9 to 10 do if targetOu...
Translate the given Go code snippet into Pascal without altering its behavior.
package main import ( "fmt" "rcu" "sort" ) func areSame(l1, l2 []int) bool { if len(l1) != len(l2) { return false } sort.Ints(l2) for i := 0; i < len(l1); i++ { if l1[i] != l2[i] { return false } } return true } func main() { i := 100 ...
program euler52; uses sysutils; const BaseConvDgt :array[0..35] of char = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; MAXBASE = 12; type TUsedDigits = array[0..MAXBASE-1] of byte; tDigitsInUse = set of 0..MAXBASE-1; var UsedDigits :tUsedDigits; gblMaxDepth, steps, base,maxmul : NativeIn...
Can you help me rewrite this code in Pascal instead of Go, keeping it the same logically?
package main import ( "fmt" "rcu" "sort" ) func areSame(l1, l2 []int) bool { if len(l1) != len(l2) { return false } sort.Ints(l2) for i := 0; i < len(l1); i++ { if l1[i] != l2[i] { return false } } return true } func main() { i := 100 ...
program euler52; uses sysutils; const BaseConvDgt :array[0..35] of char = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; MAXBASE = 12; type TUsedDigits = array[0..MAXBASE-1] of byte; tDigitsInUse = set of 0..MAXBASE-1; var UsedDigits :tUsedDigits; gblMaxDepth, steps, base,maxmul : NativeIn...
Produce a language-to-language conversion: from Go to Pascal, same semantics.
package main import "fmt" func reverse(s uint64) uint64 { e := uint64(0) for s > 0 { e = e*10 + (s % 10) s /= 10 } return e } func commatize(n uint) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } ...
program PalinGap; type tLimits = record LoLmt,HiLmt:Uint64; end; const base = 10; var delta : Array[0..9] of Uint64; deltaBase: Array[0..9] of Uint64; deltaMod : Array[0..9] of Uint32; deltaModBase : Array[0..9] of Uint32; IdxCnt : Array[0..9] of Uint32; ...
Ensure the translated Pascal code behaves exactly like the original Go snippet.
package main import "fmt" func reverse(s uint64) uint64 { e := uint64(0) for s > 0 { e = e*10 + (s % 10) s /= 10 } return e } func commatize(n uint) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } ...
program PalinGap; type tLimits = record LoLmt,HiLmt:Uint64; end; const base = 10; var delta : Array[0..9] of Uint64; deltaBase: Array[0..9] of Uint64; deltaMod : Array[0..9] of Uint32; deltaModBase : Array[0..9] of Uint32; IdxCnt : Array[0..9] of Uint32; ...
Convert this Go snippet to Pascal and keep its semantics consistent.
package main import "fmt" var canFollow [][]bool var arrang []int var bFirst = true var pmap = make(map[int]bool) func init() { for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} { pmap[i] = true } } func ptrs(res, n, done int) int { ad := arrang[done-1] if n-done <= 1 { ...
program PrimePyramid; const MAX = 21; cMaxAlign32 = (((MAX-1)DIV 32)+1)*32-1; type tPrimeRange = set of 0..127; var SetOfPrimes :tPrimeRange =[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47, 53,59,61,67,71,73,79,83,89,97,101,103,107, 109,113,127]; S...
Change the programming language of this snippet from Go to Pascal without modifying what it does.
package main import ( "fmt" "math" "rcu" "sort" ) func main() { const limit = 1000000 limit2 := int(math.Cbrt(limit)) primes := rcu.Primes(limit / 6) pc := len(primes) var sphenic []int fmt.Println("Sphenic numbers less than 1,000:") for i := 0; i < pc-2; i++ { if ...
program sphenic; const Limit= 1000*1000; type tPrimesSieve = array of boolean; tElement = Uint32; tarrElement = array of tElement; tpPrimes = pBoolean; var PrimeSieve : tPrimesSieve; primes : tarrElement; sphenics : tarrElement; procedure ClearAll; begin setlength(sphenics,0); setlength(...
Convert the following code from Go to Pascal, ensuring the logic remains intact.
package main import ( "fmt" "rcu" ) func main() { const limit = 1e9 primes := rcu.Primes(limit) var orm30 [][2]int j := int(1e5) count := 0 var counts []int for i := 0; i < len(primes)-1; i++ { p1 := primes[i] p2 := primes[i+1] if (p2-p1)%18 != 0 { ...
program Ormiston; uses sysutils,strUtils; const smlPrimes :array [0..10] of Byte = (2,3,5,7,11,13,17,19,23,29,31); maxPreSievePrimeNum = 8; maxPreSievePrime = 19; cSieveSize = 2*16384; type tSievePrim = record svdeltaPrime:word; svSivOfs:word; s...
Port the following code from Go to Pascal with equivalent syntax and logic.
package main import ( "fmt" "math" "rcu" ) var maxDepth = 6 var maxBase = 36 var c = rcu.PrimeSieve(int(math.Pow(float64(maxBase), float64(maxDepth))), true) var digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" var maxStrings [][][]int var mostBases = -1 func maxSlice(a []int) in...
program MAXBaseStringIsPrimeInBase; uses sysutils; const CharOfBase= '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; MINBASE = 2; MAXBASE = 62; MAXDIGITCOUNT = 5; type tdigits = packed record dgtDgts : array [0..13] of byte; dgtMaxIdx, ...
Port the provided Go code into Pascal while preserving the original functionality.
package main import ( "fmt" "rcu" ) func main() { limit := int(1e9) gapStarts := make(map[int]int) primes := rcu.Primes(limit * 5) for i := 1; i < len(primes); i++ { gap := primes[i] - primes[i-1] if _, ok := gapStarts[gap]; !ok { gapStarts[gap] = primes[i-1] ...
program primesieve; uses sysutils; const smlPrimes :array [0..10] of Byte = (2,3,5,7,11,13,17,19,23,29,31); maxPreSievePrime = 17; sieveSize = 1 shl 15; type tSievePrim = record svdeltaPrime:word; svSivOfs:word; svSivNum:LongWord; ...
Rewrite this program in Pascal while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "rcu" "sort" ) func main() { const limit = int(1e10) const maxIndex = 9 primes := rcu.Primes(limit) anaprimes := make(map[int][]int) for _, p := range primes { digs := rcu.Digits(p, 10) key := 1 for _, dig := range digs { ...
program AnaPrimes; uses sysutils; const Limit= 100*1000*1000; type tPrimesSieve = array of boolean; tElement = Uint64; tarrElement = array of tElement; tpPrimes = pBoolean; const cTotalSum = 16; cMaxCardsOnDeck = cTotalSum; CMaxCardsUsed = cTotalSum; type tDeckIndex = 0..cMaxCar...
Port the provided Go code into Pascal while preserving the original functionality.
package main import ( "fmt" "math" "strings" "time" ) var board [][]bool var diag1, diag2 [][]int var diag1Lookup, diag2Lookup []bool var n, minCount int var layout string func isAttacked(piece string, row, col int) bool { if piece == "Q" { for i := 0; i < n; i++ { if board[i]...
program TestMinimalQueen; uses sysutils; type tDeltaKoor = packed record dRow, dCol : Int8; end; const cKnightAttacks : array[0..7] of tDeltaKoor = ((dRow:-2;dCol:-1),(dRow:-2;dCol:+1), (dRow:-1;dCol:-2)...
Write the same algorithm in Pascal as shown in this Go implementation.
package main import ( "fmt" "math/big" "strconv" "strings" ) func main() { var res []int64 for n := 0; n <= 50; n++ { ns := strconv.Itoa(n) k := int64(1) for { bk := big.NewInt(k) s := bk.Exp(bk, bk, nil).String() if strings.Contains(...
program K_pow_K; uses sysutils; const LongWordDec = 1000*1000*1000; Digits = 6; type tMulElem = Uint32; tMul = array of tMulElem; tpMul = pUint32; tFound = Uint32; var Pot_N_str : AnsiString; Str_Found : array of tFound; FirstMissing :NativeInt; T0 : INt64; procedure Out_Results(nu...
Transform the following Go implementation into Pascal, maintaining the same output and logic.
package main import ( "fmt" "rcu" "strconv" ) func isColorful(n int) bool { if n < 0 { return false } if n < 10 { return true } digits := rcu.Digits(n, 10) for _, d := range digits { if d == 0 || d == 1 { return false } } set := m...
uses sysutils; const EightFak = 1*2*3*4*5*6*7*8; type tDgt = Int8; tpDgt = pInt8; tDgtfield = array[0..7] of tdgt; tpDgtfield = ^tDgtfield; tPermfield = tDgtfield; tAllPermDigits = array[0..EightFak] of tDgtfield; tMarkNotColorful = array[0..EightFak-1] of byte; tDat = Uin...
Write the same code in Pascal as shown below in Go.
package main import ( "fmt" "rcu" "strconv" ) func isColorful(n int) bool { if n < 0 { return false } if n < 10 { return true } digits := rcu.Digits(n, 10) for _, d := range digits { if d == 0 || d == 1 { return false } } set := m...
uses sysutils; const EightFak = 1*2*3*4*5*6*7*8; type tDgt = Int8; tpDgt = pInt8; tDgtfield = array[0..7] of tdgt; tpDgtfield = ^tDgtfield; tPermfield = tDgtfield; tAllPermDigits = array[0..EightFak] of tDgtfield; tMarkNotColorful = array[0..EightFak-1] of byte; tDat = Uin...
Generate a Pascal translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math" "rcu" ) func divisorCount(n int) int { k := 1 if n%2 == 1 { k = 2 } count := 0 sqrt := int(math.Sqrt(float64(n))) for i := 1; i <= sqrt; i += k { if n%i == 0 { count++ j := n / i if j != i { ...
program Root3rd_divs_n.pas; uses sysutils ,Windows ; const limit = 110*1000 *1000; var sol : array [0..limit] of byte; primes : array of Uint32; gblCount: Uint64; procedure SievePrimes(lmt:Uint32); var sieve : array of byte; p,i,delta : NativeInt; Begin setlength(sieve,lmt DIV 2); ...
Generate an equivalent Pascal version of this Go code.
package main import ( "fmt" "rcu" ) func factorial(n int) int { fact := 1 for i := 2; i <= n; i++ { fact *= i } return fact } func permutations(input []int) [][]int { perms := [][]int{input} a := make([]int, len(input)) copy(a, input) var n = len(input) - 1 for c...
uses System.SysUtils, System.Classes, System.Math; label nxt; begin for var sp := '0' to '1' do for var x := IfThen(sp = '1', 7654321, 76543210) downto 0 do begin var s := x.ToString; for var ch := sp to '7' do if not s.Contains(ch) then goto nxt; if x mod 3 = 0 then goto nxt; var i := 1; repeat...
Port the provided Go code into Pascal while preserving the original functionality.
package main import ( "fmt" "rcu" ) func factorial(n int) int { fact := 1 for i := 2; i <= n; i++ { fact *= i } return fact } func permutations(input []int) [][]int { perms := [][]int{input} a := make([]int, len(input)) copy(a, input) var n = len(input) - 1 for c...
uses System.SysUtils, System.Classes, System.Math; label nxt; begin for var sp := '0' to '1' do for var x := IfThen(sp = '1', 7654321, 76543210) downto 0 do begin var s := x.ToString; for var ch := sp to '7' do if not s.Contains(ch) then goto nxt; if x mod 3 = 0 then goto nxt; var i := 1; repeat...
Keep all operations the same but rewrite the snippet in Pascal.
package main import ( "fmt" "rcu" ) func prune(a []int) []int { prev := a[0] b := []int{prev} for i := 1; i < len(a); i++ { if a[i] != prev { b = append(b, a[i]) prev = a[i] } } return b } func main() { var resF, resD, resT, factors1 []int f...
program RuthAaronNumb; uses sysutils, strutils ,Windows ; const HCN_DivCnt = 4096; SizePrDeFe = 32768; type tItem = Uint64; tDivisors = array [0..HCN_DivCnt] of tItem; tpDivisor = pUint64; tdigits = array [0..31] of Uint32; tprimeFac = packed record ...
Generate an equivalent Pascal version of this Go code.
package main import "fmt" func shouldSwap(s []byte, start, curr int) bool { for i := start; i < curr; i++ { if s[i] == s[curr] { return false } } return true } func findPerms(s []byte, index, n int, res *[]string) { if index >= n { *res = append(*res, string(s)) ...
program PermWithRep; uses sysutils,classes ; const cTotalSum = 16; cMaxCardsOnDeck = cTotalSum; CMaxCardsUsed = cTotalSum; type tDeckIndex = 0..cMaxCardsOnDeck-1; tSequenceIndex = 0..CMaxCardsUsed; tDiffCardCount = Byte; tSetElem = packed record Elemcount : tDe...
Transform the following Go implementation into Pascal, maintaining the same output and logic.
package main import ( "fmt" "strings" ) var data = ` FILE FILE DEPENDENCIES ==== ================= top1 des1 ip1 ip2 top2 des1 ip2 ip3 ip1 extra1 ip1a ipcommon ip2 ip2a ip2b ip2c ipcommon des1 des1a des1b des1c des1a des1a1 des1a2 des1c des1c1 extra1` func main() { g, dep, err ...
program TopLevel; uses SysUtils, Generics.Collections; type TAdjList = class InList, OutList: THashSet<string>; constructor Create; destructor Destroy; override; end; TDigraph = class(TObjectDictionary<string, TAdjList>) procedure AddNode(const s: string); procedu...
Maintain the same structure and functionality when rewriting this code in Pascal.
package main import ( "fmt" "strings" ) var data = ` FILE FILE DEPENDENCIES ==== ================= top1 des1 ip1 ip2 top2 des1 ip2 ip3 ip1 extra1 ip1a ipcommon ip2 ip2a ip2b ip2c ipcommon des1 des1a des1b des1c des1a des1a1 des1a2 des1c des1c1 extra1` func main() { g, dep, err ...
program TopLevel; uses SysUtils, Generics.Collections; type TAdjList = class InList, OutList: THashSet<string>; constructor Create; destructor Destroy; override; end; TDigraph = class(TObjectDictionary<string, TAdjList>) procedure AddNode(const s: string); procedu...
Port the provided Go code into Pascal while preserving the original functionality.
package main import ( "fmt" "rcu" ) func powerset(set []int) [][]int { if len(set) == 0 { return [][]int{{}} } head := set[0] tail := set[1:] p1 := powerset(tail) var p2 [][]int for _, s := range powerset(tail) { h := []int{head} h = append(h, s...) ...
program practicalnumbers; uses sysutils ,Windows ; const LOW_DIVS = 0; HIGH_DIVS = 2048 - 1; type tdivs = record DivsVal: array[LOW_DIVS..HIGH_DIVS] of Uint32; DivsMaxIdx, DivsNum, DivsSumProp: NativeUInt; end; var Divs: tDivs; HasSum: array of byte; procedure GetDivisors(va...
Convert this Go block to Pascal, preserving its control flow and logic.
package main import "rcu" func isIdoneal(n int) bool { for a := 1; a < n; a++ { for b := a + 1; b < n; b++ { if a*b+a+b > n { break } for c := b + 1; c < n; c++ { sum := a*b + b*c + a*c if sum == n { re...
program idoneals; uses sysutils; const runs = 1000; type Check_isIdoneal = function(n: Uint32): boolean; var idoneals : array of Uint32; function isIdonealOrg(n: Uint32):Boolean; var a,b,c,sum : NativeUint; begin For a := 1 to n do For b := a+1 to n do Begin if (a*b + a + b >...
Port the following code from Go to Pascal with equivalent syntax and logic.
package main import "fmt" var cnt = 0 var cnt2 = 0 var wdth = 0 func factorial(n int) int { prod := 1 for i := 2; i <= n; i++ { prod *= i } return prod } func count(want int, used []int, sum int, have, uindices, rindices []int) { if sum == want { cnt++ cnt2 += factori...
program Coins0_1; uses sysutils; const coins1 :array[0..4] of byte = (1, 2, 3, 4, 5); coins2 :array[0..6] of byte = (1, 1, 2, 3, 3, 4, 5); coins3 :array[0..15] of byte = (1,2,3,4,5,5,5,5,15,15,10,10,10,10,25,100); nmax = High(Coins3); type NativeInt = Int32; tFreeCol = array[0..nmax] of I...
Translate the given Go code snippet into Pascal without altering its behavior.
package main import "fmt" var cnt = 0 var cnt2 = 0 var wdth = 0 func factorial(n int) int { prod := 1 for i := 2; i <= n; i++ { prod *= i } return prod } func count(want int, used []int, sum int, have, uindices, rindices []int) { if sum == want { cnt++ cnt2 += factori...
program Coins0_1; uses sysutils; const coins1 :array[0..4] of byte = (1, 2, 3, 4, 5); coins2 :array[0..6] of byte = (1, 1, 2, 3, 3, 4, 5); coins3 :array[0..15] of byte = (1,2,3,4,5,5,5,5,15,15,10,10,10,10,25,100); nmax = High(Coins3); type NativeInt = Int32; tFreeCol = array[0..nmax] of I...
Can you help me rewrite this code in Pascal instead of Go, keeping it the same logically?
package main import ( "fmt" "github.com/ALTree/bigfloat" "math/big" "rcu" ) func main() { t := make([]int, 30) for n := 1; n < 30; n++ { t[n] = t[n-1] + n } fmt.Println("The first 30 triangular numbers are:") rcu.PrintTable(t, 6, 3, false) for n := 1; n < 30; n++ { ...
program XangularNumbers; const MAXIDX = 29; MAXLINECNT = 13; cNames : array[0..4] of string = ('','','triangular','tetrahedral','pentatopic'); cCheckRootValues :array[0..3] of Uint64 = (7140,21408696,26728085384,14545501785001) ; type tOneLine = array[0..MAXIDX+2] of Uint64; tpOneLine = ^tO...
Write the same code in Pascal as shown below in Go.
package main import ( "fmt" "math" "rcu" "strconv" ) func reverse(s string) string { r := make([]byte, len(s)) for i := 0; i < len(s); i++ { r[i] = s[len(s)-1-i] } return string(r) } func main() { primes := []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47} ...
program penholodigital; uses sysutils; const charSet : array[0..36] of char ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; type tNumtoBase = record ntb_dgt : array[0..31-8] of byte; ntb_cnt, ntb_bas : Int32; end; var dgtSqrRoot : array[0..31-8] of...
Translate the given Go code snippet into Pascal without altering its behavior.
package main import ( "fmt" "math" "rcu" ) func contains(a []int, n int) bool { for _, e := range a { if e == n { return true } } return false } func soms(n int, f []int) bool { if n <= 0 { return false } if contains(f, n) { return true...
program practicalnumbers; var HasSum: array of byte; function FindLongestContiniuosBlock(startIdx,MaxIdx:NativeInt):NativeInt; var hs0 : pByte; l : NativeInt; begin l := 0; hs0 := @HasSum[0]; for startIdx := startIdx to MaxIdx do Begin IF hs0[startIdx]=0 then BREAK; inc(l); end; Find...
Please provide an equivalent version of this Go code in Pascal.
package main import ( "fmt" big "github.com/ncw/gmp" "rcu" ) func main() { fact := big.NewInt(1) sum := 0.0 first := int64(0) firstRatio := 0.0 fmt.Println("The mean proportion of zero digits in factorials up to the following are:") for n := int64(1); n <= 50000; n++ { ...
program Factorial; uses sysutils; type tMul = array of LongWord; tpMul = pLongWord; const LongWordDec = 1000*1000*1000; LIMIT = 50000; var CountOfZero : array[0..999] of byte; SumOfRatio :array[0..LIMIT] of extended; procedure OutMul(pMul:tpMul;Lmt :NativeInt); Begin write(pMul[lmt]); For lmt :...
Maintain the same structure and functionality when rewriting this code in Pascal.
package main import ( "fmt" "rcu" ) func genUpsideDown(limit int) chan int { ch := make(chan int) wrappings := [][2]int{ {1, 9}, {2, 8}, {3, 7}, {4, 6}, {5, 5}, {6, 4}, {7, 3}, {8, 2}, {9, 1}, } evens := []int{19, 28, 37, 46, 55, 64, 73, 82, 91} odds := []int{5} oddInde...
program UpSideDownNumbers; const TotalCnt_Dgt : array[0..41] of Uint64= (1,2,11,20,101,182,911,1640,8201,14762,73811,132860,664301,1195742, 5978711,10761680,53808401,96855122,484275611,871696100,4358480501, 7845264902,39226324511,70607384120,353036920601,635466457082, 3177332285411,5719198113740,28595990...
Port the provided Go code into Pascal while preserving the original functionality.
package main import ( "fmt" "time" ) func contains(a []int, v int) bool { for i := 0; i < len(a); i++ { if a[i] == v { return true } } return false } func main() { start := time.Now() var sends [][4]int var ors [][2]int m := 1 digits := []int{0, 2, ...
program SymbolToDigit; uses sysutils; const nmax = 9; maxLen = 7; type tFreeDgt = array[0..nmax+1] of Int32; tSymbWord = String[maxLen]; tDgtWord = record DW_DgtsIdx: array[1..maxLen] of UInt8; DW_maxIdx: Uint8; end; tDgtFront = record ...
Convert this Go snippet to Pascal and keep its semantics consistent.
package main import ( "fmt" "time" ) const rocket = ` /\ ( ) ( ) /|/\|\ /_||||_\ ` func printRocket(above int) { fmt.Print(rocket) for i := 1; i <= above; i++ { fmt.Println(" ||") } } func cls() { fmt.Print("\x1B[2J") } func main() { for n := 5; n >= 1; n-...
program launchRocketWithCountdownAndAccelerationOnOutput(output); const screenWidth = 80; type wholeNumber = 0..maxInt; natural = 1..maxInt; var n: wholeNumber; procedure sleep(n: natural); begin for n := n downto 1 do end; procedure drawRocket(column: natural); begin page; writeLn(' ':column, '�...
Write the same algorithm in COBOL as shown in this Python implementation.
seed = 675248 def random(): global seed seed = int(str(seed ** 2).zfill(12)[3:9]) return seed for _ in range(5): print(random())
IDENTIFICATION DIVISION. PROGRAM-ID. MIDDLE-SQUARE. DATA DIVISION. WORKING-STORAGE SECTION. 01 STATE. 03 SEED PIC 9(6) VALUE 675248. 03 SQUARE PIC 9(12). 03 FILLER REDEFINES SQUARE. 05 FILLER PIC 9(3). ...
Write the same code in COBOL as shown below in Python.
def query(buffer_length): message = b'Here am I' L = len(message) return message[0:L*(L <= buffer_length)]
identification division. program-id. Query. environment division. configuration section. special-names. call-convention 0 is extern. repository. function all intrinsic. data division. working-storage section. 01 query-result. ...
Rewrite this program in COBOL while keeping its functionality equivalent to the Python version.
from livewires import * horiz=640; vert=480 begin_graphics(width=horiz,height=vert,title="v_stripes",background=Colour.black) NameColors=["black","red","green","dark_blue","purple","blue","yellow","white"] stepik=horiz/len(NameColors) for index,each in enumerate(NameColors): ExcStrng="set_colour(Colour."+each+")"...
IDENTIFICATION DIVISION. PROGRAM-ID. terminal-colour-bars. DATA DIVISION. WORKING-STORAGE SECTION. 01 width PIC 9(3). 01 height PIC 9(3). 01 interval PIC 9(3). 01 colours-area. 03 colour-values. 05 FILLE...
Maintain the same structure and functionality when rewriting this code in COBOL.
from livewires import * horiz=640; vert=480 begin_graphics(width=horiz,height=vert,title="v_stripes",background=Colour.black) NameColors=["black","red","green","dark_blue","purple","blue","yellow","white"] stepik=horiz/len(NameColors) for index,each in enumerate(NameColors): ExcStrng="set_colour(Colour."+each+")"...
IDENTIFICATION DIVISION. PROGRAM-ID. terminal-colour-bars. DATA DIVISION. WORKING-STORAGE SECTION. 01 width PIC 9(3). 01 height PIC 9(3). 01 interval PIC 9(3). 01 colours-area. 03 colour-values. 05 FILLE...
Keep all operations the same but rewrite the snippet in COBOL.
>>> s = "Hello" >>> s[0] = "h" Traceback (most recent call last): File "<pyshell s[0] = "h" TypeError: 'str' object does not support item assignment
ENVIRONMENT DIVISION. CONFIGURATION SECTION. SPECIAL-NAMES. SYMBOLIC CHARACTERS NUL IS 0, TAB IS 9.
Produce a language-to-language conversion: from Python to COBOL, same semantics.
def isStrange(n): def test(a, b): return abs(a - b) in [2, 3, 5, 7] xs = digits(n) return all(map(test, xs, xs[1:])) def main(): xs = [ n for n in range(100, 1 + 500) if isStrange(n) ] print('\nStrange numbers in range [100..500]\n') print('(Total:...
IDENTIFICATION DIVISION. PROGRAM-ID. STRANGE-NUMBERS. DATA DIVISION. WORKING-STORAGE SECTION. 01 COMPUTATION. 02 NUM PIC 999. 02 DIGITS REDEFINES NUM PIC 9 OCCURS 3 TIMES. 02 DIGIT-PRIME PIC 9. 88 PRIME ...
Maintain the same structure and functionality when rewriting this code in COBOL.
def isStrange(n): def test(a, b): return abs(a - b) in [2, 3, 5, 7] xs = digits(n) return all(map(test, xs, xs[1:])) def main(): xs = [ n for n in range(100, 1 + 500) if isStrange(n) ] print('\nStrange numbers in range [100..500]\n') print('(Total:...
IDENTIFICATION DIVISION. PROGRAM-ID. STRANGE-NUMBERS. DATA DIVISION. WORKING-STORAGE SECTION. 01 COMPUTATION. 02 NUM PIC 999. 02 DIGITS REDEFINES NUM PIC 9 OCCURS 3 TIMES. 02 DIGIT-PRIME PIC 9. 88 PRIME ...
Write the same algorithm in COBOL as shown in this Python implementation.
def q(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return q.seq[n] except IndexError: ans = q(n - q(n - 1)) + q(n - q(n - 2)) q.seq.append(ans) return ans q.seq = [None, 1, 1] if __name__ == '__main__': first10 = [q(i) for i in range(1,1...
IDENTIFICATION DIVISION. PROGRAM-ID. Q-SEQ. DATA DIVISION. WORKING-STORAGE SECTION. 01 SEQ. 02 Q PIC 9(3) OCCURS 1000 TIMES. 02 Q-TMP1 PIC 9(3). 02 Q-TMP2 PIC 9(3). 02 N PIC 9(4). 01 DISPLAYING. ...
Produce a language-to-language conversion: from Python to COBOL, same semantics.
def q(n): if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1") try: return q.seq[n] except IndexError: ans = q(n - q(n - 1)) + q(n - q(n - 2)) q.seq.append(ans) return ans q.seq = [None, 1, 1] if __name__ == '__main__': first10 = [q(i) for i in range(1,1...
IDENTIFICATION DIVISION. PROGRAM-ID. Q-SEQ. DATA DIVISION. WORKING-STORAGE SECTION. 01 SEQ. 02 Q PIC 9(3) OCCURS 1000 TIMES. 02 Q-TMP1 PIC 9(3). 02 Q-TMP2 PIC 9(3). 02 N PIC 9(4). 01 DISPLAYING. ...
Generate an equivalent COBOL version of this Python code.
>>> "the three truths".count("th") 3 >>> "ababababab".count("abab") 2
IDENTIFICATION DIVISION. PROGRAM-ID. testing. DATA DIVISION. WORKING-STORAGE SECTION. 01 occurrences PIC 99. PROCEDURE DIVISION. INSPECT "the three truths" TALLYING occurrences FOR ALL "th" DISPLAY occurrences MOVE 0 TO occurrenc...
Transform the following Python implementation into COBOL, maintaining the same output and logic.
from decimal import Decimal import math def h(n): 'Simple, reduced precision calculation' return math.factorial(n) / (2 * math.log(2) ** (n + 1)) def h2(n): 'Extended precision Hickerson function' return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1)) for n in range(18): x = h2(...
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. hickerson-series. ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC . DATA DIVISION. WORKING-STORAGE SECTION. 01 n PIC 99 COMP. 01 h PIC Z(19)9.9(10). ...
Change the programming language of this snippet from Python to COBOL without modifying what it does.
from decimal import Decimal import math def h(n): 'Simple, reduced precision calculation' return math.factorial(n) / (2 * math.log(2) ** (n + 1)) def h2(n): 'Extended precision Hickerson function' return Decimal(math.factorial(n)) / (2 * Decimal(2).ln() ** (n + 1)) for n in range(18): x = h2(...
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. hickerson-series. ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC . DATA DIVISION. WORKING-STORAGE SECTION. 01 n PIC 99 COMP. 01 h PIC Z(19)9.9(10). ...
Can you help me rewrite this code in COBOL instead of Python, keeping it the same logically?
def readconf(fn): ret = {} with file(fn) as fp: for line in fp: line = line.strip() if not line or line.startswith(' boolval = True if line.startswith(';'): line = line.lstrip(';') ...
identification division. program-id. ReadConfiguration. environment division. configuration section. repository. function all intrinsic. input-output section. file-control. select config-file assign to "Configuration.txt" ...
Generate an equivalent COBOL version of this Python code.
def is_prime(n: int) -> bool: if n <= 3: return n > 1 if n % 2 == 0 or n % 3 == 0: return False i = 5 while i ** 2 <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def digit_sum(n: int) -> int: sum = 0 while n > 0: ...
IDENTIFICATION DIVISION. PROGRAM-ID. ADDITIVE-PRIMES. DATA DIVISION. WORKING-STORAGE SECTION. 01 VARIABLES. 03 MAXIMUM PIC 999. 03 AMOUNT PIC 999. 03 CANDIDATE PIC 999. 03 DIGIT PIC 9 OCCURS 3...
Convert the following code from Python to COBOL, ensuring the logic remains intact.
>>> data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7] >>> def stoogesort(L, i=0, j=None): if j is None: j = len(L) - 1 if L[j] < L[i]: L[i], L[j] = L[j], L[i] if j - i > 1: t = (j - i + 1) // 3 stoogesort(L, i , j-t) stoogesort(L, i+t, j ) stoogesort(L, i , j-t) return L >>> stoogesort(data)...
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. stooge-sort-test. DATA DIVISION. WORKING-STORAGE SECTION. 01 Arr-Len CONSTANT 7. 01 arr-area VALUE "00004001000020000005000230000000000". 03 arr-elt PIC 9(5) OCCURS Arr-Len T...
Convert the following code from Python to COBOL, ensuring the logic remains intact.
def shell(seq): inc = len(seq) // 2 while inc: for i, el in enumerate(seq[inc:], inc): while i >= inc and seq[i - inc] > el: seq[i] = seq[i - inc] i -= inc seq[i] = el inc = 1 if inc == 2 else inc * 5 // 11
******************************************************* IDENTIFICATION DIVISION. ******************************************************* PROGRAM-ID. SHELLSRT. **********************...
Transform the following Python implementation into COBOL, maintaining the same output and logic.
from time import time st = time() print(sum([n for n in range(2, 6*9**5) if sum(int(i)**5 for i in str(n)) == n]), " ", (time() - st) * 1000, "ms") st = time() nums = list(range(10)) nu = list(range(((6 * 9**5) // 100000) + 1)) numbers = [] p5 = [] for i in nums: p5.append(i**5) for i in nu: im = i * 100000 ...
IDENTIFICATION DIVISION. PROGRAM-ID. DIGIT-FIFTH-POWER. DATA DIVISION. WORKING-STORAGE SECTION. 01 VARIABLES. 03 CANDIDATE PIC 9(6). 03 MAXIMUM PIC 9(6). 03 DIGITS PIC 9 OCCURS 6 TIMES, REDE...
Produce a language-to-language conversion: from Python to COBOL, same semantics.
from time import time st = time() print(sum([n for n in range(2, 6*9**5) if sum(int(i)**5 for i in str(n)) == n]), " ", (time() - st) * 1000, "ms") st = time() nums = list(range(10)) nu = list(range(((6 * 9**5) // 100000) + 1)) numbers = [] p5 = [] for i in nums: p5.append(i**5) for i in nu: im = i * 100000 ...
IDENTIFICATION DIVISION. PROGRAM-ID. DIGIT-FIFTH-POWER. DATA DIVISION. WORKING-STORAGE SECTION. 01 VARIABLES. 03 CANDIDATE PIC 9(6). 03 MAXIMUM PIC 9(6). 03 DIGITS PIC 9 OCCURS 6 TIMES, REDE...
Transform the following Python implementation into COBOL, maintaining the same output and logic.
>>> from itertools import product >>> nuggets = set(range(101)) >>> for s, n, t in product(range(100//6+1), range(100//9+1), range(100//20+1)): nuggets.discard(6*s + 9*n + 20*t) >>> max(nuggets) 43 >>>
IDENTIFICATION DIVISION. PROGRAM-ID. MCNUGGETS. DATA DIVISION. WORKING-STORAGE SECTION. 01 NUGGETS. 03 NUGGET-FLAGS PIC X OCCURS 100 TIMES. 88 IS-NUGGET VALUE 'X'. 01 A PIC 999. 01 B PIC 999. 01...
Keep all operations the same but rewrite the snippet in COBOL.
classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal, str.isdigit, str.isidentifier, str.isnumeric, str.isprintable, str.isspace, str.istitle) for stringclass in classes: chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i))) print('\nString clas...
identification division. program-id. determine. environment division. configuration section. repository. function all intrinsic. data division. working-storage section. 01 tx pic x. 01 lower-8bit pic x(256). 01 upper-8bit pic x(256). ...
Rewrite this program in COBOL while keeping its functionality equivalent to the Python version.
from __future__ import division def jaro(s, t): s_len = len(s) t_len = len(t) if s_len == 0 and t_len == 0: return 1 match_distance = (max(s_len, t_len) // 2) - 1 s_matches = [False] * s_len t_matches = [False] * t_len matches = 0 transpositions = 0 for i in ran...
identification division. program-id. JaroDistance. environment division. configuration section. repository. function length intrinsic function trim intrinsic function max intrinsic function min intrinsic . data division...
Write the same code in COBOL as shown below in Python.
def dt_creator(): print("\n\nCREATING THE DECISION TABLE\n") conditions = input("Input conditions, in order, separated by commas: ") conditions = [c.strip() for c in conditions.split(',')] print( ("\nThat was %s conditions:\n " % len(conditions)) + '\n '.join("%i: %s" % x for x in enumera...
>> SOURCE FORMAT FREE identification division. program-id. 'decisiontable'. environment division. configuration section. repository. function all intrinsic. data division. working-storage section. 01 conditions. 03 notprinting pic x. 03 flashing pic x. 03 notrecognized pic x. procedure ...
Generate an equivalent COBOL version of this Python code.
with open('unixdict.txt', 'rt') as f: for line in f.readlines(): if not any(c in 'aiou' for c in line) and sum(c=='e' for c in line)>3: print(line.strip())
IDENTIFICATION DIVISION. PROGRAM-ID. E-WORDS. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT DICT ASSIGN TO DISK ORGANIZATION LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD DICT LABEL RECORD...
Generate an equivalent COBOL version of this Python code.
from functools import reduce from operator import mul def p(n): digits = [int(c) for c in str(n)] return not 0 in digits and ( 0 != (n % reduce(mul, digits, 1)) ) and all(0 == n % d for d in digits) def main(): xs = [ str(n) for n in range(1, 1000) if p(n) ...
IDENTIFICATION DIVISION. PROGRAM-ID. DIV-BY-DGTS-BUT-NOT-PROD. DATA DIVISION. WORKING-STORAGE SECTION. 01 CALCULATION. 02 N PIC 9(4). 02 DGT-PROD PIC 9(3). 02 NSTART PIC 9. 02 D PIC 9. ...
Produce a functionally identical COBOL code for the snippet given in Python.
import datetime weekDays = ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday") thisXMas = datetime.date(2021,12,25) thisXMasDay = thisXMas.weekday() thisXMasDayAsString = weekDays[thisXMasDay] print("This year's Christmas is on a {}".format(thisXMasDayAsString)) nextNewYear = datetime.date(2022,...
IDENTIFICATION DIVISION. PROGRAM-ID. XMASNY. DATA DIVISION. WORKING-STORAGE SECTION. 01 WEEKDAYS. 03 DAY-NAMES. 05 FILLER PIC X(9) VALUE "Saturday ". 05 FILLER PIC X(9) VALUE "Sunday ". 05 FILLER PIC X(9) VALUE "Monday ...
Port the following code from Python to COBOL with equivalent syntax and logic.
def p(n): return 9 < n and (9 < n % 16 or p(n // 16)) def main(): xs = [ str(n) for n in range(1, 1 + 500) if p(n) ] print(f'{len(xs)} matches for the predicate:\n') print( table(6)(xs) ) def chunksOf(n): def go(xs): return ( ...
IDENTIFICATION DIVISION. PROGRAM-ID. BASE-16. DATA DIVISION. WORKING-STORAGE SECTION. 01 VARIABLES COMP. 02 STRP PIC 99 VALUE 1. 02 N PIC 999. 02 NTEMP PIC 999. 02 N16 PIC 999. ...
Port the provided Python code into COBOL while preserving the original functionality.
def p(n): return 9 < n and (9 < n % 16 or p(n // 16)) def main(): xs = [ str(n) for n in range(1, 1 + 500) if p(n) ] print(f'{len(xs)} matches for the predicate:\n') print( table(6)(xs) ) def chunksOf(n): def go(xs): return ( ...
IDENTIFICATION DIVISION. PROGRAM-ID. BASE-16. DATA DIVISION. WORKING-STORAGE SECTION. 01 VARIABLES COMP. 02 STRP PIC 99 VALUE 1. 02 N PIC 999. 02 NTEMP PIC 999. 02 N16 PIC 999. ...
Produce a language-to-language conversion: from Python to COBOL, same semantics.
var num = 12 var pointer = ptr(num) print pointer @unsafe pointer.addr = 0xFFFE
data division. working-storage section. 01 ptr usage pointer. 01 var pic x(64). procedure division. set ptr to address of var.
Please provide an equivalent version of this Python code in COBOL.
infile = open('infile.dat', 'rb') outfile = open('outfile.dat', 'wb') while True: onerecord = infile.read(80) if len(onerecord) < 80: break onerecordreversed = bytes(reversed(onerecord)) outfile.write(onerecordreversed) infile.close() outfile.close()
identification division. program-id. lrecl80. environment division. configuration section. repository. function all intrinsic. input-output section. file-control. select infile assign to infile-name ...
Produce a functionally identical COBOL code for the snippet given in Python.
import urllib.request from collections import Counter urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt") dictionary = open("unixdict.txt","r") wordList = dictionary.read().split('\n') dictionary.close() for word in wordList: if len(word)>10: frequency = Co...
IDENTIFICATION DIVISION. PROGRAM-ID. ALL-VOWELS. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT DICT ASSIGN TO DISK ORGANIZATION LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD DICT LABEL REC...
Generate a COBOL translation of this Python snippet without changing its computational steps.
while 1: print "SPAM"
IDENTIFICATION DIVISION. PROGRAM-ID. Spam. PROCEDURE DIVISION. PERFORM UNTIL 1 <> 1 DISPLAY "SPAM" END-PERFORM GOBACK .
Convert the following code from Python to COBOL, ensuring the logic remains intact.
def multiply(x, y): return x * y
IDENTIFICATION DIVISION. PROGRAM-ID. myTest. DATA DIVISION. WORKING-STORAGE SECTION. 01 x PIC 9(3) VALUE 3. 01 y PIC 9(3) VALUE 2. 01 z PIC 9(9). PROCEDURE DIVISION. CALL "myMultiply" USING BY CONTENT x, BY CONTENT y, ...
Keep all operations the same but rewrite the snippet in COBOL.
import os def get_windows_terminal(): from ctypes import windll, create_string_buffer h = windll.kernel32.GetStdHandle(-12) csbi = create_string_buffer(22) res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) if not res: return 80, 25 import struct (bufx, bufy, curx, cury, watt...
IDENTIFICATION DIVISION. PROGRAM-ID. terminal-dimensions. DATA DIVISION. WORKING-STORAGE SECTION. 01 num-lines PIC 9(3). 01 num-cols PIC 9(3). SCREEN SECTION. 01 display-screen. 03 LINE 01 COL 01 PIC 9(3) FROM num-lines. 03 LINE 01 CO...
Write the same code in COBOL as shown below in Python.
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> x = [n for n in range(1000) if str(sum(int(d) for d in str(n))) in str(n)] >>> len(x) 48 >>> for i in range(0, len(x), (stride:= 10)): print(str(x[i...
IDENTIFICATION DIVISION. PROGRAM-ID. SUM-SUBSTRING. DATA DIVISION. WORKING-STORAGE SECTION. 01 CALCULATION. 02 N PIC 9999. 02 X PIC 9. 02 DSUM PIC 99. 02 N-DIGITS REDEFINES N. 03 ND P...
Please provide an equivalent version of this Python code in COBOL.
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> x = [n for n in range(1000) if str(sum(int(d) for d in str(n))) in str(n)] >>> len(x) 48 >>> for i in range(0, len(x), (stride:= 10)): print(str(x[i...
IDENTIFICATION DIVISION. PROGRAM-ID. SUM-SUBSTRING. DATA DIVISION. WORKING-STORAGE SECTION. 01 CALCULATION. 02 N PIC 9999. 02 X PIC 9. 02 DSUM PIC 99. 02 N-DIGITS REDEFINES N. 03 ND P...
Rewrite the snippet below in COBOL so it works the same as the original Python code.
>>> with open('/dev/tape', 'w') as t: t.write('Hi Tape!\n') ... >>>
>>SOURCE FORMAT IS FREE IDENTIFICATION DIVISION. PROGRAM-ID. MAKE-TAPE-FILE. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT TAPE-FILE ASSIGN "./TAPE.FILE" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD TAPE-FILE. 01 TAPE-FILE-RECORD PIC X(51). PROCEDURE ...
Write a version of this Python function in COBOL with identical behavior.
from itertools import islice class Recamans(): "Recamán's sequence generator callable class" def __init__(self): self.a = None self.n = None def __call__(self): "Recamán's sequence generator" nxt = 0 a, n = {nxt}, 0 self.a = a self.n = n ...
IDENTIFICATION DIVISION. PROGRAM-ID. RECAMAN. DATA DIVISION. WORKING-STORAGE SECTION. 01 RECAMAN-SEQUENCE COMP. 02 A PIC 999 OCCURS 99 TIMES INDEXED BY I. 02 N PIC 999 VALUE 0. 01 VARIABLES COMP. 02 ADDC PIC S...
Translate the given Python code snippet into COBOL without altering its behavior.
from itertools import islice class Recamans(): "Recamán's sequence generator callable class" def __init__(self): self.a = None self.n = None def __call__(self): "Recamán's sequence generator" nxt = 0 a, n = {nxt}, 0 self.a = a self.n = n ...
IDENTIFICATION DIVISION. PROGRAM-ID. RECAMAN. DATA DIVISION. WORKING-STORAGE SECTION. 01 RECAMAN-SEQUENCE COMP. 02 A PIC 999 OCCURS 99 TIMES INDEXED BY I. 02 N PIC 999 VALUE 0. 01 VARIABLES COMP. 02 ADDC PIC S...
Generate a COBOL translation of this Python snippet without changing its computational steps.
from itertools import zip_longest def beadsort(l): return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0))) print(beadsort([5,3,1,7,4,1,1]))
>>SOURCE FORMAT FREE identification division. program-id. beadsort. environment division. configuration section. repository. function all intrinsic. data division. working-storage section. 01 filler. 03 row occurs 9 pic x(9). 03 r pic 99. 03 r1 pic 99. 03 r2 pic 99. 03 pole pic 99. ...
Maintain the same structure and functionality when rewriting this code in COBOL.
import argparse from argparse import Namespace import datetime import shlex def parse_args(): 'Set up, parse, and return arguments' parser = argparse.ArgumentParser(epilog=globals()['__doc__']) parser.add_argument('command', choices='add pl plc pa'.split(), help=) par...
IDENTIFICATION DIVISION. PROGRAM-ID. simple-database. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT OPTIONAL database-file ASSIGN Database-Path ORGANIZATION INDEXED ACCESS SEQUENTIAL RECORD KEY data-title ...
Port the following code from Python to COBOL with equivalent syntax and logic.
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //...
IDENTIFICATION DIVISION. PROGRAM-ID. TAU-FUNCTION. DATA DIVISION. WORKING-STORAGE SECTION. 01 TAU-VARS. 03 TOTAL PIC 999. 03 N PIC 999. 03 FILLER REDEFINES N. 05 FILLER PIC 99. ...
Port the provided Python code into COBOL while preserving the original functionality.
def factorize(n): assert(isinstance(n, int)) if n < 0: n = -n if n < 2: return k = 0 while 0 == n%2: k += 1 n //= 2 if 0 < k: yield (2,k) p = 3 while p*p <= n: k = 0 while 0 == n%p: k += 1 n //...
IDENTIFICATION DIVISION. PROGRAM-ID. TAU-FUNCTION. DATA DIVISION. WORKING-STORAGE SECTION. 01 TAU-VARS. 03 TOTAL PIC 999. 03 N PIC 999. 03 FILLER REDEFINES N. 05 FILLER PIC 99. ...
Port the provided Python code into COBOL while preserving the original functionality.
def mertens(count): m = [None, 1] for n in range(2, count+1): m.append(1) for k in range(2, n+1): m[n] -= m[n//k] return m ms = mertens(1000) print("The first 99 Mertens numbers are:") print(" ", end=' ') col = 1 for n in ms[1:100]: print("{:2d}".format(n), end='...
IDENTIFICATION DIVISION. PROGRAM-ID. MERTENS. DATA DIVISION. WORKING-STORAGE SECTION. 01 VARIABLES. 03 M PIC S99 OCCURS 1000 TIMES. 03 N PIC 9(4). 03 K PIC 9(4). 03 V PIC 9(4). 03 IS-ZE...
Keep all operations the same but rewrite the snippet in COBOL.
def product_of_divisors(n): assert(isinstance(n, int) and 0 < n) ans = i = j = 1 while i*i <= n: if 0 == n%i: ans *= i j = n//i if j != i: ans *= j i += 1 return ans if __name__ == "__main__": print([product_of_divisors(n) for ...
IDENTIFICATION DIVISION. PROGRAM-ID. PRODUCT-OF-DIVISORS. DATA DIVISION. WORKING-STORAGE SECTION. 01 VARIABLES. 03 DIVISOR-PRODUCTS PIC 9(9) OCCURS 50 TIMES. 03 NUM PIC 999. 03 MUL PIC 999. 01 OUTPUT-FORM...
Please provide an equivalent version of this Python code in COBOL.
def product_of_divisors(n): assert(isinstance(n, int) and 0 < n) ans = i = j = 1 while i*i <= n: if 0 == n%i: ans *= i j = n//i if j != i: ans *= j i += 1 return ans if __name__ == "__main__": print([product_of_divisors(n) for ...
IDENTIFICATION DIVISION. PROGRAM-ID. PRODUCT-OF-DIVISORS. DATA DIVISION. WORKING-STORAGE SECTION. 01 VARIABLES. 03 DIVISOR-PRODUCTS PIC 9(9) OCCURS 50 TIMES. 03 NUM PIC 999. 03 MUL PIC 999. 01 OUTPUT-FORM...
Please provide an equivalent version of this Python code in COBOL.
import random class Card(object): suits = ("Clubs","Hearts","Spades","Diamonds") pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace") def __init__(self, pip,suit): self.pip=pip self.suit=suit def __str__(self): return "%s %s"%(self.pip,self.suit) class De...
identification division. program-id. playing-cards. environment division. configuration section. repository. function all intrinsic. data division. working-storage section. 77 card usage index. 01 deck. 05 cards occurs 52 ...
Translate this program into COBOL but keep the logic exactly as in Python.
import sys import calendar year = 2013 if len(sys.argv) > 1: try: year = int(sys.argv[-1]) except ValueError: pass for month in range(1, 13): last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month)) print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sun...
program-id. last-sun. data division. working-storage section. 1 wk-date. 2 yr pic 9999. 2 mo pic 99 value 1. 2 da pic 99 value 1. 1 rd-date redefines wk-date pic 9(8). 1 binary. 2 int-date pic 9(8). 2 dow pic 9(4). 2 sunday pic 9(...
Generate an equivalent COBOL version of this Python code.
import sys import calendar year = 2013 if len(sys.argv) > 1: try: year = int(sys.argv[-1]) except ValueError: pass for month in range(1, 13): last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month)) print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sun...
program-id. last-sun. data division. working-storage section. 1 wk-date. 2 yr pic 9999. 2 mo pic 99 value 1. 2 da pic 99 value 1. 1 rd-date redefines wk-date pic 9(8). 1 binary. 2 int-date pic 9(8). 2 dow pic 9(4). 2 sunday pic 9(...
Change the programming language of this snippet from Python to COBOL without modifying what it does.
import math szamok=[] limit = 1000 for i in range(1,int(math.ceil(math.sqrt(limit))),2): num = i*i if (num < 1000 and num > 99): szamok.append(num) print(szamok)
IDENTIFICATION DIVISION. PROGRAM-ID. ODD-AND-SQUARE. DATA DIVISION. WORKING-STORAGE SECTION. 01 VARIABLES. 03 N PIC 999. 03 SQR PIC 9999 VALUE 0. 03 FILLER REDEFINES SQR. 05 FILLER PIC 999. ...
Translate the given Python code snippet into COBOL without altering its behavior.
def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def digSum(n, b): s = 0 while n: s += (n % b) n = n // b return s if __name__ == '__main__': for n in range(11, 99): if isPrime(digSum(n**3, 10)) an...
IDENTIFICATION DIVISION. PROGRAM-ID. SQUARE-CUBE-DIGITS-PRIME. DATA DIVISION. WORKING-STORAGE SECTION. 01 NUMBER-SEARCH-VARS. 03 CAND PIC 9(6). 03 SQUARE PIC 9(6). 03 CUBE PIC 9(6). 01 SUM-DIGITS...
Translate the given Python code snippet into COBOL without altering its behavior.
from fractions import Fraction def harmonic_series(): n, h = Fraction(1), Fraction(1) while True: yield h h += 1 / (n + 1) n += 1 if __name__ == '__main__': from itertools import islice for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)): print(n,...
IDENTIFICATION DIVISION. PROGRAM-ID. HARMONIC. DATA DIVISION. WORKING-STORAGE SECTION. 01 VARS. 03 N PIC 9(5) VALUE ZERO. 03 HN PIC 9(2)V9(12) VALUE ZERO. 03 INT PIC 99 VALUE ZERO. 01 OUT-VARS. 03 POS ...
Generate a COBOL translation of this Python snippet without changing its computational steps.
var x = 0 var y = 0 There are also multi-line comments Everything inside of ] discard
* an asterisk in 7th column comments the line out
Change the following Python code into COBOL without altering its purpose.
limit = 1000 print("working...") def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def issquare(x): for n in range(1,x+1): if (x == n*n): return 1 return 0 for n in range(limit-1): if issquare(n) and isprime(n+1): print(n,end=" ") print() prin...
IDENTIFICATION DIVISION. PROGRAM-ID. SQUARE-PLUS-1-PRIME. DATA DIVISION. WORKING-STORAGE SECTION. 01 N PIC 999. 01 P PIC 9999 VALUE ZERO. 01 PRIMETEST. 03 DSOR PIC 9999. 03 PRIME-FLAG PIC X...