Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Transform the following Go implementation into Factor, maintaining the same output and logic.
package main import ( "fmt" "rcu" ) func main() { var primes []int candidates := []int{3, 33} for i := 303; i <= 393; i += 10 { candidates = append(candidates, i) } for i := 3003; i <= 3993; i += 10 { candidates = append(candidates, i) } for _, cand := range candida...
USING: formatting grouping io kernel lists lists.lazy math math.functions math.primes sequences ; : under ( list n -- list' ) '[ _ < ] lwhile ; : (surrounded) ( n -- list ) [ 1list 1 lfrom ] keep dup dup '[ 10^ _ * _ + [ [ 10 + ] lfrom-by ] keep dup _ / + 10 - under ] lmap-lazy lconcat lappend-lazy ; : s...
Generate a Factor translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "rcu" ) const MAX = 1e7 - 1 var primes = rcu.Primes(MAX) func specialNP(limit int, showAll bool) { if showAll { fmt.Println("Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:") } count := 0 for i := 1; i < len(primes); i++ { p2 := primes[i] ...
USING: kernel lists lists.lazy math math.primes math.primes.lists prettyprint sequences ; lprimes dup cdr lzip [ sum 1 - prime? ] lfilter [ second 100 < ] lwhile [ . ] leach
Produce a language-to-language conversion: from Go to Factor, same semantics.
package main import ( "fmt" "rcu" ) const MAX = 1e7 - 1 var primes = rcu.Primes(MAX) func specialNP(limit int, showAll bool) { if showAll { fmt.Println("Neighbor primes, p1 and p2, where p1 + p2 - 1 is prime:") } count := 0 for i := 1; i < len(primes); i++ { p2 := primes[i] ...
USING: kernel lists lists.lazy math math.primes math.primes.lists prettyprint sequences ; lprimes dup cdr lzip [ sum 1 - prime? ] lfilter [ second 100 < ] lwhile [ . ] leach
Produce a functionally identical Factor code for the snippet given in Go.
package main import "fmt" func isPrime(n int) bool { return n == 2 || n == 3 || n == 5 || n == 7 || n == 11 || n == 13 || n == 17 } func main() { count := 0 var d []int fmt.Println("Strange plus numbers in the open interval (100, 500) are:\n") for i := 101; i < 500; i++ { d = d[:0] ...
USING: grouping grouping.extras io kernel math math.primes math.ranges math.text.utils prettyprint sequences ; : strange+? ( n -- ? ) dup 10 < [ drop f ] [ 1 digit-groups [ + ] 2 clump-map [ prime? ] all? ] if ; "Strange plus numbers in (100, 500):" print nl 100 500 (a,b) [ strange+? ] filter dup 10 group [ [...
Port the following code from Go to Factor with equivalent syntax and logic.
package main import "fmt" func isPrime(n int) bool { return n == 2 || n == 3 || n == 5 || n == 7 || n == 11 || n == 13 || n == 17 } func main() { count := 0 var d []int fmt.Println("Strange plus numbers in the open interval (100, 500) are:\n") for i := 101; i < 500; i++ { d = d[:0] ...
USING: grouping grouping.extras io kernel math math.primes math.ranges math.text.utils prettyprint sequences ; : strange+? ( n -- ? ) dup 10 < [ drop f ] [ 1 digit-groups [ + ] 2 clump-map [ prime? ] all? ] if ; "Strange plus numbers in (100, 500):" print nl 100 500 (a,b) [ strange+? ] filter dup 10 group [ [...
Produce a language-to-language conversion: from Go to Factor, same semantics.
package main import ( "fmt" "math/big" ) var b = new(big.Int) func isSPDSPrime(n uint64) bool { nn := n for nn > 0 { r := nn % 10 if r != 2 && r != 3 && r != 5 && r != 7 { return false } nn /= 10 } b.SetUint64(n) if b.ProbablyPrime(0) { ...
USING: combinators.short-circuit io lists lists.lazy math math.parser math.primes prettyprint sequences ; IN: rosetta-code.smarandache-naive : smarandache? ( n -- ? ) { [ number>string string>digits [ prime? ] all? ] [ prime? ] } 1&& ; : smarandache ( -- list ) 1 lfrom [ smarandache? ] lfilter...
Rewrite the snippet below in Factor so it works the same as the original Go code.
package main import ( "fmt" "log" "strings" ) const dimensions int = 8 func setupMagicSquareData(d int) ([][]int, error) { var output [][]int if d < 4 || d%4 != 0 { return [][]int{}, fmt.Errorf("Square dimension must be a positive number which is divisible by 4") } var bits uint = 0x9669 size := d * d mu...
USING: arrays combinators.short-circuit formatting fry generalizations kernel math math.matrices prettyprint sequences ; IN: rosetta-code.doubly-even-magic-squares : top? ( loc n -- ? ) [ second ] dip 1/4 * < ; : bottom? ( loc n -- ? ) [ second ] dip 3/4 * >= ; : left? ( loc n -- ? ) [ first ] dip 1/4 * < ; : ...
Write the same code in Factor as shown below in Go.
package main import ( "fmt" "math" ) func sieve(limit uint64) []uint64 { primes := []uint64{2} c := make([]bool, limit+1) p := uint64(3) for { p2 := p * p if p2 > limit { break } for i := p2; i <= limit; i += 2 * p { c[i] = true ...
USING: formatting grouping io kernel math math.functions math.primes.factors math.ranges sequences sets ; IN: rosetta-code.square-free : sq-free? ( n -- ? ) factors all-unique? ; : numbers-per-line ( m -- n ) log10 >integer 2 + 80 swap /i ; : sq-free-show ( from to -- ) 2dup "Square-free integers from %d to %d:...
Generate a Factor translation of this Go snippet without changing its computational steps.
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { units := []string{ "tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer", } convs := []float32{ 0.025...
USING: formatting inverse io kernel math prettyprint quotations sequences units.imperial units.si vocabs ; IN: rosetta-code.units.russian : arshin ( n -- d ) 2+1/3 * feet ; : tochka ( n -- d ) 1/2800 * arshin ; : liniya ( n -- d ) 1/280 * arshin ; : dyuim ( n -- d ) 1/28 * arshin ; : vershok ( n -- d ) 1/16 * ars...
Can you help me rewrite this code in Factor instead of Go, keeping it the same logically?
package main import "fmt" type pair struct{ x, y int } func main() { const max = 1685 var all []pair for a := 2; a < max; a++ { for b := a + 1; b < max-a; b++ { all = append(all, pair{a, b}) } } fmt.Println("There are", len(all), "pairs where a+b <", max, "(and a<b)") products := countProducts(all...
USING: combinators.short-circuit fry kernel literals math math.ranges memoize prettyprint sequences sets tools.time ; IN: rosetta-code.sum-and-product CONSTANT: s1 $[ 2 100 [a,b] dup cartesian-product concat [ first2 { [ < ] [ + 100 < ] } 2&& ] filter ] : quot-eq ( pair quot -- seq ) [ s1 ] 2dip tuck '[ @...
Generate an equivalent Factor version of this Go code.
package main import ( "fmt" "math" "math/big" "reflect" "strings" "unsafe" ) func Float64IsInt(f float64) bool { _, frac := math.Modf(f) return frac == 0 } func Float32IsInt(f float32) bool { return Float64IsInt(float64(f)) } func Complex128IsInt(c complex128) bool { return imag(c) == 0 && Float6...
USING: formatting io kernel math math.functions sequences ; IN: rosetta-code.test-integerness GENERIC: integral? ( n -- ? ) M: real integral? [ ] [ >integer ] bi number= ; M: complex integral? >rect [ integral? ] [ 0 number= ] bi* and ; GENERIC# fuzzy-int? 1 ( n tolerance -- ? ) M: real fuzzy-int? [ dup round -...
Ensure the translated Factor code behaves exactly like the original Go snippet.
package main import ( "fmt" "math" "rcu" ) func main() { limit := int(math.Log(1e7) * 1e7 * 1.2) primes := rcu.Primes(limit) fmt.Println("The first 20 pairs of natural numbers whose sum is prime are:") for i := 1; i <= 20; i++ { p := primes[i] hp := p / 2 fmt.Print...
USING: arrays formatting kernel lists lists.lazy math math.primes.lists sequences ; 20 lprimes cdr [ 2/ dup 1 + 2array ] lmap-lazy ltake [ dup sum suffix "%d + %d = %d\n" vprintf ] leach
Write the same code in Factor as shown below in Go.
package main import ( "fmt" "rcu" ) func main() { limit := int(1e10 - 1) primes := rcu.Primes(limit) maxI := 0 maxDiff := 0 nextStop := 10 fmt.Println("The largest differences between adjacent primes under the following limits is:") for i := 1; i < len(primes); i++ { diff :...
USING: arrays formatting kernel lists lists.lazy math math.order math.primes.lists sequences ; lprimes dup cdr lzip [ first2 2dup swap - -rot 3array ] lmap-lazy [ second 1e6 < ] lwhile { 0 } [ max ] foldl "Largest difference in adjacent primes under a million: %d between %d and %d.\n" vprintf
Port the following code from Go to Factor with equivalent syntax and logic.
package main import ( "fmt" "rcu" ) func main() { numbers1 := [5]int{5, 45, 23, 21, 67} numbers2 := [5]int{43, 22, 78, 46, 38} numbers3 := [5]int{9, 98, 12, 54, 53} primes := [5]int{} for n := 0; n < 5; n++ { max := rcu.Max(rcu.Max(numbers1[n], numbers2[n]), numbers3[n]) if...
USING: math math.order math.primes prettyprint sequences ; { 5 45 23 21 67 } { 43 22 78 46 38 } { 9 98 12 54 53 } [ max max 1 - next-prime ] 3map .
Ensure the translated Factor code behaves exactly like the original Go snippet.
package main import ( "fmt" ) type any = interface{} func uselessFunc(uselessParam any) { if true { } else { fmt.Println("Never called") } for range []any{} { fmt.Println("Never called") } for false { fmt.Println("Never called") } fmt.Print("")...
dupd reach
Write the same algorithm in Factor as shown in this Go implementation.
package main import ( "fmt" "math/big" "strconv" "strings" ) func commatize(s string) string { neg := false if strings.HasPrefix(s, "-") { s = s[1:] neg = true } le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } if !neg { ...
USING: formatting kernel lists lists.lazy math math.functions present sequences tools.memory.private ; : powers-of-6 ( -- list ) 0 lfrom [ 6 swap ^ ] lmap-lazy ; : smallest ( m -- n ) present powers-of-6 [ present subseq? ] with lfilter car ; 22 [ dup smallest commas "%2d %s\n" printf ] each-integer
Please provide an equivalent version of this Go code in Factor.
package main import ( "fmt" "rcu" ) func main() { sum := 0 for _, p := range rcu.Primes(2e6 - 1) { sum += p } fmt.Printf("The sum of all primes below 2 million is %s.\n", rcu.Commatize(sum)) }
USING: math.primes prettyprint sequences ; 2,000,000 primes-upto sum .
Transform the following Go implementation into Factor, maintaining the same output and logic.
package main import ( "fmt" "rcu" "strconv" "strings" ) func contains(list []int, s int) bool { for _, e := range list { if e == s { return true } } return false } func main() { fmt.Println("Steady squares under 10,000:") finalDigits := []int{1, 5, 6} ...
USING: formatting kernel math math.functions math.functions.integer-logs prettyprint sequences tools.memory.private ; : steady? ( n -- ? ) [ sq ] [ integer-log10 1 + 10^ mod ] [ = ] tri ; 1000 <iota> { 1 5 6 } [ [ 10 * ] dip + dup steady? [ dup sq commas "%4d^2 = %s\n" printf ] [ drop ] if ] cartesian-eac...
Translate the given Go code snippet into Factor without altering its behavior.
package main import ( "fmt" "rcu" ) func allButOneEven(prime int) bool { digits := rcu.Digits(prime, 10) digits = digits[:len(digits)-1] allEven := true for _, d := range digits { if d&1 == 1 { allEven = false break } } return allEven } func mai...
USING: grouping io lists lists.lazy literals math math.primes numspec prettyprint ; << DIGIT: o 357 DIGIT: q 1379 DIGIT: e 2468 DIGIT: E 02468 NUMSPEC: one-odd-candidates o eq eEq ... ; >> CONSTANT: p $[ one-odd-candidates [ prime? ] lfilter ] "Primes with one odd digit under 1,000:" print p [ 1000 < ] lwhile list>...
Convert this Go snippet to Factor and keep its semantics consistent.
package main import ( "fmt" "rcu" ) func allButOneEven(prime int) bool { digits := rcu.Digits(prime, 10) digits = digits[:len(digits)-1] allEven := true for _, d := range digits { if d&1 == 1 { allEven = false break } } return allEven } func mai...
USING: grouping io lists lists.lazy literals math math.primes numspec prettyprint ; << DIGIT: o 357 DIGIT: q 1379 DIGIT: e 2468 DIGIT: E 02468 NUMSPEC: one-odd-candidates o eq eEq ... ; >> CONSTANT: p $[ one-odd-candidates [ prime? ] lfilter ] "Primes with one odd digit under 1,000:" print p [ 1000 < ] lwhile list>...
Transform the following Go implementation into Factor, maintaining the same output and logic.
package main import "fmt" func sieve(limit uint64) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true for i := uint64(4); i < limit; i += 2 { c[i] = true } p := uint64(3) for { p2 := p * p if p2 >= limit { break } ...
USING: fry interpolate kernel literals math math.primes sequences tools.memory.private ; IN: rosetta-code.safe-primes CONSTANT: primes $[ 10,000,000 primes-upto ] : safe/unsafe ( -- safe unsafe ) primes [ 1 - 2/ prime? ] partition ; : count< ( seq n -- str ) '[ _ < ] count commas ; : seq>commas ( seq -- str ) [...
Please provide an equivalent version of this Go code in Factor.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(499) var sprimes []int for _, p := range primes { digits := rcu.Digits(p, 10) var b1 = true for _, d := range digits { if !rcu.IsPrime(d) { b1 = false break ...
USING: combinators kernel math math.primes prettyprint sequences ; :: ssp? ( n -- ? ) { { [ n prime? not ] [ f ] } { [ n 10 < ] [ t ] } { [ n 100 mod prime? not ] [ f ] } { [ n 10 mod prime? not ] [ f ] } { [ n 10 /i prime? not ] [ f ] } { [ n 100 < ] [ t ] } ...
Produce a functionally identical Factor code for the snippet given in Go.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(499) var sprimes []int for _, p := range primes { digits := rcu.Digits(p, 10) var b1 = true for _, d := range digits { if !rcu.IsPrime(d) { b1 = false break ...
USING: combinators kernel math math.primes prettyprint sequences ; :: ssp? ( n -- ? ) { { [ n prime? not ] [ f ] } { [ n 10 < ] [ t ] } { [ n 100 mod prime? not ] [ f ] } { [ n 10 mod prime? not ] [ f ] } { [ n 10 /i prime? not ] [ f ] } { [ n 100 < ] [ t ] } ...
Maintain the same structure and functionality when rewriting this code in Factor.
package main import ( "fmt" "rcu" ) func countDivisors(n int) int { count := 0 i := 1 k := 1 if n%2 == 1 { k = 2 } for ; i*i <= n; i += k { if n%i == 0 { count++ j := n / i if j != i { count++ } } ...
USING: formatting grouping io kernel math math.primes math.primes.factors math.ranges sequences sequences.extras ; FROM: math.extras => integer-sqrt ; : odd-prime? ( n -- ? ) dup 2 = [ drop f ] [ prime? ] if ; : pdc-upto ( n -- seq ) integer-sqrt [1,b] [ sq ] [ divisors length odd-prime? ] map-filter ; 100,0...
Write the same algorithm in Factor as shown in this Go implementation.
package main import ( "fmt" "go/ast" "go/parser" "strings" "unicode" ) func isValidIdentifier(identifier string) bool { node, err := parser.ParseExpr(identifier) if err != nil { return false } ident, ok := node.(*ast.Ident) return ok && ident.Name == identifier } type runeRanges struct { ranges []stri...
USING: parser see ; \ scan-word-name see
Maintain the same structure and functionality when rewriting this code in Factor.
package main import ( "fmt" "math" ) func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] =...
USING: fry io kernel lists lists.lazy math math.primes prettyprint ; 2 [ 1 lfrom swap '[ sq _ + ] lmap-lazy [ prime? ] lfilter car ] lfrom-by [ 16000 < ] lwhile [ pprint bl ] leach nl
Translate this program into Factor but keep the logic exactly as in Go.
package main import ( "fmt" "math" ) func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] =...
USING: fry io kernel lists lists.lazy math math.primes prettyprint ; 2 [ 1 lfrom swap '[ sq _ + ] lmap-lazy [ prime? ] lfilter car ] lfrom-by [ 16000 < ] lwhile [ pprint bl ] leach nl
Write a version of this Go function in Factor with identical behavior.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(1000) maxSum := 0 for _, p := range primes { maxSum += p } c := rcu.PrimeSieve(maxSum, true) primeSum := 0 var results []int for _, p := range primes { primeSum += p if !c[primeSum] {...
USING: assocs assocs.extras kernel math.primes math.statistics prettyprint ; 1000 primes-upto dup cum-sum zip [ prime? ] filter-values .
Rewrite the snippet below in Factor so it works the same as the original Go code.
package main import ( "fmt" "rcu" "strings" ) var grid = [][]int { { 8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8}, {49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0}, {81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3...
USING: grouping kernel math.matrices math.order prettyprint sequences ; : max-horizontal ( matrix m -- n ) [ <clumps> ] curry map [ product ] matrix-map mmax ; : max-product ( matrix m -- n ) [ dup flip ] dip [ max-horizontal ] curry bi@ max ; { 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08...
Convert the following code from Go to Factor, ensuring the logic remains intact.
package main import ( "fmt" "math/rand" "time" ) const ( op_num = iota op_add op_sub op_mul op_div ) type frac struct { num, denom int } type Expr struct { op int left, right *Expr value frac } var n_cards = 4 var goal = 24 var digit_range = 9 func (x *Expr) String() string { if x.op...
USING: continuations grouping io kernel math math.combinatorics prettyprint quotations random sequences sequences.deep ; IN: rosetta-code.24-game : 4digits ( -- seq ) 4 9 random-integers [ 1 + ] map ; : expressions ( digits -- exprs ) all-permutations [ [ + - * / ] 3 selections [ append ] with map ] map flatt...
Generate an equivalent Factor version of this Go code.
package main import ( "fmt" "math/rand" "time" ) const ( op_num = iota op_add op_sub op_mul op_div ) type frac struct { num, denom int } type Expr struct { op int left, right *Expr value frac } var n_cards = 4 var goal = 24 var digit_range = 9 func (x *Expr) String() string { if x.op...
USING: continuations grouping io kernel math math.combinatorics prettyprint quotations random sequences sequences.deep ; IN: rosetta-code.24-game : 4digits ( -- seq ) 4 9 random-integers [ 1 + ] map ; : expressions ( digits -- exprs ) all-permutations [ [ + - * / ] 3 selections [ append ] with map ] map flatt...
Write the same algorithm in Factor as shown in this Go implementation.
package main import "fmt" const jobs = 12 type environment struct{ seq, cnt int } var ( env [jobs]environment seq, cnt *int ) func hail() { fmt.Printf("% 4d", *seq) if *seq == 1 { return } (*cnt)++ if *seq&1 != 0 { *seq = 3*(*seq) + 1 } else { *seq /= 2 ...
USING: assocs continuations formatting io kernel math math.ranges sequences ; : (next-hailstone) ( count value -- count' value' ) [ 1 + ] [ dup even? [ 2/ ] [ 3 * 1 + ] if ] bi* ; : next-hailstone ( count value -- count' value' ) dup 1 = [ (next-hailstone) ] unless ; : make-environments ( -- seq ) 12 [ 0 ] r...
Change the following Go code into Factor without altering its purpose.
package main import ( "bufio" "errors" "fmt" "go/ast" "go/parser" "go/token" "os" "reflect" ) func main() { in := bufio.NewScanner(os.Stdin) for { fmt.Print("Expr: ") in.Scan() if err := in.Err(); err != nil { fmt.Println(err) re...
USING: arrays combinators eval formatting io kernel listener math.combinatorics prettyprint qw sequences splitting vocabs.parser ; IN: rosetta-code.truth-table : prompt ( -- str ) "Please enter a boolean expression using 1-long" print "variable names and postfix notation. Available" print "operators are an...
Translate this program into Factor but keep the logic exactly as in Go.
package main import ( "bufio" "errors" "fmt" "go/ast" "go/parser" "go/token" "os" "reflect" ) func main() { in := bufio.NewScanner(os.Stdin) for { fmt.Print("Expr: ") in.Scan() if err := in.Err(); err != nil { fmt.Println(err) re...
USING: arrays combinators eval formatting io kernel listener math.combinatorics prettyprint qw sequences splitting vocabs.parser ; IN: rosetta-code.truth-table : prompt ( -- str ) "Please enter a boolean expression using 1-long" print "variable names and postfix notation. Available" print "operators are an...
Write the same algorithm in Factor as shown in this Go implementation.
package main import ( "fmt" "math/big" "strings" "time" ) func main() { start := time.Now() rd := []string{"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"} one := big.NewInt(1) nine := big.NewInt(9) for i := big.NewInt(2); i.Cmp(nine) <= 0; i.Add(i, one) ...
USING: arrays formatting io kernel lists lists.lazy math math.functions math.ranges math.text.utils prettyprint sequences ; IN: rosetta-code.super-d : super-d? ( seq n d -- ? ) tuck ^ * 1 digit-groups subseq? ; : super-d ( d -- list ) [ dup <array> ] [ drop 1 lfrom ] [ ] tri [ super-d? ] curry with lfilter ; ...
Ensure the translated Factor code behaves exactly like the original Go snippet.
package main import ( "fmt" "math/big" "strings" "time" ) func main() { start := time.Now() rd := []string{"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"} one := big.NewInt(1) nine := big.NewInt(9) for i := big.NewInt(2); i.Cmp(nine) <= 0; i.Add(i, one) ...
USING: arrays formatting io kernel lists lists.lazy math math.functions math.ranges math.text.utils prettyprint sequences ; IN: rosetta-code.super-d : super-d? ( seq n d -- ? ) tuck ^ * 1 digit-groups subseq? ; : super-d ( d -- list ) [ dup <array> ] [ drop 1 lfrom ] [ ] tri [ super-d? ] curry with lfilter ; ...
Translate this program into Factor but keep the logic exactly as in Go.
package main import ( "fmt" "math" "math/big" "strings" ) func padovanRecur(n int) []int { p := make([]int, n) p[0], p[1], p[2] = 1, 1, 1 for i := 3; i < n; i++ { p[i] = p[i-2] + p[i-3] } return p } func padovanFloor(n int) []int { var p, s, t, u = new(big.Rat), new(bi...
USING: L-system accessors io kernel make math math.functions memoize prettyprint qw sequences ; CONSTANT: p 1.324717957244746025960908854 CONSTANT: s 1.0453567932525329623 : pfloor ( m -- n ) 1 - p swap ^ s /f .5 + >integer ; MEMO: precur ( m -- n ) dup 3 < [ drop 1 ] [ [ 2 - precur ] [ 3 - precur ] bi + ] i...
Keep all operations the same but rewrite the snippet in Factor.
package main import ( "fmt" "strconv" ) type maybe struct{ value *int } func (m maybe) bind(f func(p *int) maybe) maybe { return f(m.value) } func unit(p *int) maybe { return maybe{p} } func decrement(p *int) maybe { if p == nil { return unit(nil) } else { q := *p - 1 ...
USING: monads ; FROM: monads => do ; 3 maybe-monad return >>= [ 2 * maybe-monad return ] swap call >>= [ 1 + maybe-monad return ] swap call . nothing >>= [ 2 * maybe-monad return ] swap call >>= [ 1 + maybe-monad return ] swap call .
Change the programming language of this snippet from Go to Factor without modifying what it does.
package main import "fmt" type mlist struct{ value []int } func (m mlist) bind(f func(lst []int) mlist) mlist { return f(m.value) } func unit(lst []int) mlist { return mlist{lst} } func increment(lst []int) mlist { lst2 := make([]int, len(lst)) for i, v := range lst { lst2[i] = v + 1 } ...
USING: kernel math monads prettyprint ; FROM: monads => do ; { 3 4 5 } >>= [ 1 + array-monad return ] swap call >>= [ 2 * array-monad return ] swap call .
Please provide an equivalent version of this Go code in Factor.
package main import ( "bufio" "flag" "fmt" "io" "log" "os" "strings" "unicode" ) func main() { log.SetFlags(0) log.SetPrefix("textonyms: ") wordlist := flag.String("wordlist", "wordlist", "file containing the list of words to check") flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(2) } t ...
USING: assocs assocs.extras interpolate io io.encodings.utf8 io.files kernel literals math math.parser prettyprint sequences unicode ; << CONSTANT: src "unixdict.txt" >> CONSTANT: words $[ src utf8 file-lines [ [ letter? ] all? ] filter ] CONSTANT: digits "22233344455566677778889999" : >phone ( str -- n ) [...
Write the same code in Factor as shown below in Go.
package main import ( "fmt" "image" "reflect" ) type t int func (r t) Twice() t { return r * 2 } func (r t) Half() t { return r / 2 } func (r t) Less(r2 t) bool { return r < r2 } func (r t) privateMethod() {} func main() { report(t(0)) report(image.Point{}) } func report(x interface{}) { v := ...
USING: io math prettyprint see ; "The list of methods contained in the generic word + :" print \ + methods . nl "The list of methods specializing on the fixnum class:" print fixnum methods .
Convert the following code from Go to Factor, ensuring the logic remains intact.
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func main() { var e example m := reflect.ValueOf(e).MethodByName("Foo") r := m.Call(nil) fmt.Println(r[0].Int()) }
USING: accessors kernel math prettyprint sequences words ; IN: rosetta-code.unknown-method-call TUPLE: foo num ; C: <foo> foo GENERIC: add5 ( x -- y ) M: foo add5 num>> 5 + ; 42 <foo> "add" "5" append "rosetta-code.unknown-method-call" lookup-word execute .
Ensure the translated Factor code behaves exactly like the original Go snippet.
package main import ( "crypto/sha256" "encoding/hex" "errors" "fmt" "golang.org/x/crypto/ripemd160" ) type Point struct { x, y [32]byte } func (p *Point) SetHex(x, y string) error { if len(x) != 64 || len(y) != 64 { return errors.New("invalid hex string length") } if _,...
USING: checksums checksums.ripemd checksums.sha io.binary kernel math sequences ; IN: rosetta-code.bitcoin.point-address CONSTANT: ALPHABET "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" : btc-checksum ( bytes -- checksum-bytes ) 2 [ sha-256 checksum-bytes ] times 4 head ; : bigint>base58 ( n -- st...
Can you help me rewrite this code in Factor instead of Go, keeping it the same logically?
package main import ( "crypto/sha256" "encoding/hex" "errors" "fmt" "golang.org/x/crypto/ripemd160" ) type Point struct { x, y [32]byte } func (p *Point) SetHex(x, y string) error { if len(x) != 64 || len(y) != 64 { return errors.New("invalid hex string length") } if _,...
USING: checksums checksums.ripemd checksums.sha io.binary kernel math sequences ; IN: rosetta-code.bitcoin.point-address CONSTANT: ALPHABET "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" : btc-checksum ( bytes -- checksum-bytes ) 2 [ sha-256 checksum-bytes ] times 4 head ; : bigint>base58 ( n -- st...
Keep all operations the same but rewrite the snippet in Factor.
package main import ( "fmt" "log" "strconv" "strings" ) func check(err error) { if err != nil { log.Fatal(err) } } func canonicalize(cidr string) string { split := strings.Split(cidr, "/") dotted := split[0] size, err := strconv.Atoi(split[1]) check(err) ...
USING: command-line formatting grouping io kernel math.parser namespaces prettyprint sequences splitting ; IN: rosetta-code.canonicalize-cidr command-line get [ lines ] when-empty [ "/" split first2 string>number swap "." split [ string>number "%08b" sprintf ] map "" join over cut length ...
Please provide an equivalent version of this Go code in Factor.
package main import ( "fmt" "log" "strconv" "strings" ) func check(err error) { if err != nil { log.Fatal(err) } } func canonicalize(cidr string) string { split := strings.Split(cidr, "/") dotted := split[0] size, err := strconv.Atoi(split[1]) check(err) ...
USING: command-line formatting grouping io kernel math.parser namespaces prettyprint sequences splitting ; IN: rosetta-code.canonicalize-cidr command-line get [ lines ] when-empty [ "/" split first2 string>number swap "." split [ string>number "%08b" sprintf ] map "" join over cut length ...
Write the same code in Factor as shown below in Go.
package main import ( "fmt" "math/big" ) func main() { one := big.NewInt(1) pm := big.NewInt(1) var px, nx int var pb big.Int primes(4000, func(p int64) bool { pm.Mul(pm, pb.SetInt64(p)) px++ if pb.Add(pm, one).ProbablyPrime(0) || pb.Sub(pm, one).Pro...
USING: kernel lists lists.lazy math math.primes prettyprint sequences ; : pprime? ( n -- ? ) nprimes product [ 1 + ] [ 1 - ] bi [ prime? ] either? ; 10 1 lfrom [ pprime? ] <lazy-filter> ltake list>array .
Produce a functionally identical Factor code for the snippet given in Go.
package main import ( "fmt" "math/big" ) func main() { var n, p int64 fmt.Printf("A sample of permutations from 1 to 12:\n") for n = 1; n < 13; n++ { p = n / 3 fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of combinations from 10 to 60:\n") for n = 10; n ...
USING: math.combinatorics prettyprint ; 1000 10 nCk . 1000 10 nPk .
Maintain the same structure and functionality when rewriting this code in Factor.
package main import "fmt" func sieve(limit int) []int { var primes []int c := make([]bool, limit + 1) p := 3 p2 := p * p for p2 <= limit { for i := p2; i <= limit; i += 2 * p { c[i] = true } for ok := true; ok; ok = c[p] { p += 2 } ...
USING: formatting fry io kernel math math.functions math.primes math.primes.factors memoize prettyprint sequences ; IN: rosetta-code.long-primes : period-length ( p -- len ) [ 1 - divisors ] [ '[ 10 swap _ ^mod 1 = ] ] bi find nip ; MEMO: long-prime? ( p -- ? ) [ period-length ] [ 1 - ] bi = ; : .lp<=500 ( -- ) ...
Translate this program into Factor but keep the logic exactly as in Go.
package main import ( "fmt" "log" "math" "time" ) const layout = "2006-01-02" var cycles = [3]string{"Physical day ", "Emotional day", "Mental day "} var lengths = [3]int{23, 28, 33} var quadrants = [4][2]string{ {"up and rising", "peak"}, {"up but falling", "transition"}, {"down and f...
USING: calendar calendar.parser formatting io kernel math math.constants math.functions ; : days-between ( ymd-str ymd-str -- n ) [ ymd>timestamp ] bi@ time- duration>days abs ; : trend ( pos len -- str ) / 4 * floor 3 divisor? "↑" "↓" ? ; : percent ( pos len -- x ) [ 2pi * ] [ / sin 100 * ] bi* ; : .day ( days...
Change the following Go code into Factor without altering its purpose.
package main import ( "fmt" "log" "math" "time" ) const layout = "2006-01-02" var cycles = [3]string{"Physical day ", "Emotional day", "Mental day "} var lengths = [3]int{23, 28, 33} var quadrants = [4][2]string{ {"up and rising", "peak"}, {"up but falling", "transition"}, {"down and f...
USING: calendar calendar.parser formatting io kernel math math.constants math.functions ; : days-between ( ymd-str ymd-str -- n ) [ ymd>timestamp ] bi@ time- duration>days abs ; : trend ( pos len -- str ) / 4 * floor 3 divisor? "↑" "↓" ? ; : percent ( pos len -- x ) [ 2pi * ] [ / sin 100 * ] bi* ; : .day ( days...
Write the same code in Factor as shown below in Go.
package main import ( "fmt" "math/big" "strings" ) var zero = new(big.Int) var one = big.NewInt(1) func toEgyptianRecursive(br *big.Rat, fracs []*big.Rat) []*big.Rat { if br.Num().Cmp(zero) == 0 { return fracs } iquo := new(big.Int) irem := new(big.Int) iquo.QuoRem(br.Denom(),...
USING: backtrack formatting fry kernel locals make math math.functions math.ranges sequences ; IN: rosetta-code.egyptian-fractions : >improper ( r -- str ) >fraction "%d/%d" sprintf ; : improper ( x y -- a b ) [ /i ] [ [ rem ] [ nip ] 2bi / ] 2bi ; :: proper ( x y -- a b ) y x / ceiling :> d1 1 d1 / y neg x rem ...
Produce a functionally identical Factor code for the snippet given in Go.
package main import ( "fmt" "math/big" "strings" ) var zero = new(big.Int) var one = big.NewInt(1) func toEgyptianRecursive(br *big.Rat, fracs []*big.Rat) []*big.Rat { if br.Num().Cmp(zero) == 0 { return fracs } iquo := new(big.Int) irem := new(big.Int) iquo.QuoRem(br.Denom(),...
USING: backtrack formatting fry kernel locals make math math.functions math.ranges sequences ; IN: rosetta-code.egyptian-fractions : >improper ( r -- str ) >fraction "%d/%d" sprintf ; : improper ( x y -- a b ) [ /i ] [ [ rem ] [ nip ] 2bi / ] 2bi ; :: proper ( x y -- a b ) y x / ceiling :> d1 1 d1 / y neg x rem ...
Write the same algorithm in Factor as shown in this Go implementation.
package main import ( "fmt" "math/big" ) func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func main() { var z big.Int var cube1, cube2, cube100k, diff uint64 cubans := make(...
USING: formatting grouping io kernel lists lists.lazy math math.primes sequences tools.memory.private ; IN: rosetta-code.cuban-primes : cuban-primes ( n -- seq ) 1 lfrom [ [ 3 * ] [ 1 + * ] bi 1 + ] <lazy-map> [ prime? ] <lazy-filter> ltake list>array ; 200 cuban-primes 10 <groups> [ [ commas ] map [ "%10s" p...
Produce a functionally identical Factor code for the snippet given in Go.
package main import ( "fmt" "math" ) func main() { fmt.Println(noise(3.14, 42, 7)) } func noise(x, y, z float64) float64 { X := int(math.Floor(x)) & 255 Y := int(math.Floor(y)) & 255 Z := int(math.Floor(z)) & 255 x -= math.Floor(x) y -= math.Floor(y) z -= math.Floor(z) u := fa...
USING: kernel math math.functions literals locals prettyprint sequences ; IN: rosetta-code.perlin-noise CONSTANT: p $[ { 151 160 137 91 90 15 131 13 201 95 96 53 194 233 7 225 140 36 103 30 69 142 8 99 37 240 21 10 23 190 6 148 247 120 234 75 0 26 197 62 94 252 219 203 117 35 11 32 57 177 33 88 237 149...
Generate an equivalent Factor version of this Go code.
package main import ( "fmt" "math/big" "strings" ) func factorial(n int64) *big.Int { var z big.Int return z.MulRange(1, n) } var one = big.NewInt(1) var three = big.NewInt(3) var six = big.NewInt(6) var ten = big.NewInt(10) var seventy = big.NewInt(70) func almkvistGiullera(n int64, print bool)...
USING: continuations formatting io kernel locals math math.factorials math.functions sequences ; :: integer-term ( n -- m ) 32 6 n * factorial * 532 n sq * 126 n * + 9 + * n factorial 6 ^ 3 * / ; : exponent-term ( n -- m ) 6 * 3 + neg ; : nth-term ( n -- x ) [ integer-term ] [ exponent-term 10^ * ] bi ; ...
Write the same code in Factor as shown below in Go.
package main import ( "fmt" "math/big" "strings" ) func factorial(n int64) *big.Int { var z big.Int return z.MulRange(1, n) } var one = big.NewInt(1) var three = big.NewInt(3) var six = big.NewInt(6) var ten = big.NewInt(10) var seventy = big.NewInt(70) func almkvistGiullera(n int64, print bool)...
USING: continuations formatting io kernel locals math math.factorials math.functions sequences ; :: integer-term ( n -- m ) 32 6 n * factorial * 532 n sq * 126 n * + 9 + * n factorial 6 ^ 3 * / ; : exponent-term ( n -- m ) 6 * 3 + neg ; : nth-term ( n -- x ) [ integer-term ] [ exponent-term 10^ * ] bi ; ...
Maintain the same structure and functionality when rewriting this code in Factor.
package main import ( "fmt" "math/big" ) type mTerm struct { a, n, d int64 } var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, ...
USING: combinators formatting kernel locals math sequences ; IN: rosetta-code.machin : tan+ ( x y -- z ) [ + ] [ * 1 swap - / ] 2bi ; :: tan-eval ( coef frac -- x ) { { [ coef zero? ] [ 0 ] } { [ coef neg? ] [ coef neg frac tan-eval neg ] } { [ coef odd? ] [ frac coef 1 - frac tan-eval tan...
Convert the following code from Go to Factor, ensuring the logic remains intact.
package main import ( "fmt" "math/big" ) type mTerm struct { a, n, d int64 } var testCases = [][]mTerm{ {{1, 1, 2}, {1, 1, 3}}, {{2, 1, 3}, {1, 1, 7}}, {{4, 1, 5}, {-1, 1, 239}}, {{5, 1, 7}, {2, 3, 79}}, {{1, 1, 2}, {1, 1, 5}, {1, 1, 8}}, {{4, 1, 5}, {-1, 1, 70}, {1, 1, 99}}, ...
USING: combinators formatting kernel locals math sequences ; IN: rosetta-code.machin : tan+ ( x y -- z ) [ + ] [ * 1 swap - / ] 2bi ; :: tan-eval ( coef frac -- x ) { { [ coef zero? ] [ 0 ] } { [ coef neg? ] [ coef neg frac tan-eval neg ] } { [ coef odd? ] [ frac coef 1 - frac tan-eval tan...
Please provide an equivalent version of this Go code in Factor.
package main import ( "fmt" "log" "strings" ) var glyphs = []rune("♜♞♝♛♚♖♘♗♕♔") var names = map[rune]string{'R': "rook", 'N': "knight", 'B': "bishop", 'Q': "queen", 'K': "king"} var g2lMap = map[rune]string{ '♜': "R", '♞': "N", '♝': "B", '♛': "Q", '♚': "K", '♖': "R", '♘': "N", '♗': "B", '♕': "Q", ...
USING: assocs assocs.extras combinators formatting kernel literals math math.combinatorics sequences sequences.extras sets strings ; IN: scratchpad : check-length ( str -- ) length 8 = [ "Must have 8 pieces." throw ] unless ; : check-one ( str -- ) "KQ" counts [ nip 1 = not ] assoc-find nip [ 1string "...
Rewrite this program in Factor while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math" "regexp" "strings" ) var names = map[string]int64{ "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": ...
USING: arrays formatting grouping kernel math math.functions math.parser multiline peg peg.ebnf sequences sequences.deep ; : check-natural ( seq -- ) [ > ] monotonic? [ "Invalid number." throw ] unless ; EBNF: text>number [=[ one = "one"~ => [[ 1 ]] two = "two"~ => [[ 2 ]] thr...
Translate this program into Factor but keep the logic exactly as in Go.
package main import ( "fmt" "math" "time" ) const ld10 = math.Ln2 / math.Ln10 func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func p(L, n uint64) uint64 { i := L digits :=...
USING: formatting fry generalizations kernel literals math math.functions math.parser sequences tools.time ; CONSTANT: ld10 $[ 2 log 10 log / ] : p ( L n -- m ) swap [ 0 0 ] [ '[ over _ >= ] ] [ [ log10 >integer 10^ ] keep ] tri* '[ 1 + dup ld10 * dup >integer - 10 log * e^ _ * truncate ...
Please provide an equivalent version of this Go code in Factor.
package main import ( "fmt" "math" "time" ) const ld10 = math.Ln2 / math.Ln10 func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func p(L, n uint64) uint64 { i := L digits :=...
USING: formatting fry generalizations kernel literals math math.functions math.parser sequences tools.time ; CONSTANT: ld10 $[ 2 log 10 log / ] : p ( L n -- m ) swap [ 0 0 ] [ '[ over _ >= ] ] [ [ log10 >integer 10^ ] keep ] tri* '[ 1 + dup ld10 * dup >integer - 10 log * e^ _ * truncate ...
Write a version of this Go function in Factor with identical behavior.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64...
USING: combinators.short-circuit formatting io kernel math math.extras prettyprint sequences ; RENAME: stirling math.extras => (stirling) IN: rosetta-code.stirling-second : stirling ( n k -- m ) 2dup { [ = not ] [ nip zero? ] } 2&& [ 2drop 0 ] [ (stirling) ] if ; "Stirling numbers of the second kind: n k sti...
Translate this program into Factor but keep the logic exactly as in Go.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt64...
USING: combinators.short-circuit formatting io kernel math math.extras prettyprint sequences ; RENAME: stirling math.extras => (stirling) IN: rosetta-code.stirling-second : stirling ( n k -- m ) 2dup { [ = not ] [ nip zero? ] } 2&& [ 2drop 0 ] [ (stirling) ] if ; "Stirling numbers of the second kind: n k sti...
Write the same algorithm in Factor as shown in this Go implementation.
package main import "fmt" func c(n, p int) (R1, R2 int, ok bool) { powModP := func(a, e int) int { s := 1 for ; e > 0; e-- { s = s * a % p } return s } ls := func(a int) int { return powModP(a, (p-1)/2) } if ls(n) != 1 { re...
USING: accessors assocs interpolate io kernel literals locals math math.extras math.functions ; TUPLE: point x y ; C: <point> point :: (cipolla) ( n p -- m ) 0 0 :> ( a [ ω2 p legendere -1 = ] [ a sq n - p rem ω2 [| a b | a x>> b x>> * a y>> b y>> ω2 * * + p mod a x>> b y>> * b x>> a ...
Rewrite the snippet below in Factor so it works the same as the original Go code.
package main import "fmt" func c(n, p int) (R1, R2 int, ok bool) { powModP := func(a, e int) int { s := 1 for ; e > 0; e-- { s = s * a % p } return s } ls := func(a int) int { return powModP(a, (p-1)/2) } if ls(n) != 1 { re...
USING: accessors assocs interpolate io kernel literals locals math math.extras math.functions ; TUPLE: point x y ; C: <point> point :: (cipolla) ( n p -- m ) 0 0 :> ( a [ ω2 p legendere -1 = ] [ a sq n - p rem ω2 [| a b | a x>> b x>> * a y>> b y>> ω2 * * + p mod a x>> b y>> * b x>> a ...
Translate this program into Factor but keep the logic exactly as in Go.
package main import ( "fmt" big "github.com/ncw/gmp" "sort" ) var ( one = new(big.Int).SetUint64(1) two = new(big.Int).SetUint64(2) three = new(big.Int).SetUint64(3) ) func pierpont(ulim, vlim int, first bool) []*big.Int { p := new(big.Int) p2 := new(big.Int).Set(one) p3 := ne...
USING: fry grouping io kernel locals make math math.functions math.primes prettyprint sequences sorting ; : pierpont ( ulim vlim quot -- seq ) '[ _ <iota> _ <iota> [ [ 2 ] [ 3 ] bi* [ swap ^ ] 2bi@ * 1 @ dup prime? [ , ] [ drop ] if ] cartesian-each ] { } make natural-so...
Write a version of this Go function in Factor with identical behavior.
package main import ( "fmt" "log" "math/big" ) var ( primes []*big.Int smallPrimes []int ) func init() { two := big.NewInt(2) three := big.NewInt(3) p521 := big.NewInt(521) p29 := big.NewInt(29) primes = append(primes, two) smallPrimes = append(smallPrimes, 2) fo...
USING: deques dlists formatting fry io kernel locals make math math.order math.primes math.text.english namespaces prettyprint sequences tools.memory.private ; IN: rosetta-code.n-smooth-numbers SYMBOL: primes : ns ( n -- seq ) primes-upto [ primes set ] [ length [ 1 1dlist ] replicate ] bi ; : enqueue ( n ...
Write the same code in Factor as shown below in Go.
package main import ( "fmt" "log" ) var ( primes = sieve(100000) foundCombo = false ) func sieve(limit uint) []uint { primes := []uint{2} c := make([]bool, limit+1) p := uint(3) for { p2 := p * p if p2 > limit { break } for i := p2...
USING: formatting fry grouping kernel math.combinatorics math.parser math.primes sequences ; : partition ( x n -- str ) over [ primes-upto ] 2dip '[ sum _ = ] find-combination [ number>string ] map "+" join ; : print-partition ( x n seq -- ) [ "no solution" ] when-empty "Partitioned %5d with %2d p...
Generate a Factor translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 unsigned := true s1 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s1[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s1[n][k] = new(big.Int) } ...
USING: arrays assocs formatting io kernel math math.polynomials math.ranges prettyprint sequences ; IN: rosetta-code.stirling-first : stirling-row ( n -- seq ) [ { 1 } ] [ [ -1 ] dip neg [a,b) dup length 1 <array> zip { 0 1 } [ p* ] reduce [ abs ] map ] if-zero ; "Unsigned Stirling numbers of ...
Maintain the same structure and functionality when rewriting this code in Factor.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 unsigned := true s1 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s1[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s1[n][k] = new(big.Int) } ...
USING: arrays assocs formatting io kernel math math.polynomials math.ranges prettyprint sequences ; IN: rosetta-code.stirling-first : stirling-row ( n -- seq ) [ { 1 } ] [ [ -1 ] dip neg [a,b) dup length 1 <array> zip { 0 1 } [ p* ] reduce [ abs ] map ] if-zero ; "Unsigned Stirling numbers of ...
Maintain the same structure and functionality when rewriting this code in Factor.
package main import "fmt" type vector []float64 func (v vector) add(v2 vector) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi + v2[i] } return r } func (v vector) sub(v2 vector) vector { r := make([]float64, len(v)) for i, vi := range v { r[i] = vi - v...
(scratchpad) USE: math.vectors (scratchpad) { 1 2 } { 3 4 } v+ --- Data stack: { 4 6 }
Please provide an equivalent version of this Go code in Factor.
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...
USING: formatting io kernel math.transforms.bwt sequences ; { "banana" "dogwood" "TO BE OR NOT TO BE OR WANT TO BE OR NOT?" "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES" } [ [ print ] [ bwt ] bi 2dup " bwt-->%3d %u\n" printf ibwt " ibwt-> %u\n" printf nl ] each
Produce a language-to-language conversion: from Go to Factor, same semantics.
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...
USING: formatting io kernel math.transforms.bwt sequences ; { "banana" "dogwood" "TO BE OR NOT TO BE OR WANT TO BE OR NOT?" "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES" } [ [ print ] [ bwt ] bi 2dup " bwt-->%3d %u\n" printf ibwt " ibwt-> %u\n" printf nl ] each
Convert the following code from Go to Factor, ensuring the logic remains intact.
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])) ...
USING: kernel math math.combinatorics math.extras math.functions math.ranges prettyprint sequences ; : faulhaber ( p -- seq ) 1 + dup recip swap dup 0 (a,b] [ [ nCk ] [ -1 swap ^ ] [ bernoulli ] tri * * * ] 2with map ; 10 [ faulhaber . ] each-integer
Rewrite this program in Factor while keeping its functionality equivalent to the Go version.
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...
USING: formatting kernel math math.combinatorics math.extras math.functions regexp sequences ; : faulhaber ( p -- seq ) 1 + dup recip swap dup <iota> [ [ nCk ] [ -1 swap ^ ] [ bernoulli ] tri * * * ] 2with map ; : (poly>str) ( seq -- str ) reverse [ 1 + "%un^%d" sprintf ] map-index reverse " + " join ; :...
Convert this Go snippet to Factor and keep its semantics consistent.
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 } } ...
USING: assocs formatting grouping kernel math math.primes math.statistics sequences sorting ; IN: rosetta-code.prime-conspiracy : transitions ( n -- alist ) nprimes [ 10 mod ] map 2 clump histogram >alist natural-sort ; : t-values ( transition -- i j count freq ) first2 [ first2 ] dip dup 10000. / ; : print-...
Write the same code in Factor as shown below in Go.
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 =...
USING: assocs formatting kernel math math.functions math.statistics random sequences sorting ; 2,000,000 [ 0 1 normal-random-float ] replicate dup [ mean ] [ population-std ] bi "Mean: %f\nStdev: %f\n\n" printf [ 10 * floor 10 / ] map histogram >alist [ first ] ...
Produce a language-to-language conversion: from Go to Factor, same semantics.
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 ...
: is-1-or-0 ( char -- ? ) dup CHAR: 0 = [ drop t ] [ CHAR: 1 = ] if ; : int-is-B10 ( n -- ? ) unparse [ is-1-or-0 ] all? ; : B10-step ( x x -- x x ? ) dup int-is-B10 [ f ] [ over + t ] if ; : find-B10 ( x -- x ) dup [ B10-step ] loop nip ;
Change the following Go code into Factor without altering its purpose.
package main import "fmt" func divisors(n int) []int { divs := []int{1} divs2 := []int{} for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs = append(divs, i) if i != j { divs2 = append(divs2, j) } } } for i := l...
USING: combinators.short-circuit io kernel lists lists.lazy locals math math.primes.factors prettyprint sequences ; IN: rosetta-code.weird-numbers :: has-sum? ( n seq -- ? ) seq [ f ] [ unclip-slice :> ( xs x ) n x < [ n xs has-sum? ] [ { [ n x = ] [ n x ...
Generate a Factor translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math" "math/big" ) var bi = new(big.Int) func isPrime(n int) bool { bi.SetUint64(uint64(n)) return bi.ProbablyPrime(0) } func generateSmallPrimes(n int) []int { primes := make([]int, n) primes[0] = 2 for i, count := 3, 1; count < n; i += 2 { if is...
USING: combinators formatting fry kernel lists lists.lazy lists.lazy.examples literals math math.functions math.primes math.primes.factors math.ranges sequences ; IN: rosetta-code.nth-n-div CONSTANT: primes $[ 100 nprimes ] : prime ( m -- n ) 1 - [ primes nth ] [ ^ ] bi ; : (non-prime) ( m quot -- n ) '[ ...
Change the following Go code into Factor without altering its purpose.
package main import ( "fmt" "math/big" "math/rand" "time" ) type mont struct { n uint m *big.Int r2 *big.Int } func newMont(m *big.Int) *mont { if m.Bit(0) != 1 { return nil } n := uint(m.BitLen()) x := big.NewInt(1) x.Sub(x.Lsh(x, n), m) return ...
USING: io kernel locals math math.bitwise math.functions prettyprint ; : montgomery-reduce ( m a -- n ) over bit-length [ dup odd? [ over + ] when 2/ ] times swap mod ; CONSTANT: m 750791094644726559640638407699 CONSTANT: t1 323165824550862327179367294465482435542970161392400401329100 CONSTANT: r1 4401600251...
Convert this Go snippet to Factor and keep its semantics consistent.
package main import "fmt" func getDivisors(n int) []int { divs := []int{1, n} for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs = append(divs, i) if i != j { divs = append(divs, j) } } } return divs } func sum(div...
USING: combinators grouping io kernel lists lists.lazy math math.primes.factors memoize prettyprint sequences ; MEMO: psum? ( seq n -- ? ) { { [ dup zero? ] [ 2drop t ] } { [ over length zero? ] [ 2drop f ] } { [ over last over > ] [ [ but-last ] dip psum? ] } [ [ [ but-...
Port the provided Go code into Factor while preserving the original functionality.
package main import ( "fmt" "regexp" "strings" ) var reg = regexp.MustCompile(`(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)`) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func commatiz...
USING: accessors grouping io kernel math regexp sequences splitting strings unicode ; : numeric ( str -- new-str ) R/ [1-9][0-9]*/ first-match >string ; : commas ( numeric-str period separator -- str ) [ reverse ] [ group ] [ reverse join reverse ] tri* ; : (commatize) ( text from period separator -- str ) ...
Convert this Go block to Factor, preserving its control flow and logic.
package main import ( "fmt" "image" "reflect" ) type t struct { X int next *t } func main() { report(t{}) report(image.Point{}) } func report(x interface{}) { t := reflect.TypeOf(x) n := t.NumField() fmt.Printf("Type %v has %d fields:\n", t, n) fmt.Println("Name Type Exported") for i := 0; i...
USING: assocs kernel math mirrors prettyprint strings ; TUPLE: foo { bar string } { baz string initial: "hi" } { baxx integer initial: 50 read-only } ; C: <foo> foo "apple" "banana" 200 <foo> <mirror> [ >alist ] [ object-slots ] bi [ . ] bi@
Write the same code in Factor as shown below in Go.
package main import ( "bufio" "flag" "fmt" "io" "log" "math/rand" "os" "strings" "time" "unicode" "unicode/utf8" ) func main() { log.SetFlags(0) log.SetPrefix("markov: ") input := flag.String("in", "alice_oz.txt", "input file") n := flag.Int("n", 2, "number of words to use as prefix") runs := flag.Int...
USING: assocs fry grouping io io.encodings.ascii io.files kernel make math random sequences splitting ; : build-markov-assoc ( path n -- assoc ) [ ascii file-contents " " split harvest ] dip 1 + clump H{ } clone tuck [ [ unclip-last swap ] dip push-at ] curry each ; : first-word ( assoc -- next-key ) rand...
Convert this Go snippet to Factor and keep its semantics consistent.
package main import ( "fmt" "math" "strconv" "strings" ) func decToBin(d float64) string { whole := int64(math.Floor(d)) binary := strconv.FormatInt(whole, 2) + "." dd := d - float64(whole) for dd > 0.0 { r := dd * 2.0 if r >= 1.0 { binary += "1" ...
USING: interpolate io kernel math.parser sequences ; : bin>dec ( x -- y ) number>string "0b${}p0" interpolate>string string>number ; 23.34375 dup >bin 1011.11101 dup bin>dec [ [I ${} => ${}I] nl ] 2bi@
Change the programming language of this snippet from Go to Factor without modifying what it does.
package main import ( "fmt" "math" "strconv" "strings" ) func decToBin(d float64) string { whole := int64(math.Floor(d)) binary := strconv.FormatInt(whole, 2) + "." dd := d - float64(whole) for dd > 0.0 { r := dd * 2.0 if r >= 1.0 { binary += "1" ...
USING: interpolate io kernel math.parser sequences ; : bin>dec ( x -- y ) number>string "0b${}p0" interpolate>string string>number ; 23.34375 dup >bin 1011.11101 dup bin>dec [ [I ${} => ${}I] nl ] 2bi@
Generate an equivalent Factor version of this Go code.
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...
USING: checksums checksums.sha fry grouping io io.encodings.binary io.files kernel make math math.parser namespaces sequences ; : each-block ( ... size quot: ( ... block -- ... ) -- ... ) input-stream get spin (each-stream-block) ; inline : >sha-256 ( seq -- newseq ) sha-256 checksum-bytes ; : (hash-read) ( path...
Translate the given Go code snippet into Factor without altering its behavior.
package main import ( "fmt" "math/big" "time" ) var p []*big.Int var pd []int func partDiffDiff(n int) int { if n&1 == 1 { return (n + 1) / 2 } return n + 1 } func partDiff(n int) int { if n < 2 { return 1 } pd[n] = pd[n-1] + partDiffDiff(n-1) return pd[n] } ...
USING: kernel lists lists.lazy math sequences sequences.extras ; : penta ( n -- m ) [ sq 3 * ] [ - 2/ ] bi ; : seq ( -- list ) 1 lfrom [ penta 1 - ] <lazy-map> 1 lfrom [ neg penta 1 - ] <lazy-map> lmerge ; : ++-- ( seq -- n ) 0 [ 2/ odd? [ - ] [ + ] if ] reduce-index ; : step ( seq pseq -- seq 'pseq )...
Write the same code in Factor as shown below in Go.
package main import ( "fmt" "rcu" ) func reversed(n int) int { rev := 0 for n > 0 { rev = rev*10 + n%10 n = n / 10 } return rev } func main() { var special []int for n := 1; n < 200; n++ { divs := rcu.Divisors(n) revN := reversed(n) all := true ...
USING: grouping kernel math.functions math.parser math.primes.factors math.ranges prettyprint sequences ; : reverse-number ( n -- reversed ) 10 >base reverse dec> ; : special? ( n -- ? ) [ reverse-number ] [ divisors ] bi [ reverse-number divisor? ] with all? ; 200 [1..b] [ special? ] filter 18 group simple-...
Keep all operations the same but rewrite the snippet in Factor.
package main import ( "fmt" "strings" ) func hpo2(n uint) uint { return n & (-n) } func lhpo2(n uint) uint { q := uint(0) m := hpo2(n) for m%2 == 0 { m = m >> 1 q++ } return q } func nimsum(x, y uint) uint { return x ^ y } func nimprod(x, y uint) uint { if x < 2 ...
USING: combinators formatting io kernel locals math sequences ; : hpo2 ( n -- n ) dup neg bitand ; : lhpo2 ( n -- n ) hpo2 0 swap [ dup even? ] [ -1 shift [ 1 + ] dip ] while drop ; ALIAS: nim-sum bitxor :: nim-prod ( x y -- prod ) x hpo2 :> h 0 :> comp { { [ x 2 < y 2 < or ] [ x y * ] }...
Convert this Go block to Factor, preserving its control flow and logic.
package main import ( "bytes" "fmt" "io/ioutil" "log" ) func levenshtein(s, t string) int { d := make([][]int, len(s)+1) for i := range d { d[i] = make([]int, len(t)+1) } for i := range d { d[i][0] = i } for j := range d[0] { d[0][j] = j } for j ...
USING: formatting fry http.client io kernel lcs literals math math.ranges namespaces prettyprint.config sequences splitting ; CONSTANT: words $[ "https://www.mit.edu/~ecprice/wordlist.10000" http-get nip "\n" split harvest ] CONSTANT: word "complition" : lev-dist-of ( str n -- n ) [ words ] 2dip '[ _ leve...
Convert this Go snippet to Factor and keep its semantics consistent.
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 ...
USING: formatting io kernel lists lists.lazy math math.ranges math.vectors numspec present prettyprint sequences sets ; : multiples ( n -- seq ) [ 2 * ] [ 6 * ] [ ] tri <range> [ present ] map ; : all-set-eq? ( seq -- ? ) dup ?first [ set= ] curry all? ; NUMSPEC: starting-with-one 1 1_ ... ; : smallest-per...
Please provide an equivalent version of this Go code in Factor.
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 ...
USING: formatting io kernel lists lists.lazy math math.ranges math.vectors numspec present prettyprint sequences sets ; : multiples ( n -- seq ) [ 2 * ] [ 6 * ] [ ] tri <range> [ present ] map ; : all-set-eq? ( seq -- ? ) dup ?first [ set= ] curry all? ; NUMSPEC: starting-with-one 1 1_ ... ; : smallest-per...
Preserve the algorithm and functionality while converting the code from Go to Factor.
package main import ( "fmt" big "github.com/ncw/gmp" "rcu" ) var p, p2, q *big.Int func isPentaPowerPrimeSeed(n uint64) bool { nn := new(big.Int).SetUint64(n) p.Set(nn) k := new(big.Int).SetUint64(n + 1) p2.Add(q, k) if !p2.ProbablyPrime(15) { return false } p2.Add(p, ...
USING: grouping io kernel lists lists.lazy math math.functions math.primes prettyprint tools.memory.private ; : seed? ( n -- ? ) 5 [ dupd ^ 1 + + prime? ] with all-integers? ; : pentas ( -- list ) 1 lfrom [ seed? ] lfilter [ commas ] lmap-lazy ; "First thirty penta-power prime seeds:" print 30 pentas ltake l...
Please provide an equivalent version of this Go code in Factor.
package main import ( "fmt" big "github.com/ncw/gmp" "rcu" ) var p, p2, q *big.Int func isPentaPowerPrimeSeed(n uint64) bool { nn := new(big.Int).SetUint64(n) p.Set(nn) k := new(big.Int).SetUint64(n + 1) p2.Add(q, k) if !p2.ProbablyPrime(15) { return false } p2.Add(p, ...
USING: grouping io kernel lists lists.lazy math math.functions math.primes prettyprint tools.memory.private ; : seed? ( n -- ? ) 5 [ dupd ^ 1 + + prime? ] with all-integers? ; : pentas ( -- list ) 1 lfrom [ seed? ] lfilter [ commas ] lmap-lazy ; "First thirty penta-power prime seeds:" print 30 pentas ltake l...
Can you help me rewrite this code in Factor instead of Go, keeping it the same logically?
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:] } ...
USING: formatting fry io kernel lists lists.lazy locals math math.functions math.ranges math.text.utils prettyprint sequences ; IN: rosetta-code.palindromic-gapful-numbers : create-palindrome ( n odd? -- m ) dupd [ 10 /i ] when swap [ over 0 > ] [ 10 * [ 10 /mod ] [ + ] bi* ] while nip ; : pa...
Write the same code in Factor as shown below in Go.
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:] } ...
USING: formatting fry io kernel lists lists.lazy locals math math.functions math.ranges math.text.utils prettyprint sequences ; IN: rosetta-code.palindromic-gapful-numbers : create-palindrome ( n odd? -- m ) dupd [ 10 /i ] when swap [ over 0 > ] [ 10 * [ 10 /mod ] [ + ] bi* ] while nip ; : pa...