Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Preserve the algorithm and functionality while converting the code from Go to Factor.
package main import ( "fmt" "math" "rcu" "sort" ) var primes = rcu.Primes(1e8 - 1) type res struct { bc interface{} next int } func getBrilliant(digits, limit int, countOnly bool) res { var brilliant []int count := 0 pow := 1 next := math.MaxInt for k := 1; k <= digits;...
USING: assocs formatting grouping io kernel lists lists.lazy math math.functions math.primes.factors prettyprint project-euler.common sequences ; MEMO: brilliant? ( n -- ? ) factors [ length 2 = ] keep [ number-length ] map all-eq? and ; : lbrilliant ( -- list ) 2 lfrom [ brilliant? ] lfilter 1 lfrom lzip...
Preserve the algorithm and functionality while converting the code from Go to Factor.
package main import ( "fmt" "math" "rcu" "sort" ) var primes = rcu.Primes(1e8 - 1) type res struct { bc interface{} next int } func getBrilliant(digits, limit int, countOnly bool) res { var brilliant []int count := 0 pow := 1 next := math.MaxInt for k := 1; k <= digits;...
USING: assocs formatting grouping io kernel lists lists.lazy math math.functions math.primes.factors prettyprint project-euler.common sequences ; MEMO: brilliant? ( n -- ? ) factors [ length 2 = ] keep [ number-length ] map all-eq? and ; : lbrilliant ( -- list ) 2 lfrom [ brilliant? ] lfilter 1 lfrom lzip...
Rewrite this program in Factor while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) func calkinWilf(n int) []*big.Rat { cw := make([]*big.Rat, n+1) cw[0] = big.NewRat(1, 1) one := big.NewRat(1, 1) two := big.NewRat(2, 1) for i := 1; i < n; i++ { t := new(big.Rat).Set(cw[i-1]) f...
USING: formatting io kernel lists lists.lazy math math.continued-fractions math.functions math.parser prettyprint sequences strings vectors ; : next-cw ( x -- y ) [ floor dup + ] [ 1 swap - + recip ] bi ; : calkin-wilf ( -- list ) 1 [ next-cw ] lfrom-by ; : >continued-fraction ( x -- seq ) 1vector [ dup last int...
Generate a Factor translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math" "math/big" "strconv" "strings" ) func calkinWilf(n int) []*big.Rat { cw := make([]*big.Rat, n+1) cw[0] = big.NewRat(1, 1) one := big.NewRat(1, 1) two := big.NewRat(2, 1) for i := 1; i < n; i++ { t := new(big.Rat).Set(cw[i-1]) f...
USING: formatting io kernel lists lists.lazy math math.continued-fractions math.functions math.parser prettyprint sequences strings vectors ; : next-cw ( x -- y ) [ floor dup + ] [ 1 swap - + recip ] bi ; : calkin-wilf ( -- list ) 1 [ next-cw ] lfrom-by ; : >continued-fraction ( x -- seq ) 1vector [ dup last int...
Produce a functionally identical Factor code for the snippet given in Go.
package main import ( "fmt" "sort" "strings" ) type indexSort struct { val sort.Interface ind []int } func (s indexSort) Len() int { return len(s.ind) } func (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] } func (s indexSort) Swap(i, j int) { s.val.Swap(s.ind[i], s.ind[j]) s.ind[i], ...
qw{ the cat sat on the mat } qw{ mat cat } make-slots
Port the provided Go code into Factor while preserving the original functionality.
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" ) func isPrime(n int) bool { if n < 2 { return false } if n%2 == 0 { return n == 2 } if n%3 == 0 { return n == 3 } d := 5 for d*d <= n { if n%d == 0 { return ...
USING: io.encodings.ascii io.files math.primes prettyprint sequences ; "unixdict.txt" ascii file-lines [ [ prime? ] all? ] filter .
Translate this program into Factor but keep the logic exactly as in Go.
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" ) func isPrime(n int) bool { if n < 2 { return false } if n%2 == 0 { return n == 2 } if n%3 == 0 { return n == 3 } d := 5 for d*d <= n { if n%d == 0 { return ...
USING: io.encodings.ascii io.files math.primes prettyprint sequences ; "unixdict.txt" ascii file-lines [ [ prime? ] all? ] filter .
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 /= 10 } return rev } func main() { primes := rcu.Primes(99999) var pals []int for _, p := range primes { if p == reversed(p) { pals = appen...
USING: kernel math.primes present prettyprint sequences ; 1000 primes-upto [ present dup reverse = ] filter stack.
Translate this program into Factor but keep the logic exactly as in Go.
package main import ( "fmt" "rcu" ) func reversed(n int) int { rev := 0 for n > 0 { rev = rev*10 + n%10 n /= 10 } return rev } func main() { primes := rcu.Primes(99999) var pals []int for _, p := range primes { if p == reversed(p) { pals = appen...
USING: kernel math.primes present prettyprint sequences ; 1000 primes-upto [ present dup reverse = ] filter stack.
Convert this Go snippet to Factor and keep its semantics consistent.
package main import ( "fmt" "math" "rcu" ) func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func main() { limit := 200000 d := rcu.PrimeSieve(limit-1, true) d[1] = false for i := 2; i < limit; i++ { if !d[i] { continue } ...
USING: combinators.short-circuit.smart grouping io kernel lists lists.lazy math math.primes math.primes.factors math.statistics prettyprint sequences sequences.deep ; : duffinian? ( n -- ? ) { [ prime? not ] [ dup divisors sum simple-gcd 1 = ] } && ; : duffinians ( -- list ) 3 lfrom [ duffinian? ] lfilter ; : tr...
Maintain the same structure and functionality when rewriting this code in Factor.
package main import ( "fmt" "math/big" ) func main() { one := big.NewInt(1) two := big.NewInt(2) next := new(big.Int) sylvester := []*big.Int{two} prod := new(big.Int).Set(two) count := 1 for count < 10 { next.Add(prod, one) sylvester = append(sylvester, new(big.Int...
USING: io kernel lists lists.lazy math prettyprint ; : lsylvester ( -- list ) 2 [ dup sq swap - 1 + ] lfrom-by ; "First 10 elements of Sylvester's sequence:" print 10 lsylvester ltake dup [ . ] leach nl "Sum of the reciprocals of first 10 elements:" print 0 [ recip + ] foldl .
Convert the following code from Go to Factor, ensuring the logic remains intact.
package main import ( "fmt" "math/big" ) func harmonic(n int) *big.Rat { sum := new(big.Rat) for i := int64(1); i <= int64(n); i++ { r := big.NewRat(1, i) sum.Add(sum, r) } return sum } func main() { fmt.Println("The first 20 harmonic numbers and the 100th, expressed in ra...
USING: formatting grouping io kernel lists lists.lazy math math.functions math.ranges math.statistics math.text.english prettyprint sequences tools.memory.private ; CONSTANT: γ 0.5772156649 : Hn-approx ( n -- ~Hn ) [ log γ + 1 2 ] [ * /f + 1 ] [ sq 12 * /f - ] tri ; : lharmonics ( -- list ) 1 lfrom [ Hn-approx ...
Ensure the translated Factor code behaves exactly like the original Go snippet.
package main import "fmt" func f(s1, s2, sep string) string { return s1 + sep + sep + s2 } func main() { fmt.Println(f("Rosetta", "Code", ":")) }
( scratchpad ) : cool-func ( w1 w2 sep -- res ) dup append glue ; ( scratchpad ) "Rosetta" "Code" ":" cool-func . "Rosetta::Code"
Generate a Factor translation of this Go snippet without changing its computational steps.
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w :=...
USE: eval : eval-bi@- ( a b program -- n ) tuck [ ( y -- z ) eval ] 2bi@ - ;
Maintain the same structure and functionality when rewriting this code in Factor.
package main import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" ) func main() { squareExpr := "x*x" fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } w :=...
USE: eval : eval-bi@- ( a b program -- n ) tuck [ ( y -- z ) eval ] 2bi@ - ;
Produce a language-to-language conversion: from Go to Factor, same semantics.
package main import ( "fmt" "log" "math/rand" "time" ) func generate(from, to int64) { if to < from || from < 0 { log.Fatal("Invalid range.") } span := to - from + 1 generated := make([]bool, span) count := span for count > 0 { n := from + rand.Int63n(span) ...
USING: kernel math.combinatorics math.ranges prettyprint random sequences ; : random-permutation ( seq -- newseq ) [ length dup nPk random ] keep permutation ; 20 [1,b] random-permutation .
Maintain the same structure and functionality when rewriting this code in Factor.
package main import ( "fmt" "rcu" ) func main() { var sgp []int p := 2 count := 0 for count < 50 { if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) { sgp = append(sgp, p) count++ } if p != 2 { p = p + 2 } else { p = 3 ...
USING: lists lists.lazy math math.primes math.primes.lists prettyprint ; 50 lprimes [ 2 * 1 + prime? ] lfilter ltake [ . ] leach
Transform the following Go implementation into Factor, maintaining the same output and logic.
package main import ( "fmt" "rcu" ) func main() { var sgp []int p := 2 count := 0 for count < 50 { if rcu.IsPrime(p) && rcu.IsPrime(2*p+1) { sgp = append(sgp, p) count++ } if p != 2 { p = p + 2 } else { p = 3 ...
USING: lists lists.lazy math math.primes math.primes.lists prettyprint ; 50 lprimes [ 2 * 1 + prime? ] lfilter ltake [ . ] leach
Write the same algorithm in Factor as shown in this Go implementation.
package main import ( "fmt" "rcu" "strconv" "strings" ) func findFirst(list []int) (int, int) { for i, n := range list { if n > 1e7 { return n, i } } return -1, -1 } func reverse(s string) string { chars := []rune(s) for i, j := 0, len(chars)-1; i < j; ...
USING: accessors formatting grouping io kernel lists lists.lazy math math.functions math.primes prettyprint sequences tools.memory.private tools.time ; TUPLE: cyclops left right n max ; : <cyclops> ( -- cyclops ) 1 1 1 9 cyclops boa ; : >cyclops< ( cyclops -- right left n ) [ right>> ] [ left>> ] [ n>> ] tri...
Convert this Go snippet to Factor and keep its semantics consistent.
package main import ( "fmt" "log" ) var endings = [][]string{ {"o", "as", "at", "amus", "atis", "ant"}, {"eo", "es", "et", "emus", "etis", "ent"}, {"o", "is", "it", "imus", "itis", "unt"}, {"io", "is", "it", "imus", "itis", "iunt"}, } var infinEndings = []string{"are", "ēre", "ere", "ire"} v...
USING: formatting io kernel math qw sequences ; CONSTANT: pronouns { "I" "you" "he, she, it" "we" "you all" "they" } CONSTANT: endings qw{ ō ās at āmus ātis ant } : first-conjugation? ( str -- ? ) qw{ are āre } [ tail? ] with any? ; : check-first-conjugation ( str -- ) first-conjugat...
Preserve the algorithm and functionality while converting the code from Go to Factor.
package main import ( "fmt" "log" ) var endings = [][]string{ {"o", "as", "at", "amus", "atis", "ant"}, {"eo", "es", "et", "emus", "etis", "ent"}, {"o", "is", "it", "imus", "itis", "unt"}, {"io", "is", "it", "imus", "itis", "iunt"}, } var infinEndings = []string{"are", "ēre", "ere", "ire"} v...
USING: formatting io kernel math qw sequences ; CONSTANT: pronouns { "I" "you" "he, she, it" "we" "you all" "they" } CONSTANT: endings qw{ ō ās at āmus ātis ant } : first-conjugation? ( str -- ? ) qw{ are āre } [ tail? ] with any? ; : check-first-conjugation ( str -- ) first-conjugat...
Translate this program into Factor but keep the logic exactly as in Go.
package main import ( "fmt" "rcu" "strings" ) func main() { limit := 100_000 primes := rcu.Primes(limit * 10) var results []int for _, p := range primes { if p < 1000 || p > 99999 { continue } ps := fmt.Sprintf("%s", p) if strings.Contains(ps, "1...
USING: assocs formatting grouping io kernel literals math math.functions math.functions.integer-logs math.primes math.statistics sequences sequences.extras sequences.product sorting tools.memory.private tools.time ; << CONSTANT: d { 0 1 2 3 4 5 6 7 8 9 } CONSTANT: e { 1 3 7 9 } >> CONSTANT: digits { ...
Maintain the same structure and functionality when rewriting this code in Factor.
package main import ( "fmt" "rcu" "strings" ) func main() { limit := 100_000 primes := rcu.Primes(limit * 10) var results []int for _, p := range primes { if p < 1000 || p > 99999 { continue } ps := fmt.Sprintf("%s", p) if strings.Contains(ps, "1...
USING: assocs formatting grouping io kernel literals math math.functions math.functions.integer-logs math.primes math.statistics sequences sequences.extras sequences.product sorting tools.memory.private tools.time ; << CONSTANT: d { 0 1 2 3 4 5 6 7 8 9 } CONSTANT: e { 1 3 7 9 } >> CONSTANT: digits { ...
Please provide an equivalent version of this Go code in Factor.
package main import ( "fmt" "rcu" ) func main() { c := rcu.PrimeSieve(5505, false) var triples [][3]int fmt.Println("Prime triplets: p, p + 2, p + 6 where p < 5,500:") for i := 3; i < 5500; i += 2 { if !c[i] && !c[i+2] && !c[i+6] { triples = append(triples, [3]int{i, i + 2,...
USING: arrays kernel lists lists.lazy math math.primes math.primes.lists prettyprint sequences ; lprimes [ dup 2 + dup 4 + 3array ] lmap-lazy [ [ prime? ] all? ] lfilter [ first 5500 < ] lwhile [ . ] leach
Produce a functionally identical Factor code for the snippet given in Go.
package main import ( "fmt" "rcu" ) func main() { c := rcu.PrimeSieve(5505, false) var triples [][3]int fmt.Println("Prime triplets: p, p + 2, p + 6 where p < 5,500:") for i := 3; i < 5500; i += 2 { if !c[i] && !c[i+2] && !c[i+6] { triples = append(triples, [3]int{i, i + 2,...
USING: arrays kernel lists lists.lazy math math.primes math.primes.lists prettyprint sequences ; lprimes [ dup 2 + dup 4 + 3array ] lmap-lazy [ [ prime? ] all? ] lfilter [ first 5500 < ] lwhile [ . ] leach
Maintain the same structure and functionality when rewriting this code in Factor.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(504) var nprimes []int fmt.Println("Neighbour primes < 500:") for i := 0; i < len(primes)-1; i++ { p := primes[i]*primes[i+1] + 2 if rcu.IsPrime(p) { nprimes = append(nprimes, primes[i]) ...
USING: formatting io kernel math math.primes ; "p q p*q+2" print 2 3 [ over 500 < ] [ 2dup * 2 + dup prime? [ 3dup "%-4d %-4d %-6d\n" printf ] when drop nip dup next-prime ] while 2drop
Convert this Go snippet to Factor and keep its semantics consistent.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(504) var nprimes []int fmt.Println("Neighbour primes < 500:") for i := 0; i < len(primes)-1; i++ { p := primes[i]*primes[i+1] + 2 if rcu.IsPrime(p) { nprimes = append(nprimes, primes[i]) ...
USING: formatting io kernel math math.primes ; "p q p*q+2" print 2 3 [ over 500 < ] [ 2dup * 2 + dup prime? [ 3dup "%-4d %-4d %-6d\n" printf ] when drop nip dup next-prime ] while 2drop
Port the provided Go code into Factor while preserving the original functionality.
package main import ( "fmt" "math" "rcu" ) func magicConstant(n int) int { return (n*n + 1) * n / 2 } var ss = []string{ "\u2070", "\u00b9", "\u00b2", "\u00b3", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079", } func superscript(n int) string { if n < 10 { return ss[n]...
USING: formatting io kernel math math.functions.integer-logs math.ranges prettyprint sequences ; : magic ( m -- n ) dup sq 1 + 2 / * ; "First 20 magic constants:" print 3 22 [a,b] [ bl ] [ magic pprint ] interleave nl nl "1000th magic constant: " write 1002 magic . nl "Smallest order magic square with a constant grea...
Generate an equivalent Factor version of this Go code.
package main import ( "fmt" big "github.com/ncw/gmp" ) func cullen(n uint) *big.Int { one := big.NewInt(1) bn := big.NewInt(int64(n)) res := new(big.Int).Lsh(one, n) res.Mul(res, bn) return res.Add(res, one) } func woodall(n uint) *big.Int { res := cullen(n) return res.Sub(res, bi...
USING: arrays kernel math math.vectors prettyprint ranges sequences ; 20 [1..b] [ dup 2^ * 1 + ] map dup 2 v-n 2array simple-table.
Convert the following code from Go to Factor, ensuring the logic remains intact.
package main import ( "fmt" "regexp" "strings" ) var elements = ` hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon ...
USING: formatting kernel qw sequences ; qw{ hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon potassium calcium scandium ...
Translate this program into Factor but keep the logic exactly as in Go.
package main import "fmt" func main() { denoms := []int{200, 100, 50, 20, 10, 5, 2, 1} coins := 0 amount := 988 remaining := 988 fmt.Println("The minimum number of coins needed to make a value of", amount, "is as follows:") for _, denom := range denoms { n := remaining / denom ...
USING: assocs kernel math math.order prettyprint sorting ; : make-change ( value coins -- assoc ) [ >=< ] sort [ /mod swap ] zip-with nip ; 988 { 1 2 5 10 20 50 100 200 } make-change .
Port the following code from Go to Factor with equivalent syntax and logic.
package main import ( "fmt" "rcu" "strconv" "strings" ) func reverse(s string) string { chars := []rune(s) for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 { chars[i], chars[j] = chars[j], chars[i] } return string(chars) } func main() { fmt.Println("Primes < 500 which a...
USING: kernel math.parser math.primes prettyprint sequences sequences.extras ; 500 primes-upto [ >hex ] [ dup reverse = ] map-filter .
Generate an equivalent Factor version of this Go code.
package main import ( "fmt" "rcu" "strconv" "strings" ) func reverse(s string) string { chars := []rune(s) for i, j := 0, len(chars)-1; i < j; i, j = i+1, j-1 { chars[i], chars[j] = chars[j], chars[i] } return string(chars) } func main() { fmt.Println("Primes < 500 which a...
USING: kernel math.parser math.primes prettyprint sequences sequences.extras ; 500 primes-upto [ >hex ] [ dup reverse = ] map-filter .
Write the same code in Factor as shown below in Go.
package main import ( "fmt" "math/rand" "time" ) const boxW = 41 const boxH = 37 const pinsBaseW = 19 const nMaxBalls = 55 const centerH = pinsBaseW + (boxW-pinsBaseW*2+1)/2 - 1 const ( empty = ' ' ball = 'o' wall = '|' corner = '+' floor = '-' pin = '.' ) ...
USING: accessors arrays calendar colors combinators combinators.short-circuit fonts fry generalizations kernel literals locals math math.ranges math.vectors namespaces opengl random sequences timers ui ui.commands ui.gadgets ui.gadgets.worlds ui.gestures ui.pens.solid ui.render ui.text ; IN: rosetta-code.galton-box-ani...
Convert this Go snippet to Factor and keep its semantics consistent.
package main import ( "fmt" "math" ) func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func main() { var squares []int outer: for i := 1; i < 50; i++ { if isSquare(i) { squares = append(squares, i) } else { n := i ...
USING: arrays combinators.short-circuit.smart formatting io kernel math sequences ; [let 50 :> lim lim 0 <array> :> res 1 0 :> ( n [ found lim 1 - < ] [ n dup * :> n2 [ n2 zero? ] [ { [ n2 lim < ] [ n2 res nth zero? ] } && [ found 1 + found n2 10 /i n...
Transform the following Go implementation into Factor, maintaining the same output and logic.
package main import ( "fmt" "math" ) func isSquare(n int) bool { s := int(math.Sqrt(float64(n))) return s*s == n } func main() { var squares []int outer: for i := 1; i < 50; i++ { if isSquare(i) { squares = append(squares, i) } else { n := i ...
USING: arrays combinators.short-circuit.smart formatting io kernel math sequences ; [let 50 :> lim lim 0 <array> :> res 1 0 :> ( n [ found lim 1 - < ] [ n dup * :> n2 [ n2 zero? ] [ { [ n2 lim < ] [ n2 res nth zero? ] } && [ found 1 + found n2 10 /i n...
Keep all operations the same but rewrite the snippet in Factor.
package main import ( "bytes" "fmt" "io/ioutil" "log" "sort" "strings" ) func main() { b, err := ioutil.ReadFile("unixdict.txt") if err != nil { log.Fatal("Error reading file") } letters := "deegklnow" wordsAll := bytes.Split(b, []byte{'\n'}) var words [][]...
USING: assocs io.encodings.ascii io.files kernel math math.statistics prettyprint sequences sorting ; : pare ( elt seq -- new-seq ) [ [ member? ] keep length 2 > and ] with filter ; : words ( input-str path -- seq ) [ [ midpoint@ ] keep nth ] [ ascii file-lines pare ] bi* ; : ?<= ( m n/f -- ? ) dup f = [ n...
Write the same algorithm in Factor as shown in this Go implementation.
package main import ( "fmt" "sort" "strconv" ) type wheel struct { next int values []string } type wheelMap = map[string]wheel func generate(wheels wheelMap, start string, maxCount int) { count := 0 w := wheels[start] for { s := w.values[w.next] v, err := strconv.At...
USING: accessors assocs circular io kernel lists lists.lazy math math.parser multiline peg.ebnf prettyprint prettyprint.custom sequences strings ; IN: rosetta-code.number-wheels TUPLE: group pretty list ; C: <group> group M: group pprint* pretty>> write ; TUPLE: number-wheel seq i ; : <number-wheel> ( seq -- numbe...
Write the same code in Factor as shown below in Go.
package main import ( "fmt" "sort" "strconv" ) type wheel struct { next int values []string } type wheelMap = map[string]wheel func generate(wheels wheelMap, start string, maxCount int) { count := 0 w := wheels[start] for { s := w.values[w.next] v, err := strconv.At...
USING: accessors assocs circular io kernel lists lists.lazy math math.parser multiline peg.ebnf prettyprint prettyprint.custom sequences strings ; IN: rosetta-code.number-wheels TUPLE: group pretty list ; C: <group> group M: group pprint* pretty>> write ; TUPLE: number-wheel seq i ; : <number-wheel> ( seq -- numbe...
Produce a functionally identical Factor code for the snippet given in Go.
package main import ( "fmt" "math" ) var ( Two = "Two circles." R0 = "R==0.0 does not describe circles." Co = "Coincident points describe an infinite number of circles." CoR0 = "Coincident points with r==0.0 describe a degenerate circle." Diam = "Points form a diameter and describe on...
USING: accessors combinators combinators.short-circuit formatting io kernel literals locals math math.distances math.functions prettyprint sequences strings ; IN: rosetta-code.circles DEFER: find-circles TUPLE: input p1 p2 r ; CONSTANT: test-cases { T{ input f { 0.1234 0.9876 } { 0.8765 0.2345 } 2 } T{ inpu...
Produce a functionally identical Factor code for the snippet given in Go.
package main import ( "fmt" "math" ) var ( Two = "Two circles." R0 = "R==0.0 does not describe circles." Co = "Coincident points describe an infinite number of circles." CoR0 = "Coincident points with r==0.0 describe a degenerate circle." Diam = "Points form a diameter and describe on...
USING: accessors combinators combinators.short-circuit formatting io kernel literals locals math math.distances math.functions prettyprint sequences strings ; IN: rosetta-code.circles DEFER: find-circles TUPLE: input p1 p2 r ; CONSTANT: test-cases { T{ input f { 0.1234 0.9876 } { 0.8765 0.2345 } 2 } T{ inpu...
Generate a Factor translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math" ) func max(a, b uint64) uint64 { if a > b { return a } return b } func min(a, b uint64) uint64 { if a < b { return a } return b } func ndigits(x uint64) (n int) { for ; x > 0; x /= 10 { n++ } return } fu...
USING: combinators.short-circuit fry io kernel lists lists.lazy math math.combinatorics math.functions math.primes.factors math.statistics math.text.utils prettyprint sequences sets ; IN: rosetta-code.vampire-number : digits ( n -- m ) log10 floor >integer 1 + ; : same-digits? ( n n1 n2 -- ? ) [ 1 digit-group...
Produce a functionally identical Factor code for the snippet given in Go.
package main import ( "fmt" "math/rand" "time" ) func main() { var pack [52]byte for i := 0; i < 26; i++ { pack[i] = 'R' pack[26+i] = 'B' } rand.Seed(time.Now().UnixNano()) rand.Shuffle(52, func(i, j int) { pack[i], pack[j] = pack[j], pack[i] }) ...
USING: accessors combinators.extras formatting fry generalizations io kernel math math.ranges random sequences sequences.extras ; IN: rosetta-code.mind-boggling-card-trick SYMBOLS: R B ; TUPLE: piles deck red black discard ; : initialize-deck ( -- seq ) [ R ] [ B ] [ '[ 26 _ V{ } replicate-as ] call ] bi@ append...
Ensure the translated Factor code behaves exactly like the original Go snippet.
package main import ( "fmt" "math/rand" "time" ) func main() { var pack [52]byte for i := 0; i < 26; i++ { pack[i] = 'R' pack[26+i] = 'B' } rand.Seed(time.Now().UnixNano()) rand.Shuffle(52, func(i, j int) { pack[i], pack[j] = pack[j], pack[i] }) ...
USING: accessors combinators.extras formatting fry generalizations io kernel math math.ranges random sequences sequences.extras ; IN: rosetta-code.mind-boggling-card-trick SYMBOLS: R B ; TUPLE: piles deck red black discard ; : initialize-deck ( -- seq ) [ R ] [ B ] [ '[ 26 _ V{ } replicate-as ] call ] bi@ append...
Can you help me rewrite this code in Factor instead of Go, keeping it the same logically?
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" ...
USING: combinators continuations formatting grouping io kernel literals math.order math.text.utils multiline sequences splitting ; CONSTANT: numerals $[ HEREDOC: END + +-+ + + + + +-+ + + +-+ + + +-+ | | | |\ |/ |/ | | | | | | | | | | +-+ | + + + | + | + +-+ +-+ ...
Produce a functionally identical Factor code for the snippet given in Go.
package main import "fmt" var n = make([][]string, 15) func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } } func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" ...
USING: combinators continuations formatting grouping io kernel literals math.order math.text.utils multiline sequences splitting ; CONSTANT: numerals $[ HEREDOC: END + +-+ + + + + +-+ + + +-+ + + +-+ | | | |\ |/ |/ | | | | | | | | | | +-+ | + + + | + | + +-+ +-+ ...
Please provide an equivalent version of this Go code in Factor.
package main import ( "fmt" "sort" "strings" ) type card struct { face byte suit byte } const faces = "23456789tjqka" const suits = "shdc" func isStraight(cards []card) bool { sorted := make([]card, 5) copy(sorted, cards) sort.Slice(sorted, func(i, j int) bool { return sorted...
USING: formatting kernel poker sequences ; { "2H 2D 2C KC QD" "2H 5H 7D 8C 9S" "AH 2D 3C 4C 5D" "2H 3H 2D 3C 3D" "2H 7H 2D 3C 3D" "2H 7H 7D 7C 7S" "TH JH QH KH AH" "4H 4S KS 5D TS" "QC TC 7C 6C 4C" } [ dup string>hand-name "%s: %s\n" printf ] each
Convert this Go snippet to Factor and keep its semantics consistent.
package main import ( "fmt" "sort" "strings" ) type card struct { face byte suit byte } const faces = "23456789tjqka" const suits = "shdc" func isStraight(cards []card) bool { sorted := make([]card, 5) copy(sorted, cards) sort.Slice(sorted, func(i, j int) bool { return sorted...
USING: formatting kernel poker sequences ; { "2H 2D 2C KC QD" "2H 5H 7D 8C 9S" "AH 2D 3C 4C 5D" "2H 3H 2D 3C 3D" "2H 7H 2D 3C 3D" "2H 7H 7D 7C 7S" "TH JH QH KH AH" "4H 4S KS 5D TS" "QC TC 7C 6C 4C" } [ dup string>hand-name "%s: %s\n" printf ] each
Maintain the same structure and functionality when rewriting this code in Factor.
package main import ( "github.com/fogleman/gg" "strings" ) func wordFractal(i int) string { if i < 2 { if i == 1 { return "1" } return "" } var f1 strings.Builder f1.WriteString("1") var f2 strings.Builder f2.WriteString("0") for j := i - 2; j >=...
USING: accessors arrays combinators fry images images.loader kernel literals make match math math.vectors pair-rocket sequences ; FROM: fry => '[ _ ; IN: rosetta-code.fibonacci-word-fractal TUPLE: turtle heading loc ; C: <turtle> turtle : forward ( turtle -- turtle' ) dup heading>> [ v+ ] curry change-loc ; ...
Transform the following Go implementation into Factor, maintaining the same output and logic.
package main import "fmt" import "math/rand" func main(){ var a1,a2,a3,y,match,j,k int var inp string y=1 for y==1{ fmt.Println("Enter your sequence:") fmt.Scanln(&inp) var Ai [3] int var user [3] int for j=0;j<3;j++{ if(inp[j]==104){ user[j]=1 }else{ user[j]=0 } } for k=0;k<3;k++{ Ai[k]=rand.Intn(2) } for user[0]==Ai[...
USING: arrays ascii io kernel math prettyprint random sequences strings ; IN: rosetta-code.penneys-game : t|f ( -- t/f ) 1 random-bits 0 = ; : valid-input? ( seq -- ? ) [ [ CHAR: H = ] [ CHAR: T = ] bi or ] filter length 3 = ; : input-seq ( -- seq ) "Please input a 3-long sequence of H or T (heads or ...
Please provide an equivalent version of this Go code in Factor.
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := color....
USING: accessors images images.loader kernel literals math math.bits math.functions make sequences ; IN: rosetta-code.sierpinski-triangle-graphical CONSTANT: black B{ 33 33 33 255 } CONSTANT: white B{ 255 255 255 255 } CONSTANT: size $[ 2 8 ^ ] : sierpinski ( n -- seq ) [ [ 1 ] dip [ dup , dup 2...
Port the provided Go code into Factor while preserving the original functionality.
package main import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) func main() { const order = 8 const width = 1 << order const margin = 10 bounds := image.Rect(-margin, -margin, width+2*margin, width+2*margin) im := image.NewGray(bounds) gBlack := color....
USING: accessors images images.loader kernel literals math math.bits math.functions make sequences ; IN: rosetta-code.sierpinski-triangle-graphical CONSTANT: black B{ 33 33 33 255 } CONSTANT: white B{ 255 255 255 255 } CONSTANT: size $[ 2 8 ^ ] : sierpinski ( n -- seq ) [ [ 1 ] dip [ dup , dup 2...
Generate a Factor translation of this Go snippet without changing its computational steps.
package main import "fmt" type Range struct { start, end uint64 print bool } func main() { rgs := []Range{ {2, 1000, true}, {1000, 4000, true}, {2, 1e4, false}, {2, 1e5, false}, {2, 1e6, false}, {2, 1e7, false}, {2, 1e8, false}, {2, 1e9...
USING: arrays formatting fry io kernel math math.functions math.order math.ranges prettyprint sequences ; : eban? ( n -- ? ) 1000000000 /mod 1000000 /mod 1000 /mod [ dup 30 66 between? [ 10 mod ] when ] tri@ 4array [ { 0 2 4 6 } member? ] all? ; : .eban ( m n -- ) "eban numbers in [%d, %d]: " printf ; : e...
Write the same algorithm in Factor as shown in this Go implementation.
package main import "fmt" type Range struct { start, end uint64 print bool } func main() { rgs := []Range{ {2, 1000, true}, {1000, 4000, true}, {2, 1e4, false}, {2, 1e5, false}, {2, 1e6, false}, {2, 1e7, false}, {2, 1e8, false}, {2, 1e9...
USING: arrays formatting fry io kernel math math.functions math.order math.ranges prettyprint sequences ; : eban? ( n -- ? ) 1000000000 /mod 1000000 /mod 1000 /mod [ dup 30 66 between? [ 10 mod ] when ] tri@ 4array [ { 0 2 4 6 } member? ] all? ; : .eban ( m n -- ) "eban numbers in [%d, %d]: " printf ; : e...
Rewrite the snippet below in Factor so it works the same as the original Go code.
package main import ( "fmt" "strconv" ) const ( ul = "╔" uc = "╦" ur = "╗" ll = "╚" lc = "╩" lr = "╝" hb = "═" vb = "║" ) var mayan = [5]string{ " ", " ∙ ", " ∙∙ ", "∙∙∙ ", "∙∙∙∙", } const ( m0 = " Θ " m5 = "────" ) func dec2vig(n uint64) []u...
USING: arrays formatting io kernel make math math.extras sequences ; IN: rosetta-code.mayan-numerals : mayan-digit ( n -- m pair ) 20 /mod 5 /mod swap 2array ; : integer>mayan ( n -- seq ) [ [ mayan-digit , ] until-zero ] { } make reverse ; : ones ( n -- str ) [ CHAR: ● ] "" replicate-as ; : fives ( n -- str ) [...
Transform the following Go implementation into Factor, maintaining the same output and logic.
package main import ( "fmt" "math" "strconv" "strings" ) func d2d(d float64) float64 { return math.Mod(d, 360) } func g2g(g float64) float64 { return math.Mod(g, 400) } func m2m(m float64) float64 { return math.Mod(m, 6400) } func r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) } func d2g(d...
USING: accessors combinators formatting inverse kernel math math.constants quotations qw sequences units.si ; IN: rosetta-code.angles ALIAS: degrees arc-deg : gradiens ( n -- d ) 9/10 * degrees ; : mils ( n -- d ) 9/160 * degrees ; : normalize ( d -- d' ) [ 2 pi * mod ] change-value ; CONSTANT: units { degrees gradien...
Write the same algorithm in Factor as shown in this Go implementation.
package main import ( "encoding/xml" "fmt" "log" "os" ) type Inventory struct { XMLName xml.Name `xml:"inventory"` Title string `xml:"title,attr"` Sections []struct { XMLName xml.Name `xml:"section"` Name string `xml:"name,attr"` Items []struct { XMLName xml.Name `xml:"item"` Name ...
"""<inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="445322344" stock="18"> <name>Levitation Salve</name> ...
Translate this program into Factor but keep the logic exactly as in Go.
package main import ( "fmt" "sort" ) type rankable interface { Len() int RankEqual(int, int) bool } func StandardRank(d rankable) []float64 { r := make([]float64, d.Len()) var k int for i := range r { if i == 0 || !d.RankEqual(i, i-1) { k = i + 1 } r[i] = float64(k) } return r } func ModifiedRank(...
USING: arrays assocs formatting fry generalizations io kernel math math.ranges math.statistics math.vectors sequences splitting.monotonic ; IN: rosetta-code.ranking CONSTANT: ranks { { 44 "Solomon" } { 42 "Jason" } { 42 "Errol" } { 41 "Garry" } { 41 "Bernard" } { 41 "Barry" } { 39 "Stephen" } } : rank ( s...
Change the programming language of this snippet from Go to Factor without modifying what it does.
package main import ( "bufio" "fmt" "log" "os" "regexp" "strings" ) func main() { f, err := os.Open("unixdict.txt") if err != nil { log.Fatalln(err) } defer f.Close() s := bufio.NewScanner(f) rie := regexp.MustCompile("^ie|[^c]ie") rei := regexp.MustCompile("^ei|[^c]ei") var cie, ie int var cei, ei ...
USING: combinators formatting generalizations io.encodings.utf8 io.files kernel literals math prettyprint regexp sequences ; IN: rosetta-code.i-before-e : correct ( #correct #incorrect rule-str -- ) pprint " is correct for %d and incorrect for %d.\n" printf ; : plausibility ( #correct #incorrect -- str ) 2 * ...
Rewrite this program in Factor while keeping its functionality equivalent to the Go version.
package main import ( "bufio" "fmt" "log" "os" "regexp" "strings" ) func main() { f, err := os.Open("unixdict.txt") if err != nil { log.Fatalln(err) } defer f.Close() s := bufio.NewScanner(f) rie := regexp.MustCompile("^ie|[^c]ie") rei := regexp.MustCompile("^ei|[^c]ei") var cie, ie int var cei, ei ...
USING: combinators formatting generalizations io.encodings.utf8 io.files kernel literals math prettyprint regexp sequences ; IN: rosetta-code.i-before-e : correct ( #correct #incorrect rule-str -- ) pprint " is correct for %d and incorrect for %d.\n" printf ; : plausibility ( #correct #incorrect -- str ) 2 * ...
Change the programming language of this snippet from Go to Factor without modifying what it does.
package main import ( "fmt" "sort" ) func permute(s string) []string { var res []string if len(s) == 0 { return res } b := []byte(s) var rc func(int) rc = func(np int) { if np == 1 { res = append(res, string(b)) return } np1 := n...
USING: formatting grouping kernel math math.combinatorics math.parser sequences ; : next-highest ( m -- n ) number>string dup [ >= ] monotonic? [ drop 0 ] [ next-permutation string>number ] if ; { 0 9 12 21 12453 738440 45072010 95322020 9589776899767587796600 } [ dup next-highest "%d -> %d\n" printf ...
Translate this program into Factor but keep the logic exactly as in Go.
package main import ( "fmt" "sort" ) func permute(s string) []string { var res []string if len(s) == 0 { return res } b := []byte(s) var rc func(int) rc = func(np int) { if np == 1 { res = append(res, string(b)) return } np1 := n...
USING: formatting grouping kernel math math.combinatorics math.parser sequences ; : next-highest ( m -- n ) number>string dup [ >= ] monotonic? [ drop 0 ] [ next-permutation string>number ] if ; { 0 9 12 21 12453 738440 45072010 95322020 9589776899767587796600 } [ dup next-highest "%d -> %d\n" printf ...
Write a version of this Go function in Factor with identical behavior.
package main import ( "fmt" "math" "strings" ) func main() { for _, n := range [...]int64{ 0, 4, 6, 11, 13, 75, 100, 337, -164, math.MaxInt64, } { fmt.Println(fourIsMagic(n)) } } func fourIsMagic(n int64) string { s := say(n) s = strings.ToUpper(s[:1]) + s[1:] t := s for n != 4 { n = int64(len(s)) ...
USING: ascii formatting io kernel make math.text.english regexp sequences ; IN: rosetta-code.four-is-magic : number>english ( n -- str ) number>text R/ and |,/ "" re-replace ; : next-len ( n -- m ) number>english length ; : len-chain ( n -- seq ) [ [ dup 4 = ] [ dup , next-len ] until , ] { } make ; ...
Produce a language-to-language conversion: from Go to Factor, same semantics.
package main import ( "fmt" "math/rand" "strings" "time" ) var cylinder = [6]bool{} func rshift() { t := cylinder[5] for i := 4; i >= 0; i-- { cylinder[i+1] = cylinder[i] } cylinder[0] = t } func unload() { for i := 0; i < 6; i++ { cylinder[i] = false } } fun...
USING: accessors assocs circular formatting fry kernel literals math random sequences ; IN: rosetta-code.roulette CONSTANT: cyl $[ { f f f f f f } <circular> ] : cylinder ( -- seq ) cyl [ drop f ] map : load ( seq -- seq' ) 0 over nth [ dup rotate-circular ] when t 0 rot [ set-nth ] [ rotate-circular ] [ ] t...
Change the following Go code into Factor without altering its purpose.
package main import ( "fmt" "math/rand" ) type symbols struct{ k, q, r, b, n rune } var A = symbols{'K', 'Q', 'R', 'B', 'N'} var W = symbols{'♔', '♕', '♖', '♗', '♘'} var B = symbols{'♚', '♛', '♜', '♝', '♞'} var krn = []string{ "nnrkr", "nrnkr", "nrknr", "nrkrn", "rnnkr", "rnknr", "rnkrn", "rknnr...
USING: io kernel math random sequences ; IN: rosetta-code.chess960 : empty ( seq -- n ) 32 swap indices random ; : next ( seq -- n ) 32 swap index ; : place ( seq elt n -- seq' ) rot [ set-nth ] keep ; : white-bishop ( -- elt n ) CHAR: ♗ 4 random 2 * ; : black-bishop ( -- elt n ) w...
Transform the following Go implementation into Factor, maintaining the same output and logic.
package main import ( "fmt" "regexp" ) var bits = []string{ "0 0 0 1 1 0 1 ", "0 0 1 1 0 0 1 ", "0 0 1 0 0 1 1 ", "0 1 1 1 1 0 1 ", "0 1 0 0 0 1 1 ", "0 1 1 0 0 0 1 ", "0 1 0 1 1 1 1 ", "0 1 1 1 0 1 1 ", "0 1 1 0 1 1 1 ", "0 0 0 1 0 1 1 ", } var ( lhs = make(map[st...
USING: combinators combinators.short-circuit formatting grouping kernel locals math math.functions math.vectors sequences sequences.repeating unicode ; CONSTANT: numbers { " ## #" " ## #" " # ##" " #### #" " # ##" " ## #" " # ####" " ### ##" " ## ###" " # ##" } : up...
Write the same algorithm in Factor as shown in this Go implementation.
import ( "fmt" "strings" ) func main() { for _, n := range []int64{ 1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003, } { fmt.Println(sayOrdinal(n)) } } var irregularOrdinals = map[string]string{ "one": "first", "two": "second", "three": "third", "five": "fifth", "eight": "eighth"...
USING: assocs formatting grouping kernel literals locals math math.parser math.text.english qw regexp sequences splitting.extras ; IN: rosetta-code.spelling-ordinal-numbers <PRIVATE CONSTANT: test-cases qw{ 1 2 3 4 5 11 65 100 101 272 23456 8007006005004003 123 00123.0 1.23e2 1,2,3 0b1111011 0o173 0x7B 27...
Generate a Factor translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) totalSecs := 0 totalSteps := 0 fmt.Println("Seconds steps behind steps ahead") fmt.Println("------- ------------ -----------") for trial := 1; trial < 10000; trial++ { ...
USING: combinators.random io kernel math math.order prettyprint ; : position ( -- n ) 0 ; : stairs ( -- n ) 100 ; : new ( -- m n ) position stairs ; : incd ( m n -- o p ) swap 1 + swap ; : seconds ( m -- n ) 100 - 5 / ; : window? ( n -- ? ) seconds 600 609 between? ; : zap ( m...
Transform the following Go implementation into Factor, maintaining the same output and logic.
package main import "fmt" func largestPrimeFactor(n uint64) uint64 { if n < 2 { return 1 } inc := [8]uint64{4, 2, 4, 2, 4, 6, 2, 6} max := uint64(1) for n%2 == 0 { max = 2 n /= 2 } for n%3 == 0 { max = 3 n /= 3 } for n%5 == 0 { max = ...
USING: math.primes.factors prettyprint sequences ; 600851475143 factors last .
Can you help me rewrite this code in Factor instead of Go, keeping it the same logically?
package main import ( "image" "image/color" "image/gif" "log" "os" ) var ( black = color.RGBA{0, 0, 0, 255} red = color.RGBA{255, 0, 0, 255} green = color.RGBA{0, 255, 0, 255} blue = color.RGBA{0, 0, 255, 255} magenta = color.RGBA{255, 0, 255, 255} cyan = colo...
USING: accessors calendar colors.constants combinators kernel locals math math.vectors opengl timers ui ui.gadgets ui.gadgets.worlds ui.pens.solid ui.render ; IN: rosetta-code.vibrating-squares TUPLE: vibrating < gadget { old-color initial: COLOR: black } { new-color initial: COLOR: red } { frame initial: ...
Please provide an equivalent version of this Go code in Factor.
package main import ( "fmt" "math" ) func main() { list := []float64{1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3} maxDiff := -1.0 var maxPairs [][2]float64 for i := 1; i < len(list); i++ { diff := math.Abs(list[i-1] - list[i]) if diff > maxDiff { maxDi...
USING: assocs grouping math prettyprint sequences ; : max-diff ( seq -- assoc ) 2 clump [ first2 - abs ] collect-by >alist supremum ; { 1 8 2 -3 0 1 1 -2.3 0 5.5 8 6 2 9 11 10 3 } max-diff .
Maintain the same structure and functionality when rewriting this code in Factor.
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h float64 func lineTo(newX, newY float64) { dc.LineTo(newX-width/2+h, height-newY+2*h) cx, cy = newX, newY } func lineN() { lineTo(cx...
USING: accessors kernel L-system sequences ui ; : curve ( L-system -- L-system ) L-parser-dialect { "G" [ dup length>> draw-forward ] } suffix >>commands [ 45 >>angle ] >>turtle-values "F--XF--F--XF" >>axiom { { "X" "XF+G+XF--F--XF+G+X" } } >>rules ; [ <L-system> curve "Sierpinski curv...
Generate an equivalent Factor version of this Go code.
package main import ( "github.com/fogleman/gg" "math" ) var ( width = 770.0 height = 770.0 dc = gg.NewContext(int(width), int(height)) ) var cx, cy, h float64 func lineTo(newX, newY float64) { dc.LineTo(newX-width/2+h, height-newY+2*h) cx, cy = newX, newY } func lineN() { lineTo(cx...
USING: accessors kernel L-system sequences ui ; : curve ( L-system -- L-system ) L-parser-dialect { "G" [ dup length>> draw-forward ] } suffix >>commands [ 45 >>angle ] >>turtle-values "F--XF--F--XF" >>axiom { { "X" "XF+G+XF--F--XF+G+X" } } >>rules ; [ <L-system> curve "Sierpinski curv...
Generate an equivalent Factor version of this Go code.
package main import ( "fmt" "strings" ) func main() { s := "abracadabra" ss := []byte(s) var ixs []int for ix, c := range s { if c == 'a' { ixs = append(ixs, ix) } } repl := "ABaCD" for i := 0; i < 5; i++ { ss[ixs[i]] = repl[i] } s = stri...
USING: assocs formatting grouping kernel random sequences ; CONSTANT: instrs { CHAR: a 1 CHAR: A CHAR: a 2 CHAR: B CHAR: a 4 CHAR: C CHAR: a 5 CHAR: D CHAR: b 1 CHAR: E CHAR: r 2 CHAR: F } : counts ( seq -- assoc ) H{ } clone swap [ 2dup swap inc-at dupd of ] zip-with nip ; : replace-nths...
Write the same algorithm in Factor as shown in this Go implementation.
package main import ( "fmt" "strings" ) func main() { s := "abracadabra" ss := []byte(s) var ixs []int for ix, c := range s { if c == 'a' { ixs = append(ixs, ix) } } repl := "ABaCD" for i := 0; i < 5; i++ { ss[ixs[i]] = repl[i] } s = stri...
USING: assocs formatting grouping kernel random sequences ; CONSTANT: instrs { CHAR: a 1 CHAR: A CHAR: a 2 CHAR: B CHAR: a 4 CHAR: C CHAR: a 5 CHAR: D CHAR: b 1 CHAR: E CHAR: r 2 CHAR: F } : counts ( seq -- assoc ) H{ } clone swap [ 2dup swap inc-at dupd of ] zip-with nip ; : replace-nths...
Maintain the same structure and functionality when rewriting this code in Factor.
package main import ( "fmt" "os" "sort" "strings" "text/template" ) func main() { const t = `[[[{{index .P 1}}, {{index .P 2}}], [{{index .P 3}}, {{index .P 4}}, {{index .P 1}}], {{index .P 5}}]] ` type S struct { P map[int]string } var s S s.P = map[int]string{ ...
USING: formatting kernel literals math sequences sequences.deep ; IN: rosetta-code.nested-template-data CONSTANT: payloads $[ 7 <iota> [ "Payload#%d" sprintf ] map ] : insert-payloads ( template -- data-structure ) [ dup fixnum? [ payloads ?nth ] when ] deep-map ; { { { 1 2 } { 3 4 1 } 5 } } { {...
Write a version of this Go function in Factor with identical behavior.
package main import ( "fmt" "strings" ) func sentenceType(s string) string { if len(s) == 0 { return "" } var types []string for _, c := range s { if c == '?' { types = append(types, "Q") } else if c == '!' { types = append(types, "E") } ...
USING: combinators io kernel regexp sequences sets splitting wrap.strings ; CONSTANT: common-abbreviations { "A.B." "abbr." "Acad." "A.D." "alt." "A.M." "Assn." "at. no." "at. wt." "Aug." "Ave." "b." "B.A." "B.C." "b.p." "B.S." "c." "Capt." "cent." "co." "Col." "Comdr." "Corp." "Cpl." "d." "D.C." "De...
Generate a Factor translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math/big" "rcu" ) func lcm(n int) *big.Int { lcm := big.NewInt(1) t := new(big.Int) for _, p := range rcu.Primes(n) { f := p for f*p <= n { f *= p } lcm.Mul(lcm, t.SetUint64(uint64(f))) } return lcm } func main()...
USING: math.functions math.ranges prettyprint sequences ; 20 [1,b] 1 [ lcm ] reduce .
Transform the following Go implementation into Factor, maintaining the same output and logic.
package main import ( "fmt" "rcu" "sort" ) func main() { list := []int{2, 43, 81, 122, 63, 13, 7, 95, 103} var primes []int for _, e := range list { if rcu.IsPrime(e) { primes = append(primes, e) } } sort.Ints(primes) fmt.Println(primes) }
USING: math.primes prettyprint sequences sorting ; { 2 43 81 122 63 13 7 95 103 } [ prime? ] filter natural-sort .
Transform the following Go implementation into Factor, maintaining the same output and logic.
package main import ( "fmt" "sort" ) func firstMissingPositive(a []int) int { var b []int for _, e := range a { if e > 0 { b = append(b, e) } } sort.Ints(b) le := len(b) if le == 0 || b[0] > 1 { return 1 } for i := 1; i < le; i++ { if...
USING: formatting fry hash-sets kernel math sequences sets ; : first-missing ( seq -- n ) >hash-set 1 swap '[ dup _ in? ] [ 1 + ] while ; { { 1 2 0 } { 3 4 1 1 } { 7 8 9 11 12 } { 1 2 3 4 5 } { -6 -5 -2 -1 } { 5 -5 } { -2 } { 1 } { } } [ dup first-missing "%u ==> %d\n" printf ] each
Preserve the algorithm and functionality while converting the code from Go to Factor.
package main import ( "fmt" "math" "rcu" ) func main() { limit := 999999 primes := rcu.Primes(limit) fmt.Println("Adjacent primes under 1,000,000 whose difference is a square > 36:") for i := 1; i < len(primes); i++ { diff := primes[i] - primes[i-1] if diff > 36 { ...
USING: formatting io kernel lists lists.lazy math math.functions math.primes.lists sequences ; : adj-primes ( -- list ) lprimes dup cdr lzip ; : diff ( pair -- n ) first2 swap - ; : adj-primes-diff ( -- list ) adj-primes [ dup diff suffix ] lmap-lazy ; : big-adj-primes-diff ( -- list ) adj-primes-diff [ las...
Generate a Factor translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math" "rcu" ) func main() { limit := 999999 primes := rcu.Primes(limit) fmt.Println("Adjacent primes under 1,000,000 whose difference is a square > 36:") for i := 1; i < len(primes); i++ { diff := primes[i] - primes[i-1] if diff > 36 { ...
USING: formatting io kernel lists lists.lazy math math.functions math.primes.lists sequences ; : adj-primes ( -- list ) lprimes dup cdr lzip ; : diff ( pair -- n ) first2 swap - ; : adj-primes-diff ( -- list ) adj-primes [ dup diff suffix ] lmap-lazy ; : big-adj-primes-diff ( -- list ) adj-primes-diff [ las...
Convert this Go block to Factor, preserving its control flow and logic.
package main import "fmt" type frac struct{ num, den int } func (f frac) String() string { return fmt.Sprintf("%d/%d", f.num, f.den) } func f(l, r frac, n int) { m := frac{l.num + r.num, l.den + r.den} if m.den <= n { f(l, m, n) fmt.Print(m, " ") f(m, r, n) } } func main() {...
USING: formatting io kernel math math.primes.factors math.ranges locals prettyprint sequences sequences.extras sets tools.time ; IN: rosetta-code.farey-sequence :: p/q ( n a/b c/d -- p/q ) a/b c/d [ >fraction ] bi@ :> ( a b c d ) n b + d / >integer [ c * a - ] [ d * b - ] bi / ; : print-farey ( order --...
Rewrite the snippet below in Factor so it works the same as the original Go code.
package main import "fmt" type frac struct{ num, den int } func (f frac) String() string { return fmt.Sprintf("%d/%d", f.num, f.den) } func f(l, r frac, n int) { m := frac{l.num + r.num, l.den + r.den} if m.den <= n { f(l, m, n) fmt.Print(m, " ") f(m, r, n) } } func main() {...
USING: formatting io kernel math math.primes.factors math.ranges locals prettyprint sequences sequences.extras sets tools.time ; IN: rosetta-code.farey-sequence :: p/q ( n a/b c/d -- p/q ) a/b c/d [ >fraction ] bi@ :> ( a b c d ) n b + d / >integer [ c * a - ] [ d * b - ] bi / ; : print-farey ( order --...
Convert the following code from Go to Factor, ensuring the logic remains intact.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(999) sum := 0 fmt.Println(" i p[i] Σp[i]") fmt.Println("----------------") for i := 0; i < len(primes); i += 2 { sum += primes[i] if rcu.IsPrime(sum) { fmt.Printf("%3d %3d %6s\n", i+1, p...
USING: assocs assocs.extras kernel math.primes math.statistics prettyprint sequences.extras ; 1000 primes-upto <evens> dup cum-sum zip [ prime? ] filter-values .
Ensure the translated Factor code behaves exactly like the original Go snippet.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(999) sum := 0 fmt.Println(" i p[i] Σp[i]") fmt.Println("----------------") for i := 0; i < len(primes); i += 2 { sum += primes[i] if rcu.IsPrime(sum) { fmt.Printf("%3d %3d %6s\n", i+1, p...
USING: assocs assocs.extras kernel math.primes math.statistics prettyprint sequences.extras ; 1000 primes-upto <evens> dup cum-sum zip [ prime? ] filter-values .
Translate the given Go code snippet into Factor without altering its behavior.
package main import ( "fmt" "math" "strings" ) const threshold = uint64(1) << 47 func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 } func contains(s []uint64, search uint64) bool { return indexOf(s, sea...
USING: combinators combinators.short-circuit formatting kernel literals locals math math.functions math.primes.factors math.ranges namespaces pair-rocket sequences sets ; FROM: namespaces => set ; IN: rosetta-code.aliquot SYMBOL: terms CONSTANT: 2^47 $[ 2 47 ^ ] CONSTANT: test-cases { 11 12 28 496 220 1184 12496 1...
Write a version of this Go function in Factor with identical behavior.
package main import ( "fmt" "math" "strings" ) const threshold = uint64(1) << 47 func indexOf(s []uint64, search uint64) int { for i, e := range s { if e == search { return i } } return -1 } func contains(s []uint64, search uint64) bool { return indexOf(s, sea...
USING: combinators combinators.short-circuit formatting kernel literals locals math math.functions math.primes.factors math.ranges namespaces pair-rocket sequences sets ; FROM: namespaces => set ; IN: rosetta-code.aliquot SYMBOL: terms CONSTANT: 2^47 $[ 2 47 ^ ] CONSTANT: test-cases { 11 12 28 496 220 1184 12496 1...
Keep all operations the same but rewrite the snippet in Factor.
package main import "fmt" func isPrime(n uint64) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := uint64(5) for d*d <= n { if n%d == 0 { return false } ...
USING: grouping io kernel lists lists.lazy math math.functions math.primes math.ranges prettyprint sequences ; : magnanimous? ( n -- ? ) dup 10 < [ drop t ] [ dup log10 >integer [1,b] [ 10^ /mod + prime? not ] with find nip >boolean not ] if ; : magnanimous ( n -- seq ) 0 lfrom [ magnanimo...
Translate this program into Factor but keep the logic exactly as in Go.
package main import ( "fmt" "time" "math/big" ) func main() { start := time.Now() one := big.NewInt(1) mp := big.NewInt(0) bp := big.NewInt(0) const max = 22 for count, p := 0, uint(2); count < max; { mp.Lsh(one, p) mp.Sub(mp, one) if mp.ProbablyPrime(0) { elapsed := time.Since(start).Seconds()...
USING: formatting math.primes.lucas-lehmer math.ranges sequences ; : mersennes-upto ( n -- seq ) [1,b] [ lucas-lehmer ] filter ; 3500 mersennes-upto [ "2 ^ %d - 1\n" printf ] each
Write the same algorithm in Factor as shown in this Go implementation.
package main import ( "fmt" "time" "math/big" ) func main() { start := time.Now() one := big.NewInt(1) mp := big.NewInt(0) bp := big.NewInt(0) const max = 22 for count, p := 0, uint(2); count < max; { mp.Lsh(one, p) mp.Sub(mp, one) if mp.ProbablyPrime(0) { elapsed := time.Since(start).Seconds()...
USING: formatting math.primes.lucas-lehmer math.ranges sequences ; : mersennes-upto ( n -- seq ) [1,b] [ lucas-lehmer ] filter ; 3500 mersennes-upto [ "2 ^ %d - 1\n" printf ] each
Can you help me rewrite this code in Factor instead of Go, keeping it the same logically?
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.functions math.primes prettyprint ; 2 [ 1 lfrom swap '[ 3 ^ _ + ] lmap-lazy [ prime? ] lfilter car ] lfrom-by [ 15000 < ] lwhile [ pprint bl ] leach nl
Change the following Go code into Factor without altering its purpose.
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.functions math.primes prettyprint ; 2 [ 1 lfrom swap '[ 3 ^ _ + ] lmap-lazy [ prime? ] lfilter car ] lfrom-by [ 15000 < ] lwhile [ pprint bl ] leach nl
Can you help me rewrite this code in Factor instead of Go, keeping it the same logically?
package main import "fmt" 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] = true } ...
USING: combinators.short-circuit fry interpolate io kernel literals locals make math math.primes math.ranges prettyprint qw sequences tools.memory.private ; IN: rosetta-code.sexy-primes CONSTANT: limit 1,000,035 CONSTANT: primes $[ limit primes-upto ] CONSTANT: tuplet-names qw{ pair triplet quadruplet quintuplet } : ...
Change the following Go code into Factor without altering its purpose.
package main import "fmt" 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] = true } ...
USING: formatting grouping kernel math math.primes sequences tools.memory.private ; IN: rosetta-code.strong-primes : fn ( p-1 p p+1 -- p sum ) rot + 2 / ; : strong? ( p-1 p p+1 -- ? ) fn > ; : weak? ( p-1 p p+1 -- ? ) fn < ; : swprimes ( seq quot -- seq ) [ 3 <clumps> ] dip [ first3 ] prepose filter [ second ] ma...
Transform the following Go implementation into Factor, maintaining the same output and logic.
package main import "fmt" func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d...
USING: formatting io kernel math math.combinatorics math.primes sequences tools.memory.private ; : .triplet ( seq -- ) "%2d+%2d+%2d = %d\n" vprintf ; : strange ( n -- ) primes-upto 3 [ dup sum dup prime? [ suffix .triplet ] [ 2drop ] if ] each-combination ; : count-strange ( n -- count ) 0 swap prime...
Keep all operations the same but rewrite the snippet in Factor.
package main import "fmt" func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d...
USING: formatting io kernel math math.combinatorics math.primes sequences tools.memory.private ; : .triplet ( seq -- ) "%2d+%2d+%2d = %d\n" vprintf ; : strange ( n -- ) primes-upto 3 [ dup sum dup prime? [ suffix .triplet ] [ 2drop ] if ] each-combination ; : count-strange ( n -- count ) 0 swap prime...
Change the programming language of this snippet from Go to Factor without modifying what it does.
package main import ( "fmt" "rcu" ) func motzkin(n int) []int { m := make([]int, n+1) m[0] = 1 m[1] = 1 for i := 2; i <= n; i++ { m[i] = (m[i-1]*(2*i+1) + m[i-2]*(3*i-3)) / (i + 2) } return m } func main() { fmt.Println(" n M[n] Prime?") fmt.Printl...
USING: combinators formatting io kernel math math.primes tools.memory.private ; MEMO: motzkin ( m -- n ) dup 2 < [ drop 1 ] [ { [ 2 * 1 + ] [ 1 - motzkin * ] [ 3 * 3 - ] [ 2 - motzkin * + ] [ 2 + /i ] } cleave ] if ; " n ...
Write the same code in Factor as shown below in Go.
package main import ( "fmt" "runtime" "ex" ) func main() { f := func() { pc, _, _, _ := runtime.Caller(0) fmt.Println(runtime.FuncForPC(pc).Name(), "here!") } ex.X(f) }
USE: math 2 2 +
Please provide an equivalent version of this Go code in Factor.
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...