Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write the same algorithm in Factor as shown in this Go implementation. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
)
var p, p2 *big.Int
func isQuadPowerPrimeSeed(n uint64) bool {
nn := new(big.Int).SetUint64(n)
p.Set(nn)
k := new(big.Int).SetUint64(n + 1)
p2.Add(p, k)
if !p2.ProbablyPrime(15) {
return false
}
for i := 0; i < 3; i++ {
p.Mul(p, nn)
p2.Set(p)
p2.Add(p2, k)
if !p2.ProbablyPrime(15) {
return false
}
}
return true
}
func ord(c int) string {
m := c % 100
if m > 4 && m <= 20 {
return "th"
}
m %= 10
switch m {
case 1:
return "st"
case 2:
return "nd"
case 3:
return "rd"
default:
return "th"
}
}
func main() {
p = new(big.Int)
p2 = new(big.Int)
c := 0
m := 1
n := uint64(1)
fmt.Println("First fifty quad-power prime seeds:")
for ; c < 50; n++ {
if isQuadPowerPrimeSeed(n) {
fmt.Printf("%7s ", rcu.Commatize(int(n)))
c++
if c%10 == 0 {
fmt.Println()
}
}
}
fmt.Println("\nFirst quad-power prime seed greater than:")
for {
if isQuadPowerPrimeSeed(n) {
c++
if n > 1000000*uint64(m) {
ns := rcu.Commatize(int(n))
fmt.Printf(" %2d million is the %d%s: %10s\n", m, c, ord(c), ns)
m++
if m == 11 {
break
}
}
}
n++
}
}
| USING: grouping io kernel lists lists.lazy math math.functions
math.primes prettyprint sequences tools.memory.private ;
: seed? ( n -- ? )
{ 1 2 3 4 } [ dupd ^ 1 + + prime? ] with all? ;
: quads ( -- list )
1 lfrom [ seed? ] lfilter [ commas ] lmap-lazy ;
"First fifty quad-power prime seeds:" print
50 quads ltake list>array 10 group simple-table.
|
Change the programming language of this snippet from Go to Factor without modifying what it does. | package main
import (
"fmt"
big "github.com/ncw/gmp"
"rcu"
)
var p, p2 *big.Int
func isQuadPowerPrimeSeed(n uint64) bool {
nn := new(big.Int).SetUint64(n)
p.Set(nn)
k := new(big.Int).SetUint64(n + 1)
p2.Add(p, k)
if !p2.ProbablyPrime(15) {
return false
}
for i := 0; i < 3; i++ {
p.Mul(p, nn)
p2.Set(p)
p2.Add(p2, k)
if !p2.ProbablyPrime(15) {
return false
}
}
return true
}
func ord(c int) string {
m := c % 100
if m > 4 && m <= 20 {
return "th"
}
m %= 10
switch m {
case 1:
return "st"
case 2:
return "nd"
case 3:
return "rd"
default:
return "th"
}
}
func main() {
p = new(big.Int)
p2 = new(big.Int)
c := 0
m := 1
n := uint64(1)
fmt.Println("First fifty quad-power prime seeds:")
for ; c < 50; n++ {
if isQuadPowerPrimeSeed(n) {
fmt.Printf("%7s ", rcu.Commatize(int(n)))
c++
if c%10 == 0 {
fmt.Println()
}
}
}
fmt.Println("\nFirst quad-power prime seed greater than:")
for {
if isQuadPowerPrimeSeed(n) {
c++
if n > 1000000*uint64(m) {
ns := rcu.Commatize(int(n))
fmt.Printf(" %2d million is the %d%s: %10s\n", m, c, ord(c), ns)
m++
if m == 11 {
break
}
}
}
n++
}
}
| USING: grouping io kernel lists lists.lazy math math.functions
math.primes prettyprint sequences tools.memory.private ;
: seed? ( n -- ? )
{ 1 2 3 4 } [ dupd ^ 1 + + prime? ] with all? ;
: quads ( -- list )
1 lfrom [ seed? ] lfilter [ commas ] lmap-lazy ;
"First fifty quad-power prime seeds:" print
50 quads ltake list>array 10 group simple-table.
|
Rewrite this program in Factor while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"rcu"
)
const LIMIT = 999999
var primes = rcu.Primes(LIMIT)
func longestSeq(dir string) {
pd := 0
longSeqs := [][]int{{2}}
currSeq := []int{2}
for i := 1; i < len(primes); i++ {
d := primes[i] - primes[i-1]
if (dir == "ascending" && d <= pd) || (dir == "descending" && d >= pd) {
if len(currSeq) > len(longSeqs[0]) {
longSeqs = [][]int{currSeq}
} else if len(currSeq) == len(longSeqs[0]) {
longSeqs = append(longSeqs, currSeq)
}
currSeq = []int{primes[i-1], primes[i]}
} else {
currSeq = append(currSeq, primes[i])
}
pd = d
}
if len(currSeq) > len(longSeqs[0]) {
longSeqs = [][]int{currSeq}
} else if len(currSeq) == len(longSeqs[0]) {
longSeqs = append(longSeqs, currSeq)
}
fmt.Println("Longest run(s) of primes with", dir, "differences is", len(longSeqs[0]), ":")
for _, ls := range longSeqs {
var diffs []int
for i := 1; i < len(ls); i++ {
diffs = append(diffs, ls[i]-ls[i-1])
}
for i := 0; i < len(ls)-1; i++ {
fmt.Print(ls[i], " (", diffs[i], ") ")
}
fmt.Println(ls[len(ls)-1])
}
fmt.Println()
}
func main() {
fmt.Println("For primes < 1 million:\n")
for _, dir := range []string{"ascending", "descending"} {
longestSeq(dir)
}
}
| USING: arrays assocs formatting grouping io kernel literals math
math.primes math.statistics sequences sequences.extras
tools.memory.private ;
<< CONSTANT: limit 1,000,000 >>
CONSTANT: primes $[ limit primes-upto ]
: run ( n quot -- seq quot )
[ primes ] [ <clumps> ] [ ] tri*
'[ differences _ monotonic? ] ; inline
: max-run ( quot -- n )
1 swap '[ 1 + dup _ run find drop ] loop 1 - ; inline
: runs ( quot -- seq )
[ max-run ] keep run filter ; inline
: .run ( seq -- )
dup differences [ [ commas ] map ] bi@
[ "(" ")" surround ] map 2array round-robin " " join print ;
: .runs ( quot -- )
[ runs ] keep [ < ] = "rising" "falling" ? limit commas
"Largest run(s) of %s gaps between primes less than %s:\n"
printf [ .run ] each ; inline
[ < ] [ > ] [ .runs nl ] bi@
|
Generate a Factor translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math/big"
"rcu"
)
func main() {
const LIMIT = 11000
primes := rcu.Primes(LIMIT)
facts := make([]*big.Int, LIMIT)
facts[0] = big.NewInt(1)
for i := int64(1); i < LIMIT; i++ {
facts[i] = new(big.Int)
facts[i].Mul(facts[i-1], big.NewInt(i))
}
sign := int64(1)
f := new(big.Int)
zero := new(big.Int)
fmt.Println(" n: Wilson primes")
fmt.Println("--------------------")
for n := 1; n < 12; n++ {
fmt.Printf("%2d: ", n)
sign = -sign
for _, p := range primes {
if p < n {
continue
}
f.Mul(facts[n-1], facts[p-n])
f.Sub(f, big.NewInt(sign))
p2 := int64(p * p)
bp2 := big.NewInt(p2)
if f.Rem(f, bp2).Cmp(zero) == 0 {
fmt.Printf("%d ", p)
}
}
fmt.Println()
}
}
| USING: formatting infix io kernel literals math math.functions
math.primes math.ranges prettyprint sequences sequences.extras ;
<< CONSTANT: limit 11,000 >>
CONSTANT: primes $[ limit primes-upto ]
CONSTANT: factorials
$[ limit [1,b] 1 [ * ] accumulate* 1 prefix ]
: factorial ( n -- n
INFIX:: fn ( p n -- m )
factorial(n-1) * factorial(p-n) - -1**n ;
: wilson? ( p n -- ? ) [ fn ] keepd sq divisor? ; inline
: order ( n -- seq )
primes swap [ [ < ] curry drop-while ] keep
[ wilson? ] curry filter ;
: order. ( n -- )
dup "%2d: " printf order [ pprint bl ] each nl ;
" n: Wilson primes\n--------------------" print
11 [1,b] [ order. ] each
|
Convert this Go snippet to Factor and keep its semantics consistent. | package main
import "fmt"
func padovanN(n, t int) []int {
if n < 2 || t < 3 {
ones := make([]int, t)
for i := 0; i < t; i++ {
ones[i] = 1
}
return ones
}
p := padovanN(n-1, t)
for i := n + 1; i < t; i++ {
p[i] = 0
for j := i - 2; j >= i-n-1; j-- {
p[i] += p[j]
}
}
return p
}
func main() {
t := 15
fmt.Println("First", t, "terms of the Padovan n-step number sequences:")
for n := 2; n <= 8; n++ {
fmt.Printf("%d: %3d\n", n, padovanN(n, t))
}
}
| USING: compiler.tree.propagation.call-effect io kernel math
math.ranges prettyprint sequences ;
: padn ( m n -- seq )
V{ "|" 1 1 1 } over prefix clone over 2 -
[ dup last2 + suffix
[ dup length 1 - pick [ - ] keepd pick <slice> sum suffix
times nip ;
"Padovan n-step sequences" print
2 8 [a..b] [ 15 swap padn ] map simple-table.
|
Produce a language-to-language conversion: from Go to Factor, same semantics. | package main
import (
"fmt"
"rcu"
)
func main() {
primes := rcu.Primes(5 * 1e6)
var h [][2]int
var h10000 [2]int
for i, count := 1, 0; count < 10000; i++ {
if rcu.DigitSum(i, 10) == rcu.DigitSum(primes[i-1], 10) {
count++
if count <= 50 {
h = append(h, [2]int{i, primes[i-1]})
} else if count == 10000 {
h10000 = [2]int{i, primes[i-1]}
}
}
}
fmt.Println("The first 50 Honaker primes (index, prime):\n")
for i := 0; i < 50; i++ {
fmt.Printf("(%3d, %5s) ", h[i][0], rcu.Commatize(h[i][1]))
if (i+1)%5 == 0 {
fmt.Println()
}
}
fmt.Printf("\nand the 10,000th: (%7s, %9s)\n", rcu.Commatize(h10000[0]), rcu.Commatize(h10000[1]))
}
| USING: grouping kernel lists lists.lazy math math.primes.lists
prettyprint sequences ;
: sum-digits ( n -- sum )
0 swap [ 10 /mod rot + swap ] until-zero ;
: honaker ( -- list )
1 lfrom lprimes lzip [ first2 [ sum-digits ] same? ] lfilter ;
50 honaker ltake list>array 5 group simple-table.
|
Write a version of this Go function in Factor with identical behavior. | package main
import (
"fmt"
"rcu"
)
func main() {
const limit = 1e9
primes := rcu.Primes(limit)
var orm30 [][2]int
j := int(1e5)
count := 0
var counts []int
for i := 0; i < len(primes)-1; i++ {
p1 := primes[i]
p2 := primes[i+1]
if (p2-p1)%18 != 0 {
continue
}
key1 := 1
for _, dig := range rcu.Digits(p1, 10) {
key1 *= primes[dig]
}
key2 := 1
for _, dig := range rcu.Digits(p2, 10) {
key2 *= primes[dig]
}
if key1 == key2 {
if count < 30 {
orm30 = append(orm30, [2]int{p1, p2})
}
if p1 >= j {
counts = append(counts, count)
j *= 10
}
count++
}
}
counts = append(counts, count)
fmt.Println("First 30 Ormiston pairs:")
for i := 0; i < 30; i++ {
fmt.Printf("%5v ", orm30[i])
if (i+1)%3 == 0 {
fmt.Println()
}
}
fmt.Println()
j = int(1e5)
for i := 0; i < len(counts); i++ {
fmt.Printf("%s Ormiston pairs before %s\n", rcu.Commatize(counts[i]), rcu.Commatize(j))
j *= 10
}
}
| USING: grouping io kernel lists lists.lazy math math.parser
math.primes.lists math.statistics prettyprint sequences ;
: ormistons ( -- list )
lprimes dup cdr lzip
[ first2 [ >dec histogram ] same? ] lfilter ;
"First 30 Ormiston pairs:" print
30 ormistons ltake list>array 5 group simple-table. nl
ormistons [ first 1e6 < ] lwhile llength pprint bl
"Ormiston pairs less than a million." print
|
Port the provided Go code into Factor while preserving the original functionality. | package main
import (
"fmt"
"math/big"
)
var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper",
"Nickel", "Aluminium", "Iron", "Tin", "Lead"}
func lucas(b int64) {
fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b)
fmt.Print("First 15 elements: ")
var x0, x1 int64 = 1, 1
fmt.Printf("%d, %d", x0, x1)
for i := 1; i <= 13; i++ {
x2 := b*x1 + x0
fmt.Printf(", %d", x2)
x0, x1 = x1, x2
}
fmt.Println()
}
func metallic(b int64, dp int) {
x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)
ratio := big.NewRat(1, 1)
iters := 0
prev := ratio.FloatString(dp)
for {
iters++
x2.Mul(bb, x1)
x2.Add(x2, x0)
this := ratio.SetFrac(x2, x1).FloatString(dp)
if prev == this {
plural := "s"
if iters == 1 {
plural = " "
}
fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this)
return
}
prev = this
x0.Set(x1)
x1.Set(x2)
}
}
func main() {
for b := int64(0); b < 10; b++ {
lucas(b)
metallic(b, 32)
}
fmt.Println("Golden ratio, where b = 1:")
metallic(1, 256)
}
| USING: combinators decimals formatting generalizations io kernel
math prettyprint qw sequences ;
IN: rosetta-code.metallic-ratios
: lucas ( n a b -- n a' b' ) tuck reach * + ;
: lucas. ( n -- )
1 pprint bl 1 1 14 [ lucas over pprint bl ] times 3drop nl ;
: approx ( a b -- d ) swap [ 0 <decimal> ] bi@ 32 D/ ;
: approximate ( n -- value iter )
-1 swap 1 1 0 1 [ 2dup = ]
[ [ 1 + ] 5 ndip [ lucas 2dup approx ] 2dip drop ] until
4nip decimal>ratio swap ;
qw{
Platinum Golden Silver Bronze Copper Nickel Aluminum Iron
Tin Lead
}
[
dup dup approximate {
[ "Lucas sequence for %s ratio " printf ]
[ "where b = %d:\n" printf ]
[ "First 15 elements: " write lucas. ]
[ "Approximated value: %.32f " printf ]
[ "- reached after %d iteration(s)\n\n" printf ]
} spread
] each-index
|
Convert the following code from Go to Factor, ensuring the logic remains intact. | package main
import (
"fmt"
"math/big"
)
var names = [10]string{"Platinum", "Golden", "Silver", "Bronze", "Copper",
"Nickel", "Aluminium", "Iron", "Tin", "Lead"}
func lucas(b int64) {
fmt.Printf("Lucas sequence for %s ratio, where b = %d:\n", names[b], b)
fmt.Print("First 15 elements: ")
var x0, x1 int64 = 1, 1
fmt.Printf("%d, %d", x0, x1)
for i := 1; i <= 13; i++ {
x2 := b*x1 + x0
fmt.Printf(", %d", x2)
x0, x1 = x1, x2
}
fmt.Println()
}
func metallic(b int64, dp int) {
x0, x1, x2, bb := big.NewInt(1), big.NewInt(1), big.NewInt(0), big.NewInt(b)
ratio := big.NewRat(1, 1)
iters := 0
prev := ratio.FloatString(dp)
for {
iters++
x2.Mul(bb, x1)
x2.Add(x2, x0)
this := ratio.SetFrac(x2, x1).FloatString(dp)
if prev == this {
plural := "s"
if iters == 1 {
plural = " "
}
fmt.Printf("Value to %d dp after %2d iteration%s: %s\n\n", dp, iters, plural, this)
return
}
prev = this
x0.Set(x1)
x1.Set(x2)
}
}
func main() {
for b := int64(0); b < 10; b++ {
lucas(b)
metallic(b, 32)
}
fmt.Println("Golden ratio, where b = 1:")
metallic(1, 256)
}
| USING: combinators decimals formatting generalizations io kernel
math prettyprint qw sequences ;
IN: rosetta-code.metallic-ratios
: lucas ( n a b -- n a' b' ) tuck reach * + ;
: lucas. ( n -- )
1 pprint bl 1 1 14 [ lucas over pprint bl ] times 3drop nl ;
: approx ( a b -- d ) swap [ 0 <decimal> ] bi@ 32 D/ ;
: approximate ( n -- value iter )
-1 swap 1 1 0 1 [ 2dup = ]
[ [ 1 + ] 5 ndip [ lucas 2dup approx ] 2dip drop ] until
4nip decimal>ratio swap ;
qw{
Platinum Golden Silver Bronze Copper Nickel Aluminum Iron
Tin Lead
}
[
dup dup approximate {
[ "Lucas sequence for %s ratio " printf ]
[ "where b = %d:\n" printf ]
[ "First 15 elements: " write lucas. ]
[ "Approximated value: %.32f " printf ]
[ "- reached after %d iteration(s)\n\n" printf ]
} spread
] each-index
|
Generate a Factor translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math"
"rcu"
)
var maxDepth = 6
var maxBase = 36
var c = rcu.PrimeSieve(int(math.Pow(float64(maxBase), float64(maxDepth))), true)
var digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
var maxStrings [][][]int
var mostBases = -1
func maxSlice(a []int) int {
max := 0
for _, e := range a {
if e > max {
max = e
}
}
return max
}
func maxInt(a, b int) int {
if a > b {
return a
}
return b
}
func process(indices []int) {
minBase := maxInt(2, maxSlice(indices)+1)
if maxBase - minBase + 1 < mostBases {
return
}
var bases []int
for b := minBase; b <= maxBase; b++ {
n := 0
for _, i := range indices {
n = n*b + i
}
if !c[n] {
bases = append(bases, b)
}
}
count := len(bases)
if count > mostBases {
mostBases = count
indices2 := make([]int, len(indices))
copy(indices2, indices)
maxStrings = [][][]int{[][]int{indices2, bases}}
} else if count == mostBases {
indices2 := make([]int, len(indices))
copy(indices2, indices)
maxStrings = append(maxStrings, [][]int{indices2, bases})
}
}
func printResults() {
fmt.Printf("%d\n", len(maxStrings[0][1]))
for _, m := range maxStrings {
s := ""
for _, i := range m[0] {
s = s + string(digits[i])
}
fmt.Printf("%s -> %v\n", s, m[1])
}
}
func nestedFor(indices []int, length, level int) {
if level == len(indices) {
process(indices)
} else {
indices[level] = 0
if level == 0 {
indices[level] = 1
}
for indices[level] < length {
nestedFor(indices, length, level+1)
indices[level]++
}
}
}
func main() {
for depth := 1; depth <= maxDepth; depth++ {
fmt.Print(depth, " character strings which are prime in most bases: ")
maxStrings = maxStrings[:0]
mostBases = -1
indices := make([]int, depth)
nestedFor(indices, maxBase, 0)
printResults()
fmt.Println()
}
}
| USING: assocs assocs.extras formatting io kernel math
math.functions math.parser math.primes math.ranges present
sequences ;
: prime?* ( n -- ? ) [ prime? ] [ f ] if* ; inline
: (bases) ( n -- range quot )
present 2 36 [a,b] [ base> prime?* ] with ; inline
: <digits> ( n -- range ) [ 1 - ] keep [ 10^ ] bi@ [a,b) ;
: multibase ( n -- assoc )
<digits> [ (bases) count ] zip-with assoc-invert
expand-keys-push-at >alist [ first ] supremum-by ;
: multibase. ( n -- )
dup multibase first2
[ "%d-digit numbers that are prime in the most bases: %d\n" printf ] dip
[ dup (bases) filter "%d => %[%d, %]\n" printf ] each ;
4 [1,b] [ multibase. nl ] each
|
Translate the given Go code snippet into Factor without altering its behavior. | package main
import (
"fmt"
"math"
"rcu"
)
var limit = int(math.Log(1e6) * 1e6 * 1.2)
var primes = rcu.Primes(limit)
var prevCats = make(map[int]int)
func cat(p int) int {
if v, ok := prevCats[p]; ok {
return v
}
pf := rcu.PrimeFactors(p + 1)
all := true
for _, f := range pf {
if f != 2 && f != 3 {
all = false
break
}
}
if all {
return 1
}
if p > 2 {
len := len(pf)
for i := len - 1; i >= 1; i-- {
if pf[i-1] == pf[i] {
pf = append(pf[:i], pf[i+1:]...)
}
}
}
for c := 2; c <= 11; c++ {
all := true
for _, f := range pf {
if cat(f) >= c {
all = false
break
}
}
if all {
prevCats[p] = c
return c
}
}
return 12
}
func main() {
es := make([][]int, 12)
fmt.Println("First 200 primes:\n")
for _, p := range primes[0:200] {
c := cat(p)
es[c-1] = append(es[c-1], p)
}
for c := 1; c <= 6; c++ {
if len(es[c-1]) > 0 {
fmt.Println("Category", c, "\b:")
fmt.Println(es[c-1])
fmt.Println()
}
}
fmt.Println("First million primes:\n")
for _, p := range primes[200:1e6] {
c := cat(p)
es[c-1] = append(es[c-1], p)
}
for c := 1; c <= 12; c++ {
e := es[c-1]
if len(e) > 0 {
format := "Category %-2d: First = %7d Last = %8d Count = %6d\n"
fmt.Printf(format, c, e[0], e[len(e)-1], len(e))
}
}
}
| USING: assocs combinators formatting grouping grouping.extras io
kernel math math.primes math.primes.factors math.statistics
prettyprint sequences sequences.deep ;
PREDICATE: >3 < integer 3 > ;
GENERIC: depth ( seq -- n )
M: sequence depth
0 swap [ flatten1 [ 1 + ] dip ] to-fixed-point drop ;
M: integer depth drop 1 ;
MEMO: pfactors ( n -- seq ) 1 + factors ;
: category ( m -- n )
[ dup >3? [ pfactors ] when ] deep-map depth ;
: categories ( n -- assoc ) nprimes [ category ] collect-by ;
: table. ( seq n -- )
[ "" pad-groups ] keep group simple-table. ;
: categories... ( assoc -- )
[ [ "Category %d:\n" printf ] dip 15 table. ] assoc-each ;
: row. ( category first last count -- )
"Category %d: first->%d last->%d count->%d\n" printf ;
: categories. ( assoc -- )
[ [ minmax ] keep length row. ] assoc-each ;
200 categories categories... nl
1,000,000 categories categories.
|
Port the following code from Go to Factor with equivalent syntax and logic. | package main
import (
"fmt"
"math"
)
type mwriter struct {
value float64
log string
}
func (m mwriter) bind(f func(v float64) mwriter) mwriter {
n := f(m.value)
n.log = m.log + n.log
return n
}
func unit(v float64, s string) mwriter {
return mwriter{v, fmt.Sprintf(" %-17s: %g\n", s, v)}
}
func root(v float64) mwriter {
return unit(math.Sqrt(v), "Took square root")
}
func addOne(v float64) mwriter {
return unit(v+1, "Added one")
}
func half(v float64) mwriter {
return unit(v/2, "Divided by two")
}
func main() {
mw1 := unit(5, "Initial value")
mw2 := mw1.bind(root).bind(addOne).bind(half)
fmt.Println("The Golden Ratio is", mw2.value)
fmt.Println("\nThis was derived as follows:-")
fmt.Println(mw2.log)
}
| USING: kernel math math.functions monads prettyprint ;
FROM: monads => do ;
{
[ 5 "Started with five, " <writer> ]
[ sqrt "took square root, " <writer> ]
[ 1 + "added one, " <writer> ]
[ 2 / "divided by two." <writer> ]
} do .
|
Convert this Go block to Factor, preserving its control flow and logic. | package main
import (
"fmt"
"sort"
)
func fourFaceCombs() (res [][4]int) {
found := make([]bool, 256)
for i := 1; i <= 4; i++ {
for j := 1; j <= 4; j++ {
for k := 1; k <= 4; k++ {
for l := 1; l <= 4; l++ {
c := [4]int{i, j, k, l}
sort.Ints(c[:])
key := 64*(c[0]-1) + 16*(c[1]-1) + 4*(c[2]-1) + (c[3] - 1)
if !found[key] {
found[key] = true
res = append(res, c)
}
}
}
}
}
return
}
func cmp(x, y [4]int) int {
xw := 0
yw := 0
for i := 0; i < 4; i++ {
for j := 0; j < 4; j++ {
if x[i] > y[j] {
xw++
} else if y[j] > x[i] {
yw++
}
}
}
if xw < yw {
return -1
} else if xw > yw {
return 1
}
return 0
}
func findIntransitive3(cs [][4]int) (res [][3][4]int) {
var c = len(cs)
for i := 0; i < c; i++ {
for j := 0; j < c; j++ {
for k := 0; k < c; k++ {
first := cmp(cs[i], cs[j])
if first == -1 {
second := cmp(cs[j], cs[k])
if second == -1 {
third := cmp(cs[i], cs[k])
if third == 1 {
res = append(res, [3][4]int{cs[i], cs[j], cs[k]})
}
}
}
}
}
}
return
}
func findIntransitive4(cs [][4]int) (res [][4][4]int) {
c := len(cs)
for i := 0; i < c; i++ {
for j := 0; j < c; j++ {
for k := 0; k < c; k++ {
for l := 0; l < c; l++ {
first := cmp(cs[i], cs[j])
if first == -1 {
second := cmp(cs[j], cs[k])
if second == -1 {
third := cmp(cs[k], cs[l])
if third == -1 {
fourth := cmp(cs[i], cs[l])
if fourth == 1 {
res = append(res, [4][4]int{cs[i], cs[j], cs[k], cs[l]})
}
}
}
}
}
}
}
}
return
}
func main() {
combs := fourFaceCombs()
fmt.Println("Number of eligible 4-faced dice", len(combs))
it3 := findIntransitive3(combs)
fmt.Printf("\n%d ordered lists of 3 non-transitive dice found, namely:\n", len(it3))
for _, a := range it3 {
fmt.Println(a)
}
it4 := findIntransitive4(combs)
fmt.Printf("\n%d ordered lists of 4 non-transitive dice found, namely:\n", len(it4))
for _, a := range it4 {
fmt.Println(a)
}
}
| USING: grouping io kernel math math.combinatorics math.ranges
prettyprint sequences ;
: possible-dice ( n -- seq )
[ [1,b] ] [ selections ] bi [ [ <= ] monotonic? ] filter ;
: cmp ( seq seq -- n ) [ - sgn ] cartesian-map concat sum ;
: non-transitive? ( seq -- ? )
[ 2 clump [ first2 cmp neg? ] all? ]
[ [ last ] [ first ] bi cmp neg? and ] bi ;
: find-non-transitive ( #sides #dice -- seq )
[ possible-dice ] [ <k-permutations> ] bi*
[ non-transitive? ] filter ;
"Number of eligible 4-sided dice: " write
4 possible-dice length . nl
"All ordered lists of 3 non-transitive dice with 4 sides:" print
4 3 find-non-transitive . nl
"All ordered lists of 4 non-transitive dice with 4 sides:" print
4 4 find-non-transitive .
|
Change the following Go code into Factor without altering its purpose. | package main
import (
"fmt"
"math/rand"
"strconv"
"strings"
"time"
)
func factorial(n int) int {
fact := 1
for i := 2; i <= n; i++ {
fact *= i
}
return fact
}
func genFactBaseNums(size int, countOnly bool) ([][]int, int) {
var results [][]int
count := 0
for n := 0; ; n++ {
radix := 2
var res []int = nil
if !countOnly {
res = make([]int, size)
}
k := n
for k > 0 {
div := k / radix
rem := k % radix
if !countOnly {
if radix <= size+1 {
res[size-radix+1] = rem
}
}
k = div
radix++
}
if radix > size+2 {
break
}
count++
if !countOnly {
results = append(results, res)
}
}
return results, count
}
func mapToPerms(factNums [][]int) [][]int {
var perms [][]int
psize := len(factNums[0]) + 1
start := make([]int, psize)
for i := 0; i < psize; i++ {
start[i] = i
}
for _, fn := range factNums {
perm := make([]int, psize)
copy(perm, start)
for m := 0; m < len(fn); m++ {
g := fn[m]
if g == 0 {
continue
}
first := m
last := m + g
for i := 1; i <= g; i++ {
temp := perm[first]
for j := first + 1; j <= last; j++ {
perm[j-1] = perm[j]
}
perm[last] = temp
}
}
perms = append(perms, perm)
}
return perms
}
func join(is []int, sep string) string {
ss := make([]string, len(is))
for i := 0; i < len(is); i++ {
ss[i] = strconv.Itoa(is[i])
}
return strings.Join(ss, sep)
}
func undot(s string) []int {
ss := strings.Split(s, ".")
is := make([]int, len(ss))
for i := 0; i < len(ss); i++ {
is[i], _ = strconv.Atoi(ss[i])
}
return is
}
func main() {
rand.Seed(time.Now().UnixNano())
factNums, _ := genFactBaseNums(3, false)
perms := mapToPerms(factNums)
for i, fn := range factNums {
fmt.Printf("%v -> %v\n", join(fn, "."), join(perms[i], ""))
}
_, count := genFactBaseNums(10, true)
fmt.Println("\nPermutations generated =", count)
fmt.Println("compared to 11! which =", factorial(11))
fmt.Println()
fbn51s := []string{
"39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0",
"51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1",
}
factNums = [][]int{undot(fbn51s[0]), undot(fbn51s[1])}
perms = mapToPerms(factNums)
shoe := []rune("A♠K♠Q♠J♠T♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥T♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦T♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣T♣9♣8♣7♣6♣5♣4♣3♣2♣")
cards := make([]string, 52)
for i := 0; i < 52; i++ {
cards[i] = string(shoe[2*i : 2*i+2])
if cards[i][0] == 'T' {
cards[i] = "10" + cards[i][1:]
}
}
for i, fbn51 := range fbn51s {
fmt.Println(fbn51)
for _, d := range perms[i] {
fmt.Print(cards[d])
}
fmt.Println("\n")
}
fbn51 := make([]int, 51)
for i := 0; i < 51; i++ {
fbn51[i] = rand.Intn(52 - i)
}
fmt.Println(join(fbn51, "."))
perms = mapToPerms([][]int{fbn51})
for _, d := range perms[0] {
fmt.Print(cards[d])
}
fmt.Println()
}
| USING: assocs io kernel literals math math.factorials
math.parser math.ranges prettyprint qw random sequences
splitting ;
RENAME: factoradic math.combinatorics.private => _factoradic
RENAME: rotate sequences.extras => _rotate
IN: rosetta-code.factorial-permutations
CONSTANT: shoe $[
qw{ A K Q J 10 9 8 7 6 5 4 3 2 } qw{ ♠ ♥ ♦ ♣ }
[ append ] cartesian-map flip concat
]
: factoradic ( n -- seq )
_factoradic dup [ drop but-last ] unless-empty ;
: string>factoradic ( str -- seq )
"." split [ string>number ] map ;
: (rotate) ( from to seq -- newseq )
[ 1 + ] dip [ snip ] [ subseq ] 3bi -1 _rotate glue ;
: rotate ( from to seq -- newseq )
2over = [ 2nip ] [ (rotate) ] if ;
: fpermute ( factoradic -- permutation )
dup length 1 + <iota> swap <enumerated>
[ over + rot rotate ] assoc-each ;
: findex ( factoradic seq -- permutation )
[ fpermute ] [ nths concat ] bi* ;
: .f ( seq -- ) [ "." write ] [ pprint ] interleave ;
: .p ( seq -- ) [ pprint ] each nl ;
: show-table ( -- )
"Generate table" print 24
[ factoradic 3 0 pad-head dup .f fpermute " -> " write .p ]
each-integer nl ;
: show-shuffles ( -- )
"Generate given task shuffles" print
"Original deck:" print shoe concat print nl
"39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0"
"51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1"
[ [ print ] [ string>factoradic shoe findex print nl ] bi ] bi@ ;
: show-random-shuffle ( -- )
"Random shuffle:" print
51 52 [ n
: main ( -- ) show-table show-shuffles show-random-shuffle ;
MAIN: main
|
Change the programming language of this snippet from Go to Factor without modifying what it does. | package main
import (
"fmt"
"strings"
)
type Location struct{ lat, lng float64 }
func (loc Location) String() string { return fmt.Sprintf("[%f, %f]", loc.lat, loc.lng) }
type Range struct{ lower, upper float64 }
var gBase32 = "0123456789bcdefghjkmnpqrstuvwxyz"
func encodeGeohash(loc Location, prec int) string {
latRange := Range{-90, 90}
lngRange := Range{-180, 180}
var hash strings.Builder
hashVal := 0
bits := 0
even := true
for hash.Len() < prec {
val := loc.lat
rng := latRange
if even {
val = loc.lng
rng = lngRange
}
mid := (rng.lower + rng.upper) / 2
if val > mid {
hashVal = (hashVal << 1) + 1
rng = Range{mid, rng.upper}
if even {
lngRange = Range{mid, lngRange.upper}
} else {
latRange = Range{mid, latRange.upper}
}
} else {
hashVal <<= 1
if even {
lngRange = Range{lngRange.lower, mid}
} else {
latRange = Range{latRange.lower, mid}
}
}
even = !even
if bits < 4 {
bits++
} else {
bits = 0
hash.WriteByte(gBase32[hashVal])
hashVal = 0
}
}
return hash.String()
}
func main() {
locs := []Location{
{51.433718, -0.214126},
{51.433718, -0.214126},
{57.64911, 10.40744},
}
precs := []int{2, 9, 11}
for i, loc := range locs {
geohash := encodeGeohash(loc, precs[i])
fmt.Printf("geohash for %v, precision %-2d = %s\n", loc, precs[i], geohash)
}
}
| USING: formatting generalizations geohash io kernel sequences ;
: encode-geohash ( latitude longitude precision -- str )
[ >geohash ] [ head ] bi* ;
51.433718 -0.214126 2
51.433718 -0.214126 9
57.649110 10.407440 11
[
3dup encode-geohash
"geohash for [%f, %f], precision %2d = %s\n" printf
] 3 3 mnapply nl
"u4pruydqqvj" dup geohash>
"coordinates for %s ~= [%f, %f]\n" printf
|
Change the programming language of this snippet from Go to Factor without modifying what it does. | package main
import (
"fmt"
"math/big"
"strconv"
"strings"
)
func main() {
var res []int64
for n := 0; n <= 50; n++ {
ns := strconv.Itoa(n)
k := int64(1)
for {
bk := big.NewInt(k)
s := bk.Exp(bk, bk, nil).String()
if strings.Contains(s, ns) {
res = append(res, k)
break
}
k++
}
}
fmt.Println("The smallest positive integers K where K ^ K contains N (0..50) are:")
for i, n := range res {
fmt.Printf("%2d ", n)
if (i+1)%17 == 0 {
fmt.Println()
}
}
}
| USING: formatting grouping io kernel lists lists.lazy
math.functions present sequences ;
: smallest ( m -- n )
present 1 lfrom [ dup ^ present subseq? ] with lfilter car ;
51 <iota> [ smallest ] map 10 group
[ [ "%3d" printf ] each nl ] each
|
Generate an equivalent Factor version of this Go code. | package main
import (
"fmt"
"strings"
)
func derivative(p []int) []int {
if len(p) == 1 {
return []int{0}
}
d := make([]int, len(p)-1)
copy(d, p[1:])
for i := 0; i < len(d); i++ {
d[i] = p[i+1] * (i + 1)
}
return d
}
var ss = []string{"", "", "\u00b2", "\u00b3", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079"}
func superscript(n int) string {
if n < 10 {
return ss[n]
}
if n < 20 {
return ss[1] + ss[n-10]
}
return ss[2] + ss[0]
}
func abs(n int) int {
if n < 0 {
return -n
}
return n
}
func polyPrint(p []int) string {
if len(p) == 1 {
return fmt.Sprintf("%d", p[0])
}
var terms []string
for i := 0; i < len(p); i++ {
if p[i] == 0 {
continue
}
c := fmt.Sprintf("%d", p[i])
if i > 0 && abs(p[i]) == 1 {
c = ""
if p[i] != 1 {
c = "-"
}
}
x := "x"
if i <= 0 {
x = ""
}
terms = append(terms, fmt.Sprintf("%s%s%s", c, x, superscript(i)))
}
for i, j := 0, len(terms)-1; i < j; i, j = i+1, j-1 {
terms[i], terms[j] = terms[j], terms[i]
}
s := strings.Join(terms, "+")
return strings.Replace(s, "+-", "-", -1)
}
func main() {
fmt.Println("The derivatives of the following polynomials are:\n")
polys := [][]int{{5}, {4, -3}, {-1, 6, 5}, {-4, 3, -2, 1}, {1, 1, 0, -1, -1}}
for _, poly := range polys {
deriv := derivative(poly)
fmt.Printf("%v -> %v\n", poly, deriv)
}
fmt.Println("\nOr in normal mathematical notation:\n")
for _, poly := range polys {
deriv := derivative(poly)
fmt.Println("Polynomial : ", polyPrint(poly))
fmt.Println("Derivative : ", polyPrint(deriv), "\n")
}
}
| USING: generalizations kernel math.polynomials prettyprint ;
{ 5 }
{ 4 -3 }
{ -1 6 5 }
{ -4 3 -2 1 }
{ 1 1 0 -1 -1 }
[ pdiff ] 5 napply .s clear
|
Maintain the same structure and functionality when rewriting this code in Factor. | package main
import (
"fmt"
"strconv"
)
var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
func anchorDay(y int) int {
return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7
}
func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }
var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
func main() {
dates := []string{
"1800-01-06",
"1875-03-29",
"1915-12-07",
"1970-12-23",
"2043-05-14",
"2077-02-12",
"2101-04-02",
}
fmt.Println("Days of week given by Doomsday rule:")
for _, date := range dates {
y, _ := strconv.Atoi(date[0:4])
m, _ := strconv.Atoi(date[5:7])
m--
d, _ := strconv.Atoi(date[8:10])
a := anchorDay(y)
f := firstDaysCommon[m]
if isLeapYear(y) {
f = firstDaysLeap[m]
}
w := d - f
if w < 0 {
w = 7 + w
}
dow := (a + w) % 7
fmt.Printf("%s -> %s\n", date, days[dow])
}
}
| USING: accessors calendar calendar.english formatting
generalizations kernel math math.order math.vectors sequences ;
: check-year ( year -- )
1582 9999 between?
[ "Year must be between 1582 and 9999." throw ] unless ;
: doomsday ( year -- n )
{ 4 100 400 } [ mod ] with map { 5 4 6 } vdot 2 + 7 mod ;
: anchorday ( year month -- m )
1 - swap leap-year? { 4 1 } { 3 7 } ?
{ 7 4 2 6 4 1 5 3 7 5 } append nth ;
: weekday ( date -- str )
[ year>> dup check-year doomsday ] [ day>> + ]
[ dup year>> swap month>> anchorday - 7 + 7 mod ] tri
day-names nth ;
: test ( date -- )
[ "%B %d, %Y" strftime ]
[ now before? "was" "will be" ? ]
[ weekday ] tri
"%s %s on a %s.\n" printf ;
1800 1 6
1875 3 29
1915 12 7
1970 12 23
2043 5 14
2077 2 12
2101 4 2
[ <date> test ] 3 7 mnapply
|
Keep all operations the same but rewrite the snippet in Factor. | package main
import (
"fmt"
"strconv"
)
var days = []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
func anchorDay(y int) int {
return (2 + 5*(y%4) + 4*(y%100) + 6*(y%400)) % 7
}
func isLeapYear(y int) bool { return y%4 == 0 && (y%100 != 0 || y%400 == 0) }
var firstDaysCommon = []int{3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
var firstDaysLeap = []int{4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5}
func main() {
dates := []string{
"1800-01-06",
"1875-03-29",
"1915-12-07",
"1970-12-23",
"2043-05-14",
"2077-02-12",
"2101-04-02",
}
fmt.Println("Days of week given by Doomsday rule:")
for _, date := range dates {
y, _ := strconv.Atoi(date[0:4])
m, _ := strconv.Atoi(date[5:7])
m--
d, _ := strconv.Atoi(date[8:10])
a := anchorDay(y)
f := firstDaysCommon[m]
if isLeapYear(y) {
f = firstDaysLeap[m]
}
w := d - f
if w < 0 {
w = 7 + w
}
dow := (a + w) % 7
fmt.Printf("%s -> %s\n", date, days[dow])
}
}
| USING: accessors calendar calendar.english formatting
generalizations kernel math math.order math.vectors sequences ;
: check-year ( year -- )
1582 9999 between?
[ "Year must be between 1582 and 9999." throw ] unless ;
: doomsday ( year -- n )
{ 4 100 400 } [ mod ] with map { 5 4 6 } vdot 2 + 7 mod ;
: anchorday ( year month -- m )
1 - swap leap-year? { 4 1 } { 3 7 } ?
{ 7 4 2 6 4 1 5 3 7 5 } append nth ;
: weekday ( date -- str )
[ year>> dup check-year doomsday ] [ day>> + ]
[ dup year>> swap month>> anchorday - 7 + 7 mod ] tri
day-names nth ;
: test ( date -- )
[ "%B %d, %Y" strftime ]
[ now before? "was" "will be" ? ]
[ weekday ] tri
"%s %s on a %s.\n" printf ;
1800 1 6
1875 3 29
1915 12 7
1970 12 23
2043 5 14
2077 2 12
2101 4 2
[ <date> test ] 3 7 mnapply
|
Port the provided Go code into Factor while preserving the original functionality. | package main
import "fmt"
type vector = []float64
type matrix []vector
func (m matrix) inverse() matrix {
le := len(m)
for _, v := range m {
if len(v) != le {
panic("Not a square matrix")
}
}
aug := make(matrix, le)
for i := 0; i < le; i++ {
aug[i] = make(vector, 2*le)
copy(aug[i], m[i])
aug[i][i+le] = 1
}
aug.toReducedRowEchelonForm()
inv := make(matrix, le)
for i := 0; i < le; i++ {
inv[i] = make(vector, le)
copy(inv[i], aug[i][le:])
}
return inv
}
func (m matrix) toReducedRowEchelonForm() {
lead := 0
rowCount, colCount := len(m), len(m[0])
for r := 0; r < rowCount; r++ {
if colCount <= lead {
return
}
i := r
for m[i][lead] == 0 {
i++
if rowCount == i {
i = r
lead++
if colCount == lead {
return
}
}
}
m[i], m[r] = m[r], m[i]
if div := m[r][lead]; div != 0 {
for j := 0; j < colCount; j++ {
m[r][j] /= div
}
}
for k := 0; k < rowCount; k++ {
if k != r {
mult := m[k][lead]
for j := 0; j < colCount; j++ {
m[k][j] -= m[r][j] * mult
}
}
}
lead++
}
}
func (m matrix) print(title string) {
fmt.Println(title)
for _, v := range m {
fmt.Printf("% f\n", v)
}
fmt.Println()
}
func main() {
a := matrix{{1, 2, 3}, {4, 1, 6}, {7, 8, 9}}
a.inverse().print("Inverse of A is:\n")
b := matrix{{2, -1, 0}, {-1, 2, -1}, {0, -1, 2}}
b.inverse().print("Inverse of B is:\n")
}
| USING: kernel math.matrices math.matrices.elimination
prettyprint sequences ;
: augment-identity ( matrix -- new-matrix )
dup first length <identity-matrix>
[ flip ] bi@ append flip ;
: gauss-jordan-invert ( matrix -- inverted )
dup square-matrix? [ "Matrix must be square." throw ] unless
augment-identity solution
flip halves nip flip ;
{
{ -1 -2 3 2 }
{ -4 -1 6 2 }
{ 7 -8 9 1 }
{ 1 -2 1 3 }
} gauss-jordan-invert simple-table.
|
Transform the following Go implementation into Factor, maintaining the same output and logic. | package main
import "fmt"
type vector = []float64
type matrix []vector
func (m matrix) inverse() matrix {
le := len(m)
for _, v := range m {
if len(v) != le {
panic("Not a square matrix")
}
}
aug := make(matrix, le)
for i := 0; i < le; i++ {
aug[i] = make(vector, 2*le)
copy(aug[i], m[i])
aug[i][i+le] = 1
}
aug.toReducedRowEchelonForm()
inv := make(matrix, le)
for i := 0; i < le; i++ {
inv[i] = make(vector, le)
copy(inv[i], aug[i][le:])
}
return inv
}
func (m matrix) toReducedRowEchelonForm() {
lead := 0
rowCount, colCount := len(m), len(m[0])
for r := 0; r < rowCount; r++ {
if colCount <= lead {
return
}
i := r
for m[i][lead] == 0 {
i++
if rowCount == i {
i = r
lead++
if colCount == lead {
return
}
}
}
m[i], m[r] = m[r], m[i]
if div := m[r][lead]; div != 0 {
for j := 0; j < colCount; j++ {
m[r][j] /= div
}
}
for k := 0; k < rowCount; k++ {
if k != r {
mult := m[k][lead]
for j := 0; j < colCount; j++ {
m[k][j] -= m[r][j] * mult
}
}
}
lead++
}
}
func (m matrix) print(title string) {
fmt.Println(title)
for _, v := range m {
fmt.Printf("% f\n", v)
}
fmt.Println()
}
func main() {
a := matrix{{1, 2, 3}, {4, 1, 6}, {7, 8, 9}}
a.inverse().print("Inverse of A is:\n")
b := matrix{{2, -1, 0}, {-1, 2, -1}, {0, -1, 2}}
b.inverse().print("Inverse of B is:\n")
}
| USING: kernel math.matrices math.matrices.elimination
prettyprint sequences ;
: augment-identity ( matrix -- new-matrix )
dup first length <identity-matrix>
[ flip ] bi@ append flip ;
: gauss-jordan-invert ( matrix -- inverted )
dup square-matrix? [ "Matrix must be square." throw ] unless
augment-identity solution
flip halves nip flip ;
{
{ -1 -2 3 2 }
{ -4 -1 6 2 }
{ 7 -8 9 1 }
{ 1 -2 1 3 }
} gauss-jordan-invert simple-table.
|
Maintain the same structure and functionality when rewriting this code in Factor. | package main
import (
"fmt"
"math"
)
type F = func(float64) float64
func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {
m = (a + b) / 2
fm = f(m)
simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)
return
}
func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {
lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)
rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)
delta := left + right - whole
if math.Abs(delta) <= eps*15 {
return left + right + delta/15
}
return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +
quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)
}
func quadAsr(f F, a, b, eps float64) float64 {
fa, fb := f(a), f(b)
m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)
return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)
}
func main() {
a, b := 0.0, 1.0
sinx := quadAsr(math.Sin, a, b, 1e-09)
fmt.Printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx)
}
| USING: formatting kernel locals math math.functions math.ranges
sequences ;
IN: rosetta-code.simpsons
:: simps ( f a b n -- x )
n even?
[ n "n must be even; %d was given" sprintf throw ] unless
b a - n / :> h
1 n 2 <range> 2 n 1 - 2 <range>
[ [ a + h * f call ] map-sum ] bi@ [ 4 ] [ 2 ] bi*
[ * ] 2bi@ a b [ f call ] bi@ + + + h 3 / * ; inline
[ sin ] 0 1 100 simps
"Simpson's rule integration of sin from 0 to 1 is: %u\n" printf
|
Write the same code in Factor as shown below in Go. | package main
import (
"fmt"
"math"
)
type F = func(float64) float64
func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {
m = (a + b) / 2
fm = f(m)
simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)
return
}
func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {
lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)
rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)
delta := left + right - whole
if math.Abs(delta) <= eps*15 {
return left + right + delta/15
}
return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +
quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)
}
func quadAsr(f F, a, b, eps float64) float64 {
fa, fb := f(a), f(b)
m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)
return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)
}
func main() {
a, b := 0.0, 1.0
sinx := quadAsr(math.Sin, a, b, 1e-09)
fmt.Printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx)
}
| USING: formatting kernel locals math math.functions math.ranges
sequences ;
IN: rosetta-code.simpsons
:: simps ( f a b n -- x )
n even?
[ n "n must be even; %d was given" sprintf throw ] unless
b a - n / :> h
1 n 2 <range> 2 n 1 - 2 <range>
[ [ a + h * f call ] map-sum ] bi@ [ 4 ] [ 2 ] bi*
[ * ] 2bi@ a b [ f call ] bi@ + + + h 3 / * ; inline
[ sin ] 0 1 100 simps
"Simpson's rule integration of sin from 0 to 1 is: %u\n" printf
|
Can you help me rewrite this code in Factor instead of Go, keeping it the same logically? | package main
import (
"fmt"
"rcu"
"strconv"
)
func isColorful(n int) bool {
if n < 0 {
return false
}
if n < 10 {
return true
}
digits := rcu.Digits(n, 10)
for _, d := range digits {
if d == 0 || d == 1 {
return false
}
}
set := make(map[int]bool)
for _, d := range digits {
set[d] = true
}
dc := len(digits)
if len(set) < dc {
return false
}
for k := 2; k <= dc; k++ {
for i := 0; i <= dc-k; i++ {
prod := 1
for j := i; j <= i+k-1; j++ {
prod *= digits[j]
}
if ok := set[prod]; ok {
return false
}
set[prod] = true
}
}
return true
}
var count = make([]int, 9)
var used = make([]bool, 11)
var largest = 0
func countColorful(taken int, n string) {
if taken == 0 {
for digit := 0; digit < 10; digit++ {
dx := digit + 1
used[dx] = true
t := 1
if digit < 2 {
t = 9
}
countColorful(t, string(digit+48))
used[dx] = false
}
} else {
nn, _ := strconv.Atoi(n)
if isColorful(nn) {
ln := len(n)
count[ln]++
if nn > largest {
largest = nn
}
}
if taken < 9 {
for digit := 2; digit < 10; digit++ {
dx := digit + 1
if !used[dx] {
used[dx] = true
countColorful(taken+1, n+string(digit+48))
used[dx] = false
}
}
}
}
}
func main() {
var cn []int
for i := 0; i < 100; i++ {
if isColorful(i) {
cn = append(cn, i)
}
}
fmt.Println("The", len(cn), "colorful numbers less than 100 are:")
for i := 0; i < len(cn); i++ {
fmt.Printf("%2d ", cn[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
countColorful(0, "")
fmt.Println("\n\nThe largest possible colorful number is:")
fmt.Println(rcu.Commatize(largest))
fmt.Println("\nCount of colorful numbers for each order of magnitude:")
pow := 10
for dc := 1; dc < len(count); dc++ {
cdc := rcu.Commatize(count[dc])
pc := 100 * float64(count[dc]) / float64(pow)
fmt.Printf(" %d digit colorful number count: %6s - %7.3f%%\n", dc, cdc, pc)
if pow == 10 {
pow = 90
} else {
pow *= 10
}
}
sum := 0
for _, c := range count {
sum += c
}
fmt.Printf("\nTotal colorful numbers: %s\n", rcu.Commatize(sum))
}
| USING: assocs grouping grouping.extras io kernel literals math
math.combinatorics math.ranges prettyprint project-euler.common
sequences sequences.extras sets ;
CONSTANT: digits $[ 2 9 [a..b] ]
: (colorful?) ( seq -- ? )
all-subseqs [ product ] map all-unique? ;
: colorful? ( n -- ? )
[ t ] [ number>digits (colorful?) ] if-zero ;
: table. ( seq cols -- )
[ "" pad-groups ] keep group simple-table. ;
: (oom-count) ( n -- count )
digits swap <k-permutations> [ (colorful?) ] count ;
: oom-count ( n -- count )
dup 1 = [ drop 10 ] [ (oom-count) ] if ;
"Colorful numbers under 100:" print
100 <iota> [ colorful? ] filter 10 table. nl
"Largest colorful number:" print
digits <permutations> [ (colorful?) ] find-last nip digits>number . nl
"Count of colorful numbers by number of digits:" print
8 [1..b] [ oom-count ] zip-with dup .
"Total: " write values sum .
|
Convert this Go snippet to Factor and keep its semantics consistent. | package main
import (
"fmt"
"rcu"
"strconv"
)
func isColorful(n int) bool {
if n < 0 {
return false
}
if n < 10 {
return true
}
digits := rcu.Digits(n, 10)
for _, d := range digits {
if d == 0 || d == 1 {
return false
}
}
set := make(map[int]bool)
for _, d := range digits {
set[d] = true
}
dc := len(digits)
if len(set) < dc {
return false
}
for k := 2; k <= dc; k++ {
for i := 0; i <= dc-k; i++ {
prod := 1
for j := i; j <= i+k-1; j++ {
prod *= digits[j]
}
if ok := set[prod]; ok {
return false
}
set[prod] = true
}
}
return true
}
var count = make([]int, 9)
var used = make([]bool, 11)
var largest = 0
func countColorful(taken int, n string) {
if taken == 0 {
for digit := 0; digit < 10; digit++ {
dx := digit + 1
used[dx] = true
t := 1
if digit < 2 {
t = 9
}
countColorful(t, string(digit+48))
used[dx] = false
}
} else {
nn, _ := strconv.Atoi(n)
if isColorful(nn) {
ln := len(n)
count[ln]++
if nn > largest {
largest = nn
}
}
if taken < 9 {
for digit := 2; digit < 10; digit++ {
dx := digit + 1
if !used[dx] {
used[dx] = true
countColorful(taken+1, n+string(digit+48))
used[dx] = false
}
}
}
}
}
func main() {
var cn []int
for i := 0; i < 100; i++ {
if isColorful(i) {
cn = append(cn, i)
}
}
fmt.Println("The", len(cn), "colorful numbers less than 100 are:")
for i := 0; i < len(cn); i++ {
fmt.Printf("%2d ", cn[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
countColorful(0, "")
fmt.Println("\n\nThe largest possible colorful number is:")
fmt.Println(rcu.Commatize(largest))
fmt.Println("\nCount of colorful numbers for each order of magnitude:")
pow := 10
for dc := 1; dc < len(count); dc++ {
cdc := rcu.Commatize(count[dc])
pc := 100 * float64(count[dc]) / float64(pow)
fmt.Printf(" %d digit colorful number count: %6s - %7.3f%%\n", dc, cdc, pc)
if pow == 10 {
pow = 90
} else {
pow *= 10
}
}
sum := 0
for _, c := range count {
sum += c
}
fmt.Printf("\nTotal colorful numbers: %s\n", rcu.Commatize(sum))
}
| USING: assocs grouping grouping.extras io kernel literals math
math.combinatorics math.ranges prettyprint project-euler.common
sequences sequences.extras sets ;
CONSTANT: digits $[ 2 9 [a..b] ]
: (colorful?) ( seq -- ? )
all-subseqs [ product ] map all-unique? ;
: colorful? ( n -- ? )
[ t ] [ number>digits (colorful?) ] if-zero ;
: table. ( seq cols -- )
[ "" pad-groups ] keep group simple-table. ;
: (oom-count) ( n -- count )
digits swap <k-permutations> [ (colorful?) ] count ;
: oom-count ( n -- count )
dup 1 = [ drop 10 ] [ (oom-count) ] if ;
"Colorful numbers under 100:" print
100 <iota> [ colorful? ] filter 10 table. nl
"Largest colorful number:" print
digits <permutations> [ (colorful?) ] find-last nip digits>number . nl
"Count of colorful numbers by number of digits:" print
8 [1..b] [ oom-count ] zip-with dup .
"Total: " write values sum .
|
Convert this Go snippet to Factor and keep its semantics consistent. | package main
import (
"fmt"
"math/rand"
"strconv"
"strings"
"time"
)
var grid [8][8]byte
func abs(i int) int {
if i >= 0 {
return i
} else {
return -i
}
}
func createFen() string {
placeKings()
placePieces("PPPPPPPP", true)
placePieces("pppppppp", true)
placePieces("RNBQBNR", false)
placePieces("rnbqbnr", false)
return toFen()
}
func placeKings() {
for {
r1 := rand.Intn(8)
c1 := rand.Intn(8)
r2 := rand.Intn(8)
c2 := rand.Intn(8)
if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 {
grid[r1][c1] = 'K'
grid[r2][c2] = 'k'
return
}
}
}
func placePieces(pieces string, isPawn bool) {
numToPlace := rand.Intn(len(pieces))
for n := 0; n < numToPlace; n++ {
var r, c int
for {
r = rand.Intn(8)
c = rand.Intn(8)
if grid[r][c] == '\000' && !(isPawn && (r == 7 || r == 0)) {
break
}
}
grid[r][c] = pieces[n]
}
}
func toFen() string {
var fen strings.Builder
countEmpty := 0
for r := 0; r < 8; r++ {
for c := 0; c < 8; c++ {
ch := grid[r][c]
if ch == '\000' {
ch = '.'
}
fmt.Printf("%2c ", ch)
if ch == '.' {
countEmpty++
} else {
if countEmpty > 0 {
fen.WriteString(strconv.Itoa(countEmpty))
countEmpty = 0
}
fen.WriteByte(ch)
}
}
if countEmpty > 0 {
fen.WriteString(strconv.Itoa(countEmpty))
countEmpty = 0
}
fen.WriteString("/")
fmt.Println()
}
fen.WriteString(" w - - 0 1")
return fen.String()
}
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println(createFen())
}
| USING: combinators.short-circuit grouping io kernel math
math.parser math.ranges math.vectors prettyprint random
sequences sets splitting.monotonic strings ;
IN: rosetta-code.random-chess-position
<PRIVATE
CONSTANT: pieces "RNBQBNRPPPPPPPPrnbqbnrpppppppp"
CONSTANT: empty CHAR: .
: <empty-board> ( -- seq ) 64 [ empty ] "" replicate-as ;
: empty-index ( seq -- n ) empty swap indices random ;
: place ( seq elt n -- seq' ) rot [ set-nth ] keep ;
: adj ( n -- seq )
[ 1 - ] [ 1 + ] bi [a,b] { 8 8 8 } [ v- ] 2keep dupd v+
append append ;
: rand-non-adjacent ( m -- n ) 64 <iota> swap adj diff random ;
: place-kings ( seq -- seq' )
CHAR: K over empty-index [ place ] keep [ CHAR: k ] dip
rand-non-adjacent place ;
: non-pawn ( seq elt -- seq' ) over empty-index place ;
: pawn ( seq elt -- seq' )
over empty swap indices
[ { [ 7 > ] [ 56 < ] } 1&& ] filter random place ;
: place-piece ( seq -- seq' )
pieces random dup "Pp" member? [ pawn ] [ non-pawn ] if ;
PRIVATE>
: position ( -- seq )
<empty-board> place-kings 30 random [ place-piece ] times ;
: position. ( seq -- )
[ 1string ] { } map-as 8 group simple-table. ;
: position>fen ( seq -- seq' )
8 group [
[ = ] monotonic-split
[ dup first empty = [ length number>string ] when ]
map concat
] map "/" join "/ w - - 0 1" append ;
: random-chess-position-demo ( -- )
position [ position. ] [ position>fen print ] bi ;
MAIN: random-chess-position-demo
|
Produce a language-to-language conversion: from Go to Factor, same semantics. | package main
import (
"fmt"
"math"
"rcu"
)
func divisorCount(n int) int {
k := 1
if n%2 == 1 {
k = 2
}
count := 0
sqrt := int(math.Sqrt(float64(n)))
for i := 1; i <= sqrt; i += k {
if n%i == 0 {
count++
j := n / i
if j != i {
count++
}
}
}
return count
}
func main() {
var numbers50 []int
count := 0
for n := 1; count < 50000; n++ {
dc := divisorCount(n)
if n == 1 || dc == 8 {
count++
if count <= 50 {
numbers50 = append(numbers50, n)
if count == 50 {
rcu.PrintTable(numbers50, 10, 3, false)
}
} else if count == 500 {
fmt.Printf("\n500th : %s", rcu.Commatize(n))
} else if count == 5000 {
fmt.Printf("\n5,000th : %s", rcu.Commatize(n))
} else if count == 50000 {
fmt.Printf("\n50,000th: %s\n", rcu.Commatize(n))
}
}
}
}
| USING: formatting grouping io kernel lists lists.lazy math
prettyprint project-euler.common ;
: A111398 ( -- list )
L{ 1 } 2 lfrom [ tau 8 = ] lfilter lappend-lazy ;
50 A111398 ltake list>array 10 group simple-table. nl
499 4999 49999
[ [ 1 + ] keep A111398 lnth "%5dth: %d\n" printf ] tri@
|
Transform the following Go implementation into Factor, maintaining the same output and logic. | package main
import (
"fmt"
"rcu"
)
func D(n float64) float64 {
if n < 0 {
return -D(-n)
}
if n < 2 {
return 0
}
var f []int
if n < 1e19 {
f = rcu.PrimeFactors(int(n))
} else {
g := int(n / 100)
f = rcu.PrimeFactors(g)
f = append(f, []int{2, 2, 5, 5}...)
}
c := len(f)
if c == 1 {
return 1
}
if c == 2 {
return float64(f[0] + f[1])
}
d := n / float64(f[0])
return D(d)*float64(f[0]) + d
}
func main() {
ad := make([]int, 200)
for n := -99; n < 101; n++ {
ad[n+99] = int(D(float64(n)))
}
rcu.PrintTable(ad, 10, 4, false)
fmt.Println()
pow := 1.0
for m := 1; m < 21; m++ {
pow *= 10
fmt.Printf("D(10^%-2d) / 7 = %.0f\n", m, D(pow)/7)
}
}
| USING: combinators formatting grouping io kernel math
math.primes.factors prettyprint ranges sequences ;
: n' ( m -- n )
{
{ [ dup neg? ] [ neg n' neg ] }
{ [ dup 2 < ] [ drop 0 ] }
{ [ factors dup length 1 = ] [ drop 1 ] }
[ unclip-slice swap product 2dup n' * spin n' * + ]
} cond ;
-99 100 [a..b] [ n' ] map 10 group
[ [ "%5d" printf ] each nl ] each
|
Ensure the translated Factor code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"rcu"
)
func main() {
prods := make([]int, 100)
prods[0] = 1
for i := 2; i <= 100; i++ {
factors := rcu.PrimeFactors(i)
prods[i-1] = factors[0] * factors[len(factors)-1]
}
fmt.Println("Product of smallest and greatest prime factors of n for 1 to 100:")
rcu.PrintTable(prods, 10, 4, false)
}
| USING: grouping math math.primes.factors math.statistics
prettyprint ranges sequences ;
2 100 [a..b] [ factors minmax * ] map 1 prefix 10 group simple-table.
|
Keep all operations the same but rewrite the snippet in Factor. | package main
import (
"fmt"
"math/big"
)
func sf(n int) *big.Int {
if n < 2 {
return big.NewInt(1)
}
sfact := big.NewInt(1)
fact := big.NewInt(1)
for i := 2; i <= n; i++ {
fact.Mul(fact, big.NewInt(int64(i)))
sfact.Mul(sfact, fact)
}
return sfact
}
func H(n int) *big.Int {
if n < 2 {
return big.NewInt(1)
}
hfact := big.NewInt(1)
for i := 2; i <= n; i++ {
bi := big.NewInt(int64(i))
hfact.Mul(hfact, bi.Exp(bi, bi, nil))
}
return hfact
}
func af(n int) *big.Int {
if n < 1 {
return new(big.Int)
}
afact := new(big.Int)
fact := big.NewInt(1)
sign := new(big.Int)
if n%2 == 0 {
sign.SetInt64(-1)
} else {
sign.SetInt64(1)
}
t := new(big.Int)
for i := 1; i <= n; i++ {
fact.Mul(fact, big.NewInt(int64(i)))
afact.Add(afact, t.Mul(fact, sign))
sign.Neg(sign)
}
return afact
}
func ef(n int) *big.Int {
if n < 1 {
return big.NewInt(1)
}
t := big.NewInt(int64(n))
return t.Exp(t, ef(n-1), nil)
}
func rf(n *big.Int) int {
i := 0
fact := big.NewInt(1)
for {
if fact.Cmp(n) == 0 {
return i
}
if fact.Cmp(n) > 0 {
return -1
}
i++
fact.Mul(fact, big.NewInt(int64(i)))
}
}
func main() {
fmt.Println("First 10 superfactorials:")
for i := 0; i < 10; i++ {
fmt.Println(sf(i))
}
fmt.Println("\nFirst 10 hyperfactorials:")
for i := 0; i < 10; i++ {
fmt.Println(H(i))
}
fmt.Println("\nFirst 10 alternating factorials:")
for i := 0; i < 10; i++ {
fmt.Print(af(i), " ")
}
fmt.Println("\n\nFirst 5 exponential factorials:")
for i := 0; i <= 4; i++ {
fmt.Print(ef(i), " ")
}
fmt.Println("\n\nThe number of digits in 5$ is", len(ef(5).String()))
fmt.Println("\nReverse factorials:")
facts := []int64{1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 119}
for _, fact := range facts {
bfact := big.NewInt(fact)
rfact := rf(bfact)
srfact := fmt.Sprintf("%d", rfact)
if rfact == -1 {
srfact = "none"
}
fmt.Printf("%4s <- rf(%d)\n", srfact, fact)
}
}
| USING: formatting io kernel math math.factorials math.functions
math.parser math.ranges prettyprint sequences sequences.extras ;
IN: rosetta-code.special-factorials
: sf ( n -- m ) [1..b] [ n
: (H) ( n -- m ) [1..b] [ dup ^ ] map-product ;
: H ( n -- m ) [ 1 ] [ (H) ] if-zero ;
:: af ( n -- m ) n [1..b] [| i | -1 n i - ^ i n
: $ ( n -- m ) [1..b] [ ] [ swap ^ ] map-reduce ;
: (rf) ( n -- m )
[ 1 1 ] dip [ dup reach > ]
[ [ 1 + [ * ] keep ] dip ] while swapd = swap and ;
: rf ( n -- m ) dup 1 = [ drop 0 ] [ (rf) ] if ;
: .show ( n quot -- )
[ pprint bl ] compose each-integer nl ; inline
"First 10 superfactorials:" print
10 [ sf ] .show nl
"First 10 hyperfactorials:" print
10 [ H ] .show nl
"First 10 alternating factorials:" print
10 [ af ] .show nl
"First 5 exponential factorials:" print
5 [ $ ] .show nl
"Number of digits in 5$:" print
5 $ log10 >integer 1 + . nl
{ 1 2 6 24 120 720 5040 40320 362880 3628800 119 }
[ dup rf "rf(%d) = %u\n" printf ] each nl
|
Write a version of this Go function in Factor with identical behavior. | package main
import (
"fmt"
"rcu"
)
func factorial(n int) int {
fact := 1
for i := 2; i <= n; i++ {
fact *= i
}
return fact
}
func permutations(input []int) [][]int {
perms := [][]int{input}
a := make([]int, len(input))
copy(a, input)
var n = len(input) - 1
for c := 1; c < factorial(n+1); c++ {
i := n - 1
j := n
for a[i] > a[i+1] {
i--
}
for a[j] < a[i] {
j--
}
a[i], a[j] = a[j], a[i]
j = n
i += 1
for i < j {
a[i], a[j] = a[j], a[i]
i++
j--
}
b := make([]int, len(input))
copy(b, a)
perms = append(perms, b)
}
return perms
}
func main() {
outer:
for _, start := range []int{1, 0} {
fmt.Printf("The largest pandigital decimal prime which uses all the digits %d..n once is:\n", start)
for _, n := range []int{7, 4} {
m := n + 1 - start
list := make([]int, m)
for i := 0; i < m; i++ {
list[i] = i + start
}
perms := permutations(list)
for i := len(perms) - 1; i >= 0; i-- {
le := len(perms[i])
if perms[i][le-1]%2 == 0 || perms[i][le-1] == 5 || (start == 0 && perms[i][0] == 0) {
continue
}
p := 0
pow := 1
for j := le - 1; j >= 0; j-- {
p += perms[i][j] * pow
pow *= 10
}
if rcu.IsPrime(p) {
fmt.Println(rcu.Commatize(p) + "\n")
continue outer
}
}
}
}
}
| USING: io kernel math math.combinatorics math.functions
math.primes math.ranges present sequences sequences.cords ;
{ 4 7 } [ [1,b] <permutations> ] [ cord-append ] map-reduce
[ reverse 0 [ 10^ * + ] reduce-index prime? ] find-last nip
"The largest pandigital decimal prime is: " print
[ present write ] each nl
|
Maintain the same structure and functionality when rewriting this code in Factor. | package main
import (
"fmt"
"rcu"
)
func factorial(n int) int {
fact := 1
for i := 2; i <= n; i++ {
fact *= i
}
return fact
}
func permutations(input []int) [][]int {
perms := [][]int{input}
a := make([]int, len(input))
copy(a, input)
var n = len(input) - 1
for c := 1; c < factorial(n+1); c++ {
i := n - 1
j := n
for a[i] > a[i+1] {
i--
}
for a[j] < a[i] {
j--
}
a[i], a[j] = a[j], a[i]
j = n
i += 1
for i < j {
a[i], a[j] = a[j], a[i]
i++
j--
}
b := make([]int, len(input))
copy(b, a)
perms = append(perms, b)
}
return perms
}
func main() {
outer:
for _, start := range []int{1, 0} {
fmt.Printf("The largest pandigital decimal prime which uses all the digits %d..n once is:\n", start)
for _, n := range []int{7, 4} {
m := n + 1 - start
list := make([]int, m)
for i := 0; i < m; i++ {
list[i] = i + start
}
perms := permutations(list)
for i := len(perms) - 1; i >= 0; i-- {
le := len(perms[i])
if perms[i][le-1]%2 == 0 || perms[i][le-1] == 5 || (start == 0 && perms[i][0] == 0) {
continue
}
p := 0
pow := 1
for j := le - 1; j >= 0; j-- {
p += perms[i][j] * pow
pow *= 10
}
if rcu.IsPrime(p) {
fmt.Println(rcu.Commatize(p) + "\n")
continue outer
}
}
}
}
}
| USING: io kernel math math.combinatorics math.functions
math.primes math.ranges present sequences sequences.cords ;
{ 4 7 } [ [1,b] <permutations> ] [ cord-append ] map-reduce
[ reverse 0 [ 10^ * + ] reduce-index prime? ] find-last nip
"The largest pandigital decimal prime is: " print
[ present write ] each nl
|
Convert the following code from Go to Factor, ensuring the logic remains intact. | package main
import (
"github.com/fogleman/gg"
"github.com/trubitsyn/go-lindenmayer"
"log"
"math"
)
const twoPi = 2 * math.Pi
var (
width = 770.0
height = 770.0
dc = gg.NewContext(int(width), int(height))
)
var cx, cy, h, theta float64
func main() {
dc.SetRGB(0, 0, 1)
dc.Clear()
cx, cy = 10, height/2+5
h = 6
sys := lindenmayer.Lsystem{
Variables: []rune{'X'},
Constants: []rune{'F', '+', '-'},
Axiom: "F+XF+F+XF",
Rules: []lindenmayer.Rule{
{"X", "XF-F+F-XF+F+XF-F+F-X"},
},
Angle: math.Pi / 2,
}
result := lindenmayer.Iterate(&sys, 5)
operations := map[rune]func(){
'F': func() {
newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)
dc.LineTo(newX, newY)
cx, cy = newX, newY
},
'+': func() {
theta = math.Mod(theta+sys.Angle, twoPi)
},
'-': func() {
theta = math.Mod(theta-sys.Angle, twoPi)
},
}
if err := lindenmayer.Process(result, operations); err != nil {
log.Fatal(err)
}
operations['+']()
operations['F']()
dc.SetRGB255(255, 255, 0)
dc.SetLineWidth(2)
dc.Stroke()
dc.SavePNG("sierpinski_square_curve.png")
}
| USING: accessors kernel L-system sequences ui ;
: square-curve ( L-system -- L-system )
L-parser-dialect >>commands
[ 90 >>angle ] >>turtle-values
"F+XF+F+XF" >>axiom
{
{ "X" "XF-F+F-XF+F+XF-F+F-X" }
} >>rules ;
[
<L-system> square-curve
"Sierpinski square curve" open-window
] with-ui
|
Transform the following Go implementation into Factor, maintaining the same output and logic. | package main
import (
"fmt"
"math"
"sort"
)
func totient(n int) int {
tot := n
i := 2
for i*i <= n {
if n%i == 0 {
for n%i == 0 {
n /= i
}
tot -= tot / i
}
if i == 2 {
i = 1
}
i += 2
}
if n > 1 {
tot -= tot / n
}
return tot
}
var pps = make(map[int]bool)
func getPerfectPowers(maxExp int) {
upper := math.Pow(10, float64(maxExp))
for i := 2; i <= int(math.Sqrt(upper)); i++ {
fi := float64(i)
p := fi
for {
p *= fi
if p >= upper {
break
}
pps[int(p)] = true
}
}
}
func getAchilles(minExp, maxExp int) map[int]bool {
lower := math.Pow(10, float64(minExp))
upper := math.Pow(10, float64(maxExp))
achilles := make(map[int]bool)
for b := 1; b <= int(math.Cbrt(upper)); b++ {
b3 := b * b * b
for a := 1; a <= int(math.Sqrt(upper)); a++ {
p := b3 * a * a
if p >= int(upper) {
break
}
if p >= int(lower) {
if _, ok := pps[p]; !ok {
achilles[p] = true
}
}
}
}
return achilles
}
func main() {
maxDigits := 15
getPerfectPowers(maxDigits)
achillesSet := getAchilles(1, 5)
achilles := make([]int, len(achillesSet))
i := 0
for k := range achillesSet {
achilles[i] = k
i++
}
sort.Ints(achilles)
fmt.Println("First 50 Achilles numbers:")
for i = 0; i < 50; i++ {
fmt.Printf("%4d ", achilles[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 30 strong Achilles numbers:")
var strongAchilles []int
count := 0
for n := 0; count < 30; n++ {
tot := totient(achilles[n])
if _, ok := achillesSet[tot]; ok {
strongAchilles = append(strongAchilles, achilles[n])
count++
}
}
for i = 0; i < 30; i++ {
fmt.Printf("%5d ", strongAchilles[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nNumber of Achilles numbers with:")
for d := 2; d <= maxDigits; d++ {
ac := len(getAchilles(d-1, d))
fmt.Printf("%2d digits: %d\n", d, ac)
}
}
| USING: assocs combinators.short-circuit formatting grouping io
kernel lists lists.lazy math math.functions math.primes.factors
prettyprint ranges sequences ;
: achilles? ( n -- ? )
group-factors values {
[ [ 1 > ] all? ]
[ unclip-slice [ simple-gcd ] reduce 1 = ]
} 1&& ;
: achilles ( -- list )
2 lfrom [ achilles? ] lfilter ;
: strong-achilles ( -- list )
achilles [ totient achilles? ] lfilter ;
: show ( n list -- ) ltake list>array 10 group simple-table. ;
: <order-of-magnitude> ( n -- range )
1 - 10^ dup 10 * [a..b) ;
"First 50 Achilles numbers:" print
50 achilles show nl
"First 30 strong Achilles numbers:" print
30 strong-achilles show nl
"Number of Achilles numbers with" print
{ 2 3 4 5 } [
dup <order-of-magnitude> [ achilles? ] count
"%d digits: %d\n" printf
] each
|
Produce a functionally identical Factor code for the snippet given in Go. | package main
import (
"fmt"
"math"
"sort"
)
func totient(n int) int {
tot := n
i := 2
for i*i <= n {
if n%i == 0 {
for n%i == 0 {
n /= i
}
tot -= tot / i
}
if i == 2 {
i = 1
}
i += 2
}
if n > 1 {
tot -= tot / n
}
return tot
}
var pps = make(map[int]bool)
func getPerfectPowers(maxExp int) {
upper := math.Pow(10, float64(maxExp))
for i := 2; i <= int(math.Sqrt(upper)); i++ {
fi := float64(i)
p := fi
for {
p *= fi
if p >= upper {
break
}
pps[int(p)] = true
}
}
}
func getAchilles(minExp, maxExp int) map[int]bool {
lower := math.Pow(10, float64(minExp))
upper := math.Pow(10, float64(maxExp))
achilles := make(map[int]bool)
for b := 1; b <= int(math.Cbrt(upper)); b++ {
b3 := b * b * b
for a := 1; a <= int(math.Sqrt(upper)); a++ {
p := b3 * a * a
if p >= int(upper) {
break
}
if p >= int(lower) {
if _, ok := pps[p]; !ok {
achilles[p] = true
}
}
}
}
return achilles
}
func main() {
maxDigits := 15
getPerfectPowers(maxDigits)
achillesSet := getAchilles(1, 5)
achilles := make([]int, len(achillesSet))
i := 0
for k := range achillesSet {
achilles[i] = k
i++
}
sort.Ints(achilles)
fmt.Println("First 50 Achilles numbers:")
for i = 0; i < 50; i++ {
fmt.Printf("%4d ", achilles[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nFirst 30 strong Achilles numbers:")
var strongAchilles []int
count := 0
for n := 0; count < 30; n++ {
tot := totient(achilles[n])
if _, ok := achillesSet[tot]; ok {
strongAchilles = append(strongAchilles, achilles[n])
count++
}
}
for i = 0; i < 30; i++ {
fmt.Printf("%5d ", strongAchilles[i])
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Println("\nNumber of Achilles numbers with:")
for d := 2; d <= maxDigits; d++ {
ac := len(getAchilles(d-1, d))
fmt.Printf("%2d digits: %d\n", d, ac)
}
}
| USING: assocs combinators.short-circuit formatting grouping io
kernel lists lists.lazy math math.functions math.primes.factors
prettyprint ranges sequences ;
: achilles? ( n -- ? )
group-factors values {
[ [ 1 > ] all? ]
[ unclip-slice [ simple-gcd ] reduce 1 = ]
} 1&& ;
: achilles ( -- list )
2 lfrom [ achilles? ] lfilter ;
: strong-achilles ( -- list )
achilles [ totient achilles? ] lfilter ;
: show ( n list -- ) ltake list>array 10 group simple-table. ;
: <order-of-magnitude> ( n -- range )
1 - 10^ dup 10 * [a..b) ;
"First 50 Achilles numbers:" print
50 achilles show nl
"First 30 strong Achilles numbers:" print
30 strong-achilles show nl
"Number of Achilles numbers with" print
{ 2 3 4 5 } [
dup <order-of-magnitude> [ achilles? ] count
"%d digits: %d\n" printf
] each
|
Produce a language-to-language conversion: from Go to Factor, same semantics. | package main
import (
"fmt"
"github.com/nsf/termbox-go"
"log"
"math/rand"
"strconv"
"time"
)
type coord struct{ x, y int }
const (
width = 79
height = 22
nCount = float64(width * height)
)
var (
board [width * height]int
score = 0
bold = termbox.AttrBold
cursor coord
)
var colors = [10]termbox.Attribute{
termbox.ColorDefault,
termbox.ColorWhite,
termbox.ColorBlack | bold,
termbox.ColorBlue | bold,
termbox.ColorGreen | bold,
termbox.ColorCyan | bold,
termbox.ColorRed | bold,
termbox.ColorMagenta | bold,
termbox.ColorYellow | bold,
termbox.ColorWhite | bold,
}
func printAt(x, y int, s string, fg, bg termbox.Attribute) {
for _, r := range s {
termbox.SetCell(x, y, r, fg, bg)
x++
}
}
func createBoard() {
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
board[x+width*y] = rand.Intn(9) + 1
}
}
cursor = coord{rand.Intn(width), rand.Intn(height)}
board[cursor.x+width*cursor.y] = 0
score = 0
printScore()
}
func displayBoard() {
termbox.SetCursor(0, 0)
bg := colors[0]
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
i := board[x+width*y]
fg := colors[i]
s := " "
if i > 0 {
s = strconv.Itoa(i)
}
printAt(x, y, s, fg, bg)
}
}
fg := colors[9]
termbox.SetCursor(cursor.x, cursor.y)
printAt(cursor.x, cursor.y, "@", fg, bg)
termbox.Flush()
}
func printScore() {
termbox.SetCursor(0, 24)
fg := colors[4]
bg := termbox.ColorGreen
s := fmt.Sprintf(" SCORE: %d : %.3f%% ", score, float64(score)*100.0/nCount)
printAt(0, 24, s, fg, bg)
termbox.Flush()
}
func execute(x, y int) {
i := board[cursor.x+x+width*(cursor.y+y)]
if countSteps(i, x, y) {
score += i
for i != 0 {
i--
cursor.x += x
cursor.y += y
board[cursor.x+width*cursor.y] = 0
}
}
}
func countSteps(i, x, y int) bool {
t := cursor
for i != 0 {
i--
t.x += x
t.y += y
if t.x < 0 || t.y < 0 || t.x >= width || t.y >= height || board[t.x+width*t.y] == 0 {
return false
}
}
return true
}
func existsMoves() bool {
for y := -1; y < 2; y++ {
for x := -1; x < 2; x++ {
if x == 0 && y == 0 {
continue
}
ix := cursor.x + x + width*(cursor.y+y)
i := 0
if ix >= 0 && ix < len(board) {
i = board[ix]
}
if i > 0 && countSteps(i, x, y) {
return true
}
}
}
return false
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
err := termbox.Init()
check(err)
defer termbox.Close()
eventQueue := make(chan termbox.Event)
go func() {
for {
eventQueue <- termbox.PollEvent()
}
}()
for {
termbox.HideCursor()
createBoard()
for {
displayBoard()
select {
case ev := <-eventQueue:
if ev.Type == termbox.EventKey {
switch ev.Ch {
case 'q', 'Q':
if cursor.x > 0 && cursor.y > 0 {
execute(-1, -1)
}
case 'w', 'W':
if cursor.y > 0 {
execute(0, -1)
}
case 'e', 'E':
if cursor.x < width-1 && cursor.y > 0 {
execute(1, -1)
}
case 'a', 'A':
if cursor.x > 0 {
execute(-1, 0)
}
case 'd', 'D':
if cursor.x < width-1 {
execute(1, 0)
}
case 'z', 'Z':
if cursor.x > 0 && cursor.y < height-1 {
execute(-1, 1)
}
case 'x', 'X':
if cursor.y < height-1 {
execute(0, 1)
}
case 'c', 'C':
if cursor.x < width-1 && cursor.y < height-1 {
execute(1, 1)
}
case 'l', 'L':
return
}
} else if ev.Type == termbox.EventResize {
termbox.Flush()
}
}
printScore()
if !existsMoves() {
break
}
}
displayBoard()
fg := colors[7]
bg := colors[0]
printAt(19, 8, "+----------------------------------------+", fg, bg)
printAt(19, 9, "| GAME OVER |", fg, bg)
printAt(19, 10, "| PLAY AGAIN(Y/N)? |", fg, bg)
printAt(19, 11, "+----------------------------------------+", fg, bg)
termbox.SetCursor(48, 10)
termbox.Flush()
select {
case ev := <-eventQueue:
if ev.Type == termbox.EventKey {
if ev.Ch == 'y' || ev.Ch == 'Y' {
break
} else {
return
}
}
}
}
}
| USING: accessors arrays colors combinators
combinators.short-circuit fry grouping io io.styles kernel lexer
literals make math math.matrices math.parser math.vectors random
sequences strings ui ui.commands ui.gadgets.panes
ui.gadgets.status-bar ui.gadgets.worlds ui.gestures
ui.pens.solid ;
IN: rosetta-code.greed
<<
SYNTAX: RGB: scan-token 2 cut 2 cut [ hex> 255 /f ] tri@ 1
<rgba> suffix
>>
CONSTANT: cells-width 79
CONSTANT: cells-height 22
CONSTANT: size 24
CONSTANT: bg-color RGB: 000000
CONSTANT: player-format {
{ font-size $ size }
{ foreground RGB: 5990C8 }
{ background RGB: B96646 }
}
CONSTANT: normal-format { { font-size $ size } }
CONSTANT: colors {
RGB: 40B4A4
RGB: 40B3B7
RGB: 40A2B9
RGB: 408FBC
RGB: 407CBF
RGB: 4268C0
RGB: 4355C2
RGB: 4845C3
RGB: 5F46C4
}
CONSTANT: neighbors {
{ -1 -1 } { -1 0 } { -1 1 }
{ 0 -1 } { 0 1 }
{ 1 -1 } { 1 0 } { 1 1 }
}
TUPLE: greed < pane cells x y score ;
: set-player ( greed elt -- )
'[ y>> _ swap ] [ x>> 2array ] [ cells>> ] tri set-index ;
: place-player ( greed -- ) 0 set-player ;
: remove-player ( greed -- ) f set-player ;
: make-cells ( -- cells )
cells-width cells-height * [ 9 random 1 + ] replicate
cells-width group ;
: write-number ( n/f -- )
[ >digit 1string normal-format first foreground ]
[ 1 - colors nth 2array ] bi 2array format ;
: write-cell ( n/f -- )
{
{ f [ " " normal-format format ] }
{ 0 [ "@" player-format format ] }
[ write-number ]
} case ;
: write-cells ( cells -- ) [ [ write-cell ] each nl ] each ;
: update-cells ( greed -- )
dup cells>> [ write-cells ] curry with-pane ;
: init-greed ( greed -- greed' )
make-cells >>cells cells-width random >>x cells-height
random >>y 0 >>score dup place-player dup update-cells dup
"Score: 0" swap show-status ;
: <greed> ( -- greed )
f greed new-pane bg-color <solid> >>interior init-greed ;
: ?r,c ( r c matrix -- elt/f ) swapd ?nth ?nth ;
: ?r,cths ( seq matrix -- newseq )
[ [ first2 ] dip ?r,c ] curry map ;
: (ray) ( start-loc dir length -- seq )
1 + [ [ [ v+ ] keep over , ] times ] { } make 2nip ;
: ray ( start-loc dir length -- seq/f )
dup [ (ray) ] [ 2nip ] if ;
: ?r,c-dir ( r c dir matrix -- n )
[ 2array ] [ v+ first2 ] [ ?r,c ] tri* ;
: move-length ( greed dir -- n )
[ [ y>> ] [ x>> ] [ ] tri ] dip swap cells>> ?r,c-dir ;
: y,x>loc ( greed -- loc ) [ y>> ] [ x>> ] bi 2array ;
: ray-dir ( greed dir -- seq )
[ [ y,x>loc ] dip ] [ move-length ] 2bi ray ;
: in-bounds? ( dim loc -- ? )
{ [ nip [ 0 >= ] all? ] [ v- [ 0 > ] all? ] } 2&& ;
: endpoint-in-bounds? ( greed dir -- ? )
ray-dir dup [
last ${ cells-height cells-width } swap in-bounds?
] when ;
: gapless? ( greed dir -- ? )
[ ray-dir ] [ drop cells>> ?r,cths ] 2bi [ integer? ] all? ;
: can-move? ( greed dir -- ? )
{ [ endpoint-in-bounds? ] [ gapless? ] } 2&& ;
: can-move-any? ( greed -- ? )
neighbors [ can-move? ] with map [ t = ] any? ;
: setup-move ( greed dir -- seq ) over remove-player ray-dir ;
: update-score ( greed dir -- greed dir )
2dup move-length pick swap [ + ] curry change-score dup
score>> number>string "Score: " prepend swap show-status ;
: (move) ( greed dir -- )
update-score [ drop f ] [ setup-move dup last ]
[ drop cells>> swap [ set-indices ] dip ] 2tri first2
[ >>y ] dip >>x place-player ;
: game-over ( greed -- )
[
score>> number>string "Game over
prepend " Press <space> for new game." append
] [ show-status ] bi ;
: ?game-over ( greed -- )
dup can-move-any? [ drop ] [ game-over ] if ;
: move ( greed dir -- )
dupd 2dup can-move? [ (move) ] [ 2drop ] if
[ update-cells ] [ ?game-over ] bi ;
: ?new-game ( greed -- )
dup can-move-any? [ drop ] [ init-greed drop ] if ;
: e ( greed -- ) { 0 1 } move ;
: se ( greed -- ) { 1 1 } move ;
: s ( greed -- ) { 1 0 } move ;
: sw ( greed -- ) { 1 -1 } move ;
: w ( greed -- ) { 0 -1 } move ;
: nw ( greed -- ) { -1 -1 } move ;
: n ( greed -- ) { -1 0 } move ;
: ne ( greed -- ) { -1 1 } move ;
greed "gestures" f {
{ T{ key-down { sym "l" } } e }
{ T{ key-down { sym "n" } } se }
{ T{ key-down { sym "j" } } s }
{ T{ key-down { sym "b" } } sw }
{ T{ key-down { sym "h" } } w }
{ T{ key-down { sym "y" } } nw }
{ T{ key-down { sym "k" } } n }
{ T{ key-down { sym "u" } } ne }
{ T{ key-down { sym " " } } ?new-game }
} define-command-map
: greed-window ( -- )
[
<greed> <world-attributes> "Greed" >>title
open-status-window
] with-ui ;
MAIN: greed-window
|
Can you help me rewrite this code in Factor instead of Go, keeping it the same logically? | package main
import (
"fmt"
"github.com/nsf/termbox-go"
"log"
"math/rand"
"strconv"
"time"
)
type coord struct{ x, y int }
const (
width = 79
height = 22
nCount = float64(width * height)
)
var (
board [width * height]int
score = 0
bold = termbox.AttrBold
cursor coord
)
var colors = [10]termbox.Attribute{
termbox.ColorDefault,
termbox.ColorWhite,
termbox.ColorBlack | bold,
termbox.ColorBlue | bold,
termbox.ColorGreen | bold,
termbox.ColorCyan | bold,
termbox.ColorRed | bold,
termbox.ColorMagenta | bold,
termbox.ColorYellow | bold,
termbox.ColorWhite | bold,
}
func printAt(x, y int, s string, fg, bg termbox.Attribute) {
for _, r := range s {
termbox.SetCell(x, y, r, fg, bg)
x++
}
}
func createBoard() {
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
board[x+width*y] = rand.Intn(9) + 1
}
}
cursor = coord{rand.Intn(width), rand.Intn(height)}
board[cursor.x+width*cursor.y] = 0
score = 0
printScore()
}
func displayBoard() {
termbox.SetCursor(0, 0)
bg := colors[0]
for y := 0; y < height; y++ {
for x := 0; x < width; x++ {
i := board[x+width*y]
fg := colors[i]
s := " "
if i > 0 {
s = strconv.Itoa(i)
}
printAt(x, y, s, fg, bg)
}
}
fg := colors[9]
termbox.SetCursor(cursor.x, cursor.y)
printAt(cursor.x, cursor.y, "@", fg, bg)
termbox.Flush()
}
func printScore() {
termbox.SetCursor(0, 24)
fg := colors[4]
bg := termbox.ColorGreen
s := fmt.Sprintf(" SCORE: %d : %.3f%% ", score, float64(score)*100.0/nCount)
printAt(0, 24, s, fg, bg)
termbox.Flush()
}
func execute(x, y int) {
i := board[cursor.x+x+width*(cursor.y+y)]
if countSteps(i, x, y) {
score += i
for i != 0 {
i--
cursor.x += x
cursor.y += y
board[cursor.x+width*cursor.y] = 0
}
}
}
func countSteps(i, x, y int) bool {
t := cursor
for i != 0 {
i--
t.x += x
t.y += y
if t.x < 0 || t.y < 0 || t.x >= width || t.y >= height || board[t.x+width*t.y] == 0 {
return false
}
}
return true
}
func existsMoves() bool {
for y := -1; y < 2; y++ {
for x := -1; x < 2; x++ {
if x == 0 && y == 0 {
continue
}
ix := cursor.x + x + width*(cursor.y+y)
i := 0
if ix >= 0 && ix < len(board) {
i = board[ix]
}
if i > 0 && countSteps(i, x, y) {
return true
}
}
}
return false
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
err := termbox.Init()
check(err)
defer termbox.Close()
eventQueue := make(chan termbox.Event)
go func() {
for {
eventQueue <- termbox.PollEvent()
}
}()
for {
termbox.HideCursor()
createBoard()
for {
displayBoard()
select {
case ev := <-eventQueue:
if ev.Type == termbox.EventKey {
switch ev.Ch {
case 'q', 'Q':
if cursor.x > 0 && cursor.y > 0 {
execute(-1, -1)
}
case 'w', 'W':
if cursor.y > 0 {
execute(0, -1)
}
case 'e', 'E':
if cursor.x < width-1 && cursor.y > 0 {
execute(1, -1)
}
case 'a', 'A':
if cursor.x > 0 {
execute(-1, 0)
}
case 'd', 'D':
if cursor.x < width-1 {
execute(1, 0)
}
case 'z', 'Z':
if cursor.x > 0 && cursor.y < height-1 {
execute(-1, 1)
}
case 'x', 'X':
if cursor.y < height-1 {
execute(0, 1)
}
case 'c', 'C':
if cursor.x < width-1 && cursor.y < height-1 {
execute(1, 1)
}
case 'l', 'L':
return
}
} else if ev.Type == termbox.EventResize {
termbox.Flush()
}
}
printScore()
if !existsMoves() {
break
}
}
displayBoard()
fg := colors[7]
bg := colors[0]
printAt(19, 8, "+----------------------------------------+", fg, bg)
printAt(19, 9, "| GAME OVER |", fg, bg)
printAt(19, 10, "| PLAY AGAIN(Y/N)? |", fg, bg)
printAt(19, 11, "+----------------------------------------+", fg, bg)
termbox.SetCursor(48, 10)
termbox.Flush()
select {
case ev := <-eventQueue:
if ev.Type == termbox.EventKey {
if ev.Ch == 'y' || ev.Ch == 'Y' {
break
} else {
return
}
}
}
}
}
| USING: accessors arrays colors combinators
combinators.short-circuit fry grouping io io.styles kernel lexer
literals make math math.matrices math.parser math.vectors random
sequences strings ui ui.commands ui.gadgets.panes
ui.gadgets.status-bar ui.gadgets.worlds ui.gestures
ui.pens.solid ;
IN: rosetta-code.greed
<<
SYNTAX: RGB: scan-token 2 cut 2 cut [ hex> 255 /f ] tri@ 1
<rgba> suffix
>>
CONSTANT: cells-width 79
CONSTANT: cells-height 22
CONSTANT: size 24
CONSTANT: bg-color RGB: 000000
CONSTANT: player-format {
{ font-size $ size }
{ foreground RGB: 5990C8 }
{ background RGB: B96646 }
}
CONSTANT: normal-format { { font-size $ size } }
CONSTANT: colors {
RGB: 40B4A4
RGB: 40B3B7
RGB: 40A2B9
RGB: 408FBC
RGB: 407CBF
RGB: 4268C0
RGB: 4355C2
RGB: 4845C3
RGB: 5F46C4
}
CONSTANT: neighbors {
{ -1 -1 } { -1 0 } { -1 1 }
{ 0 -1 } { 0 1 }
{ 1 -1 } { 1 0 } { 1 1 }
}
TUPLE: greed < pane cells x y score ;
: set-player ( greed elt -- )
'[ y>> _ swap ] [ x>> 2array ] [ cells>> ] tri set-index ;
: place-player ( greed -- ) 0 set-player ;
: remove-player ( greed -- ) f set-player ;
: make-cells ( -- cells )
cells-width cells-height * [ 9 random 1 + ] replicate
cells-width group ;
: write-number ( n/f -- )
[ >digit 1string normal-format first foreground ]
[ 1 - colors nth 2array ] bi 2array format ;
: write-cell ( n/f -- )
{
{ f [ " " normal-format format ] }
{ 0 [ "@" player-format format ] }
[ write-number ]
} case ;
: write-cells ( cells -- ) [ [ write-cell ] each nl ] each ;
: update-cells ( greed -- )
dup cells>> [ write-cells ] curry with-pane ;
: init-greed ( greed -- greed' )
make-cells >>cells cells-width random >>x cells-height
random >>y 0 >>score dup place-player dup update-cells dup
"Score: 0" swap show-status ;
: <greed> ( -- greed )
f greed new-pane bg-color <solid> >>interior init-greed ;
: ?r,c ( r c matrix -- elt/f ) swapd ?nth ?nth ;
: ?r,cths ( seq matrix -- newseq )
[ [ first2 ] dip ?r,c ] curry map ;
: (ray) ( start-loc dir length -- seq )
1 + [ [ [ v+ ] keep over , ] times ] { } make 2nip ;
: ray ( start-loc dir length -- seq/f )
dup [ (ray) ] [ 2nip ] if ;
: ?r,c-dir ( r c dir matrix -- n )
[ 2array ] [ v+ first2 ] [ ?r,c ] tri* ;
: move-length ( greed dir -- n )
[ [ y>> ] [ x>> ] [ ] tri ] dip swap cells>> ?r,c-dir ;
: y,x>loc ( greed -- loc ) [ y>> ] [ x>> ] bi 2array ;
: ray-dir ( greed dir -- seq )
[ [ y,x>loc ] dip ] [ move-length ] 2bi ray ;
: in-bounds? ( dim loc -- ? )
{ [ nip [ 0 >= ] all? ] [ v- [ 0 > ] all? ] } 2&& ;
: endpoint-in-bounds? ( greed dir -- ? )
ray-dir dup [
last ${ cells-height cells-width } swap in-bounds?
] when ;
: gapless? ( greed dir -- ? )
[ ray-dir ] [ drop cells>> ?r,cths ] 2bi [ integer? ] all? ;
: can-move? ( greed dir -- ? )
{ [ endpoint-in-bounds? ] [ gapless? ] } 2&& ;
: can-move-any? ( greed -- ? )
neighbors [ can-move? ] with map [ t = ] any? ;
: setup-move ( greed dir -- seq ) over remove-player ray-dir ;
: update-score ( greed dir -- greed dir )
2dup move-length pick swap [ + ] curry change-score dup
score>> number>string "Score: " prepend swap show-status ;
: (move) ( greed dir -- )
update-score [ drop f ] [ setup-move dup last ]
[ drop cells>> swap [ set-indices ] dip ] 2tri first2
[ >>y ] dip >>x place-player ;
: game-over ( greed -- )
[
score>> number>string "Game over
prepend " Press <space> for new game." append
] [ show-status ] bi ;
: ?game-over ( greed -- )
dup can-move-any? [ drop ] [ game-over ] if ;
: move ( greed dir -- )
dupd 2dup can-move? [ (move) ] [ 2drop ] if
[ update-cells ] [ ?game-over ] bi ;
: ?new-game ( greed -- )
dup can-move-any? [ drop ] [ init-greed drop ] if ;
: e ( greed -- ) { 0 1 } move ;
: se ( greed -- ) { 1 1 } move ;
: s ( greed -- ) { 1 0 } move ;
: sw ( greed -- ) { 1 -1 } move ;
: w ( greed -- ) { 0 -1 } move ;
: nw ( greed -- ) { -1 -1 } move ;
: n ( greed -- ) { -1 0 } move ;
: ne ( greed -- ) { -1 1 } move ;
greed "gestures" f {
{ T{ key-down { sym "l" } } e }
{ T{ key-down { sym "n" } } se }
{ T{ key-down { sym "j" } } s }
{ T{ key-down { sym "b" } } sw }
{ T{ key-down { sym "h" } } w }
{ T{ key-down { sym "y" } } nw }
{ T{ key-down { sym "k" } } n }
{ T{ key-down { sym "u" } } ne }
{ T{ key-down { sym " " } } ?new-game }
} define-command-map
: greed-window ( -- )
[
<greed> <world-attributes> "Greed" >>title
open-status-window
] with-ui ;
MAIN: greed-window
|
Port the provided Go code into Factor while preserving the original functionality. | package main
import (
"fmt"
"rcu"
"strconv"
)
func contains(a []int, n int) bool {
for _, e := range a {
if e == n {
return true
}
}
return false
}
func main() {
for b := 2; b <= 36; b++ {
if rcu.IsPrime(b) {
continue
}
count := 0
var rhonda []int
for n := 1; count < 15; n++ {
digits := rcu.Digits(n, b)
if !contains(digits, 0) {
var anyEven = false
for _, d := range digits {
if d%2 == 0 {
anyEven = true
break
}
}
if b != 10 || (contains(digits, 5) && anyEven) {
calc1 := 1
for _, d := range digits {
calc1 *= d
}
calc2 := b * rcu.SumInts(rcu.PrimeFactors(n))
if calc1 == calc2 {
rhonda = append(rhonda, n)
count++
}
}
}
}
if len(rhonda) > 0 {
fmt.Printf("\nFirst 15 Rhonda numbers in base %d:\n", b)
rhonda2 := make([]string, len(rhonda))
counts2 := make([]int, len(rhonda))
for i, r := range rhonda {
rhonda2[i] = fmt.Sprintf("%d", r)
counts2[i] = len(rhonda2[i])
}
rhonda3 := make([]string, len(rhonda))
counts3 := make([]int, len(rhonda))
for i, r := range rhonda {
rhonda3[i] = strconv.FormatInt(int64(r), b)
counts3[i] = len(rhonda3[i])
}
maxLen2 := rcu.MaxInts(counts2)
maxLen3 := rcu.MaxInts(counts3)
maxLen := maxLen2
if maxLen3 > maxLen {
maxLen = maxLen3
}
maxLen++
fmt.Printf("In base 10: %*s\n", maxLen, rhonda2)
fmt.Printf("In base %-2d: %*s\n", b, maxLen, rhonda3)
}
}
}
| USING: formatting grouping io kernel lists lists.lazy math
math.parser math.primes math.primes.factors prettyprint ranges
sequences sequences.extras ;
: rhonda? ( n base -- ? )
[ [ >base 1 group ] keep '[ _ base> ] map-product ]
[ swap factors sum * ] 2bi = ;
: rhonda ( base -- list ) 1 lfrom swap '[ _ rhonda? ] lfilter ;
: list. ( list base -- ) '[ _ >base write bl ] leach nl ;
:: rhonda. ( base -- )
15 base rhonda ltake :> r
base "First 15 Rhonda numbers to base %d:\n" printf
"In base 10: " write r 10 list.
base "In base %d: " printf r base list. ;
2 36 [a..b] [ prime? not ] filter [ rhonda. nl ] each
|
Produce a functionally identical Factor code for the snippet given in Go. | package main
import (
"fmt"
"log"
"math"
)
var MinusInf = math.Inf(-1)
type MaxTropical struct{ r float64 }
func newMaxTropical(r float64) MaxTropical {
if math.IsInf(r, 1) || math.IsNaN(r) {
log.Fatal("Argument must be a real number or negative infinity.")
}
return MaxTropical{r}
}
func (t MaxTropical) eq(other MaxTropical) bool {
return t.r == other.r
}
func (t MaxTropical) add(other MaxTropical) MaxTropical {
if t.r == MinusInf {
return other
}
if other.r == MinusInf {
return t
}
return newMaxTropical(math.Max(t.r, other.r))
}
func (t MaxTropical) mul(other MaxTropical) MaxTropical {
if t.r == 0 {
return other
}
if other.r == 0 {
return t
}
return newMaxTropical(t.r + other.r)
}
func (t MaxTropical) pow(e int) MaxTropical {
if e < 1 {
log.Fatal("Exponent must be a positive integer.")
}
if e == 1 {
return t
}
p := t
for i := 2; i <= e; i++ {
p = p.mul(t)
}
return p
}
func (t MaxTropical) String() string {
return fmt.Sprintf("%g", t.r)
}
func main() {
data := [][]float64{
{2, -2, 1},
{-0.001, MinusInf, 0},
{0, MinusInf, 1},
{1.5, -1, 0},
{-0.5, 0, 1},
}
for _, d := range data {
a := newMaxTropical(d[0])
b := newMaxTropical(d[1])
if d[2] == 0 {
fmt.Printf("%s ⊕ %s = %s\n", a, b, a.add(b))
} else {
fmt.Printf("%s ⊗ %s = %s\n", a, b, a.mul(b))
}
}
c := newMaxTropical(5)
fmt.Printf("%s ^ 7 = %s\n", c, c.pow(7))
d := newMaxTropical(8)
e := newMaxTropical(7)
f := c.mul(d.add(e))
g := c.mul(d).add(c.mul(e))
fmt.Printf("%s ⊗ (%s ⊕ %s) = %s\n", c, d, e, f)
fmt.Printf("%s ⊗ %s ⊕ %s ⊗ %s = %s\n", c, d, c, e, g)
fmt.Printf("%s ⊗ (%s ⊕ %s) == %s ⊗ %s ⊕ %s ⊗ %s is %t\n", c, d, e, c, d, c, e, f.eq(g))
}
| USING: io kernel math math.order present prettyprint sequences
typed ;
ALIAS: ⊕ max
ALIAS: ⊗ +
PREDICATE: posint < integer 0 > ;
TYPED: ↑ ( x: real n: posint -- y: real ) * ;
: show ( quot -- )
dup present rest but-last "⟶ " append write call . ; inline
{
[ 2 -2 ⊗ ]
[ -0.001 -1/0. ⊕ ]
[ 0 -1/0. ⊗ ]
[ 1.5 -1 ⊕ ]
[ -0.5 0 ⊗ ]
[ 5 7 ↑ ]
[ 8 7 ⊕ 5 ⊗ ]
[ 5 8 ⊗ 5 7 ⊗ ⊕ ]
[ 8 7 ⊕ 5 ⊗ 5 8 ⊗ 5 7 ⊗ ⊕ = ]
} [ show ] each
|
Generate an equivalent Factor version of this Go code. | package main
import (
"fmt"
"rcu"
)
func prune(a []int) []int {
prev := a[0]
b := []int{prev}
for i := 1; i < len(a); i++ {
if a[i] != prev {
b = append(b, a[i])
prev = a[i]
}
}
return b
}
func main() {
var resF, resD, resT, factors1 []int
factors2 := []int{2}
factors3 := []int{3}
var sum1, sum2, sum3 int = 0, 2, 3
var countF, countD, countT int
for n := 2; countT < 1 || countD < 30 || countF < 30; n++ {
factors1 = factors2
factors2 = factors3
factors3 = rcu.PrimeFactors(n + 2)
sum1 = sum2
sum2 = sum3
sum3 = rcu.SumInts(factors3)
if countF < 30 && sum1 == sum2 {
resF = append(resF, n)
countF++
}
if sum1 == sum2 && sum2 == sum3 {
resT = append(resT, n)
countT++
}
if countD < 30 {
factors4 := make([]int, len(factors1))
copy(factors4, factors1)
factors5 := make([]int, len(factors2))
copy(factors5, factors2)
factors4 = prune(factors4)
factors5 = prune(factors5)
if rcu.SumInts(factors4) == rcu.SumInts(factors5) {
resD = append(resD, n)
countD++
}
}
}
fmt.Println("First 30 Ruth-Aaron numbers (factors):")
fmt.Println(resF)
fmt.Println("\nFirst 30 Ruth-Aaron numbers (divisors):")
fmt.Println(resD)
fmt.Println("\nFirst Ruth-Aaron triple (factors):")
fmt.Println(resT[0])
resT = resT[:0]
factors1 = factors1[:0]
factors2 = factors2[:1]
factors2[0] = 2
factors3 = factors3[:1]
factors3[0] = 3
countT = 0
for n := 2; countT < 1; n++ {
factors1 = factors2
factors2 = factors3
factors3 = prune(rcu.PrimeFactors(n + 2))
sum1 = sum2
sum2 = sum3
sum3 = rcu.SumInts(factors3)
if sum1 == sum2 && sum2 == sum3 {
resT = append(resT, n)
countT++
}
}
fmt.Println("\nFirst Ruth-Aaron triple (divisors):")
fmt.Println(resT[0])
}
| USING: assocs.extras grouping io kernel lists lists.lazy math
math.primes.factors prettyprint ranges sequences ;
: pair-same? ( ... n quot: ( ... m -- ... n ) -- ... ? )
[ dup 1 + ] dip same? ; inline
: RA-f? ( n -- ? ) [ factors sum ] pair-same? ;
: RA-d? ( n -- ? ) [ group-factors sum-keys ] pair-same? ;
: filter-naturals ( quot -- list ) 1 lfrom swap lfilter ; inline
: RA-f ( -- list ) [ RA-f? ] filter-naturals ;
: RA-d ( -- list ) [ RA-d? ] filter-naturals ;
: list. ( list -- )
30 swap ltake list>array 10 group simple-table. ;
"First 30 Ruth-Aaron numbers (factors):" print
RA-f list. nl
"First 30 Ruth-Aaron numbers (divisors):" print
RA-d list.
|
Write a version of this Go function in Factor with identical behavior. | package main
import "fmt"
func shouldSwap(s []byte, start, curr int) bool {
for i := start; i < curr; i++ {
if s[i] == s[curr] {
return false
}
}
return true
}
func findPerms(s []byte, index, n int, res *[]string) {
if index >= n {
*res = append(*res, string(s))
return
}
for i := index; i < n; i++ {
check := shouldSwap(s, index, i)
if check {
s[index], s[i] = s[i], s[index]
findPerms(s, index+1, n, res)
s[index], s[i] = s[i], s[index]
}
}
}
func createSlice(nums []int, charSet string) []byte {
var chars []byte
for i := 0; i < len(nums); i++ {
for j := 0; j < nums[i]; j++ {
chars = append(chars, charSet[i])
}
}
return chars
}
func main() {
var res, res2, res3 []string
nums := []int{2, 1}
s := createSlice(nums, "12")
findPerms(s, 0, len(s), &res)
fmt.Println(res)
fmt.Println()
nums = []int{2, 3, 1}
s = createSlice(nums, "123")
findPerms(s, 0, len(s), &res2)
fmt.Println(res2)
fmt.Println()
s = createSlice(nums, "ABC")
findPerms(s, 0, len(s), &res3)
fmt.Println(res3)
}
| USING: arrays grouping math math.combinatorics prettyprint
sequences sets ;
: distinct-permutations ( seq -- seq )
[ CHAR: A + <array> ] map-index "" concat-as <permutations>
members ;
{ 2 3 1 } distinct-permutations 10 group simple-table.
|
Rewrite this program in Factor while keeping its functionality equivalent to the Go version. | package main
import "fmt"
func gcd(a, b uint) uint {
if b == 0 {
return a
}
return gcd(b, a%b)
}
func lcm(a, b uint) uint {
return a / gcd(a, b) * b
}
func ipow(x, p uint) uint {
prod := uint(1)
for p > 0 {
if p&1 != 0 {
prod *= x
}
p >>= 1
x *= x
}
return prod
}
func getPrimes(n uint) []uint {
var primes []uint
for i := uint(2); i <= n; i++ {
div := n / i
mod := n % i
for mod == 0 {
primes = append(primes, i)
n = div
div = n / i
mod = n % i
}
}
return primes
}
func isPrime(n uint) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := uint(5)
for d*d <= n {
if n%d == 0 {
return false
}
d += 2
if n%d == 0 {
return false
}
d += 4
}
return true
}
}
func pisanoPeriod(m uint) uint {
var p, c uint = 0, 1
for i := uint(0); i < m*m; i++ {
p, c = c, (p+c)%m
if p == 0 && c == 1 {
return i + 1
}
}
return 1
}
func pisanoPrime(p uint, k uint) uint {
if !isPrime(p) || k == 0 {
return 0
}
return ipow(p, k-1) * pisanoPeriod(p)
}
func pisano(m uint) uint {
primes := getPrimes(m)
primePowers := make(map[uint]uint)
for _, p := range primes {
primePowers[p]++
}
var pps []uint
for k, v := range primePowers {
pps = append(pps, pisanoPrime(k, v))
}
if len(pps) == 0 {
return 1
}
if len(pps) == 1 {
return pps[0]
}
f := pps[0]
for i := 1; i < len(pps); i++ {
f = lcm(f, pps[i])
}
return f
}
func main() {
for p := uint(2); p < 15; p++ {
pp := pisanoPrime(p, 2)
if pp > 0 {
fmt.Printf("pisanoPrime(%2d: 2) = %d\n", p, pp)
}
}
fmt.Println()
for p := uint(2); p < 180; p++ {
pp := pisanoPrime(p, 1)
if pp > 0 {
fmt.Printf("pisanoPrime(%3d: 1) = %d\n", p, pp)
}
}
fmt.Println()
fmt.Println("pisano(n) for integers 'n' from 1 to 180 are:")
for n := uint(1); n <= 180; n++ {
fmt.Printf("%3d ", pisano(n))
if n != 1 && n%15 == 0 {
fmt.Println()
}
}
fmt.Println()
}
| USING: formatting fry grouping io kernel math math.functions
math.primes math.primes.factors math.ranges sequences ;
: pisano-period ( m -- n )
[ 0 1 ] dip [ sq <iota> ] [ ] bi
'[ drop tuck + _ mod 2dup [ zero? ] [ 1 = ] bi* and ]
find 3nip [ 1 + ] [ 1 ] if* ;
: pisano-prime ( p k -- n )
over prime? [ "p must be prime." throw ] unless
^ pisano-period ;
: pisano ( m -- n )
group-factors [ first2 pisano-prime ] [ lcm ] map-reduce ;
: show-pisano ( upto m -- )
[ primes-upto ] dip
[ 2dup pisano-prime "%d %d pisano-prime = %d\n" printf ]
curry each nl ;
15 2 show-pisano
180 1 show-pisano
"n pisano for integers 'n' from 2 to 180:" print
2 180 [a,b] [ pisano ] map 15 group
[ [ "%3d " printf ] each nl ] each
|
Rewrite this program in Factor while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"math"
"math/big"
"strconv"
"strings"
)
type minmult struct {
min int
mult float64
}
var abbrevs = map[string]minmult{
"PAIRs": {4, 2}, "SCOres": {3, 20}, "DOZens": {3, 12},
"GRoss": {2, 144}, "GREATGRoss": {7, 1728}, "GOOGOLs": {6, 1e100},
}
var metric = map[string]float64{
"K": 1e3, "M": 1e6, "G": 1e9, "T": 1e12, "P": 1e15, "E": 1e18,
"Z": 1e21, "Y": 1e24, "X": 1e27, "W": 1e30, "V": 1e33, "U": 1e36,
}
var binary = map[string]float64{
"Ki": b(10), "Mi": b(20), "Gi": b(30), "Ti": b(40), "Pi": b(50), "Ei": b(60),
"Zi": b(70), "Yi": b(80), "Xi": b(90), "Wi": b(100), "Vi": b(110), "Ui": b(120),
}
func b(e float64) float64 {
return math.Pow(2, e)
}
func googol() *big.Float {
g1 := new(big.Float).SetPrec(500)
g1.SetInt64(10000000000)
g := new(big.Float)
g.Set(g1)
for i := 2; i <= 10; i++ {
g.Mul(g, g1)
}
return g
}
func fact(num string, d int) int {
prod := 1
n, _ := strconv.Atoi(num)
for i := n; i > 0; i -= d {
prod *= i
}
return prod
}
func parse(number string) *big.Float {
bf := new(big.Float).SetPrec(500)
t1 := new(big.Float).SetPrec(500)
t2 := new(big.Float).SetPrec(500)
var i int
for i = len(number) - 1; i >= 0; i-- {
if '0' <= number[i] && number[i] <= '9' {
break
}
}
num := number[:i+1]
num = strings.Replace(num, ",", "", -1)
suf := strings.ToUpper(number[i+1:])
if suf == "" {
bf.SetString(num)
return bf
}
if suf[0] == '!' {
prod := fact(num, len(suf))
bf.SetInt64(int64(prod))
return bf
}
for k, v := range abbrevs {
kk := strings.ToUpper(k)
if strings.HasPrefix(kk, suf) && len(suf) >= v.min {
t1.SetString(num)
if k != "GOOGOLs" {
t2.SetFloat64(v.mult)
} else {
t2 = googol()
}
bf.Mul(t1, t2)
return bf
}
}
bf.SetString(num)
for k, v := range metric {
for j := 0; j < len(suf); j++ {
if k == suf[j:j+1] {
if j < len(suf)-1 && suf[j+1] == 'I' {
t1.SetFloat64(binary[k+"i"])
bf.Mul(bf, t1)
j++
} else {
t1.SetFloat64(v)
bf.Mul(bf, t1)
}
}
}
}
return bf
}
func commatize(s string) string {
if len(s) == 0 {
return ""
}
neg := s[0] == '-'
if neg {
s = s[1:]
}
frac := ""
if ix := strings.Index(s, "."); ix >= 0 {
frac = s[ix:]
s = s[:ix]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if !neg {
return s + frac
}
return "-" + s + frac
}
func process(numbers []string) {
fmt.Print("numbers = ")
for _, number := range numbers {
fmt.Printf("%s ", number)
}
fmt.Print("\nresults = ")
for _, number := range numbers {
res := parse(number)
t := res.Text('g', 50)
fmt.Printf("%s ", commatize(t))
}
fmt.Println("\n")
}
func main() {
numbers := []string{"2greatGRo", "24Gros", "288Doz", "1,728pairs", "172.8SCOre"}
process(numbers)
numbers = []string{"1,567", "+1.567k", "0.1567e-2m"}
process(numbers)
numbers = []string{"25.123kK", "25.123m", "2.5123e-00002G"}
process(numbers)
numbers = []string{"25.123kiKI", "25.123Mi", "2.5123e-00002Gi", "+.25123E-7Ei"}
process(numbers)
numbers = []string{"-.25123e-34Vikki", "2e-77gooGols"}
process(numbers)
numbers = []string{"9!", "9!!", "9!!!", "9!!!!", "9!!!!!", "9!!!!!!",
"9!!!!!!!", "9!!!!!!!!", "9!!!!!!!!!"}
process(numbers)
}
| USING: combinators combinators.short-circuit formatting fry
grouping grouping.extras kernel literals math math.functions
math.parser math.ranges qw regexp sequences sequences.deep
sequences.extras sets splitting unicode ;
IN: rosetta-code.numerical-suffixes
CONSTANT: test-cases {
qw{ 2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre }
qw{ 1,567 +1.567k 0.1567e-2m }
qw{ 25.123kK 25.123m 2.5123e-00002G }
qw{ 25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei }
qw{ -.25123e-34Vikki 2e-77gooGols }
qw{
9
9
}
}
CONSTANT: alpha {
{ "PAIRs" 2 } { "DOZens" 12 } { "SCOres" 20 }
{ "GRoss" 144 } { "GREATGRoss" 1,728 }
${ "GOOGOLs" 10 100 ^ }
}
CONSTANT: metric qw{ K M G T P E Z Y X W V U }
: m
: num/suffix ( str -- n suffix(es) )
dup <head-clumps> <reversed> { } like "" map-like
[ string>number ] map [ ] find [ tail* ] dip swap ;
: abbrev? ( str1 str2 -- ? )
{
[ [ >upper ] [ [ LETTER? ] take-while head? ] bi* ]
[ [ length ] bi@ <= ]
} 2&& ;
: alpha>quot ( str -- quot )
[ alpha ] dip '[ first _ swap abbrev? ] find nip second
[ * ] curry ;
: split-compound ( str -- seq )
R/ (.i|.)/i all-matching-subseqs ;
: suffix>quot ( str -- quot )
dup [ [ 0 1 ] dip subseq >upper metric index 1 + ] dip
length 1 = [ 3 * '[ 10 _ ^ * ] ] [ 10 * '[ 2 _ ^ * ] ] if ;
: map-suffix ( seq -- seq' ) [ suffix>quot ] [ ] map-as ;
: compound? ( str -- ? )
>upper metric concat "I" append without empty? ;
: ?f>i ( x -- y/n )
dup >integer 2dup [ number= ] 2dip swap ? ;
: parse-suffix ( str -- quot )
{
{ [ dup empty? ] [ drop [ ] ] }
{ [ dup first CHAR:
{ [ dup compound? ] [ split-compound map-suffix ] }
[ alpha>quot ]
} cond flatten ;
GENERIC: commas ( n -- str )
M: integer commas number>string <reversed> 3 group
[ "," append ] map concat reverse rest ;
M: float commas number>string "." split first2
[ string>number commas ] dip "." glue ;
: parse-alpha ( str -- str' )
num/suffix parse-suffix curry call( -- x ) ?f>i commas ;
: main ( -- )
test-cases [
dup [ parse-alpha ] map
"Numbers: %[%s, %]\n Result: %[%s, %]\n\n" printf
] each ;
MAIN: main
|
Transform the following Go implementation into Factor, maintaining the same output and logic. | package main
import (
"fmt"
"math"
"math/big"
"strconv"
"strings"
)
type minmult struct {
min int
mult float64
}
var abbrevs = map[string]minmult{
"PAIRs": {4, 2}, "SCOres": {3, 20}, "DOZens": {3, 12},
"GRoss": {2, 144}, "GREATGRoss": {7, 1728}, "GOOGOLs": {6, 1e100},
}
var metric = map[string]float64{
"K": 1e3, "M": 1e6, "G": 1e9, "T": 1e12, "P": 1e15, "E": 1e18,
"Z": 1e21, "Y": 1e24, "X": 1e27, "W": 1e30, "V": 1e33, "U": 1e36,
}
var binary = map[string]float64{
"Ki": b(10), "Mi": b(20), "Gi": b(30), "Ti": b(40), "Pi": b(50), "Ei": b(60),
"Zi": b(70), "Yi": b(80), "Xi": b(90), "Wi": b(100), "Vi": b(110), "Ui": b(120),
}
func b(e float64) float64 {
return math.Pow(2, e)
}
func googol() *big.Float {
g1 := new(big.Float).SetPrec(500)
g1.SetInt64(10000000000)
g := new(big.Float)
g.Set(g1)
for i := 2; i <= 10; i++ {
g.Mul(g, g1)
}
return g
}
func fact(num string, d int) int {
prod := 1
n, _ := strconv.Atoi(num)
for i := n; i > 0; i -= d {
prod *= i
}
return prod
}
func parse(number string) *big.Float {
bf := new(big.Float).SetPrec(500)
t1 := new(big.Float).SetPrec(500)
t2 := new(big.Float).SetPrec(500)
var i int
for i = len(number) - 1; i >= 0; i-- {
if '0' <= number[i] && number[i] <= '9' {
break
}
}
num := number[:i+1]
num = strings.Replace(num, ",", "", -1)
suf := strings.ToUpper(number[i+1:])
if suf == "" {
bf.SetString(num)
return bf
}
if suf[0] == '!' {
prod := fact(num, len(suf))
bf.SetInt64(int64(prod))
return bf
}
for k, v := range abbrevs {
kk := strings.ToUpper(k)
if strings.HasPrefix(kk, suf) && len(suf) >= v.min {
t1.SetString(num)
if k != "GOOGOLs" {
t2.SetFloat64(v.mult)
} else {
t2 = googol()
}
bf.Mul(t1, t2)
return bf
}
}
bf.SetString(num)
for k, v := range metric {
for j := 0; j < len(suf); j++ {
if k == suf[j:j+1] {
if j < len(suf)-1 && suf[j+1] == 'I' {
t1.SetFloat64(binary[k+"i"])
bf.Mul(bf, t1)
j++
} else {
t1.SetFloat64(v)
bf.Mul(bf, t1)
}
}
}
}
return bf
}
func commatize(s string) string {
if len(s) == 0 {
return ""
}
neg := s[0] == '-'
if neg {
s = s[1:]
}
frac := ""
if ix := strings.Index(s, "."); ix >= 0 {
frac = s[ix:]
s = s[:ix]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if !neg {
return s + frac
}
return "-" + s + frac
}
func process(numbers []string) {
fmt.Print("numbers = ")
for _, number := range numbers {
fmt.Printf("%s ", number)
}
fmt.Print("\nresults = ")
for _, number := range numbers {
res := parse(number)
t := res.Text('g', 50)
fmt.Printf("%s ", commatize(t))
}
fmt.Println("\n")
}
func main() {
numbers := []string{"2greatGRo", "24Gros", "288Doz", "1,728pairs", "172.8SCOre"}
process(numbers)
numbers = []string{"1,567", "+1.567k", "0.1567e-2m"}
process(numbers)
numbers = []string{"25.123kK", "25.123m", "2.5123e-00002G"}
process(numbers)
numbers = []string{"25.123kiKI", "25.123Mi", "2.5123e-00002Gi", "+.25123E-7Ei"}
process(numbers)
numbers = []string{"-.25123e-34Vikki", "2e-77gooGols"}
process(numbers)
numbers = []string{"9!", "9!!", "9!!!", "9!!!!", "9!!!!!", "9!!!!!!",
"9!!!!!!!", "9!!!!!!!!", "9!!!!!!!!!"}
process(numbers)
}
| USING: combinators combinators.short-circuit formatting fry
grouping grouping.extras kernel literals math math.functions
math.parser math.ranges qw regexp sequences sequences.deep
sequences.extras sets splitting unicode ;
IN: rosetta-code.numerical-suffixes
CONSTANT: test-cases {
qw{ 2greatGRo 24Gros 288Doz 1,728pairs 172.8SCOre }
qw{ 1,567 +1.567k 0.1567e-2m }
qw{ 25.123kK 25.123m 2.5123e-00002G }
qw{ 25.123kiKI 25.123Mi 2.5123e-00002Gi +.25123E-7Ei }
qw{ -.25123e-34Vikki 2e-77gooGols }
qw{
9
9
}
}
CONSTANT: alpha {
{ "PAIRs" 2 } { "DOZens" 12 } { "SCOres" 20 }
{ "GRoss" 144 } { "GREATGRoss" 1,728 }
${ "GOOGOLs" 10 100 ^ }
}
CONSTANT: metric qw{ K M G T P E Z Y X W V U }
: m
: num/suffix ( str -- n suffix(es) )
dup <head-clumps> <reversed> { } like "" map-like
[ string>number ] map [ ] find [ tail* ] dip swap ;
: abbrev? ( str1 str2 -- ? )
{
[ [ >upper ] [ [ LETTER? ] take-while head? ] bi* ]
[ [ length ] bi@ <= ]
} 2&& ;
: alpha>quot ( str -- quot )
[ alpha ] dip '[ first _ swap abbrev? ] find nip second
[ * ] curry ;
: split-compound ( str -- seq )
R/ (.i|.)/i all-matching-subseqs ;
: suffix>quot ( str -- quot )
dup [ [ 0 1 ] dip subseq >upper metric index 1 + ] dip
length 1 = [ 3 * '[ 10 _ ^ * ] ] [ 10 * '[ 2 _ ^ * ] ] if ;
: map-suffix ( seq -- seq' ) [ suffix>quot ] [ ] map-as ;
: compound? ( str -- ? )
>upper metric concat "I" append without empty? ;
: ?f>i ( x -- y/n )
dup >integer 2dup [ number= ] 2dip swap ? ;
: parse-suffix ( str -- quot )
{
{ [ dup empty? ] [ drop [ ] ] }
{ [ dup first CHAR:
{ [ dup compound? ] [ split-compound map-suffix ] }
[ alpha>quot ]
} cond flatten ;
GENERIC: commas ( n -- str )
M: integer commas number>string <reversed> 3 group
[ "," append ] map concat reverse rest ;
M: float commas number>string "." split first2
[ string>number commas ] dip "." glue ;
: parse-alpha ( str -- str' )
num/suffix parse-suffix curry call( -- x ) ?f>i commas ;
: main ( -- )
test-cases [
dup [ parse-alpha ] map
"Numbers: %[%s, %]\n Result: %[%s, %]\n\n" printf
] each ;
MAIN: main
|
Port the provided Go code into Factor while preserving the original functionality. | package main
import (
"fmt"
"math"
)
const MAXITER = 151
func minkowski(x float64) float64 {
if x > 1 || x < 0 {
return math.Floor(x) + minkowski(x-math.Floor(x))
}
p := uint64(x)
q := uint64(1)
r := p + 1
s := uint64(1)
d := 1.0
y := float64(p)
for {
d = d / 2
if y+d == y {
break
}
m := p + r
if m < 0 || p < 0 {
break
}
n := q + s
if n < 0 {
break
}
if x < float64(m)/float64(n) {
r = m
s = n
} else {
y = y + d
p = m
q = n
}
}
return y + d
}
func minkowskiInv(x float64) float64 {
if x > 1 || x < 0 {
return math.Floor(x) + minkowskiInv(x-math.Floor(x))
}
if x == 1 || x == 0 {
return x
}
contFrac := []uint32{0}
curr := uint32(0)
count := uint32(1)
i := 0
for {
x *= 2
if curr == 0 {
if x < 1 {
count++
} else {
i++
t := contFrac
contFrac = make([]uint32, i+1)
copy(contFrac, t)
contFrac[i-1] = count
count = 1
curr = 1
x--
}
} else {
if x > 1 {
count++
x--
} else {
i++
t := contFrac
contFrac = make([]uint32, i+1)
copy(contFrac, t)
contFrac[i-1] = count
count = 1
curr = 0
}
}
if x == math.Floor(x) {
contFrac[i] = count
break
}
if i == MAXITER {
break
}
}
ret := 1.0 / float64(contFrac[i])
for j := i - 1; j >= 0; j-- {
ret = float64(contFrac[j]) + 1.0/ret
}
return 1.0 / ret
}
func main() {
fmt.Printf("%19.16f %19.16f\n", minkowski(0.5*(1+math.Sqrt(5))), 5.0/3.0)
fmt.Printf("%19.16f %19.16f\n", minkowskiInv(-5.0/9.0), (math.Sqrt(13)-7)/6)
fmt.Printf("%19.16f %19.16f\n", minkowski(minkowskiInv(0.718281828)),
minkowskiInv(minkowski(0.1213141516171819)))
}
| USING: formatting kernel make math math.constants
math.continued-fractions math.functions math.parser
math.statistics sequences sequences.extras splitting.monotonic
vectors ;
CONSTANT: max-iter 151
: >continued-fraction ( x -- seq )
0 swap 1vector
[ dup last integer? pick max-iter > or ]
[ dup next-approx [ 1 + ] dip ] until nip
dup last integer? [ but-last-slice ] unless ;
: ? ( x -- y )
>continued-fraction unclip swap cum-sum
[ max-iter < ] take-while
[ even? 1 -1 kernel:? swap 2^ / ] map-index
sum 2 * + >float ;
: (float>bin) ( x -- y )
[ dup 0 > ]
[ 2 * dup >integer # dup 1 >= [ 1 - ] when ] while ;
: float>bin ( x -- n str )
>float dup >integer [ - ] keep swap abs
[ 0 # (float>bin) ] "" make nip ;
: ?⁻¹ ( x -- y )
dup float>bin [ = ] monotonic-split
[ length ] map swap prefix >ratio swap copysign ;
: compare ( x y -- ) "%-25u%-25u\n" printf ;
phi ? 5 3 /f compare
-5/9 ?⁻¹ 13 sqrt 7 - 6 /f compare
0.718281828 ?⁻¹ ? 0.1213141516171819 ? ?⁻¹ compare
|
Keep all operations the same but rewrite the snippet in Factor. | package main
import (
"fmt"
"math/big"
"rcu"
"sort"
)
var zero = new(big.Int)
var one = big.NewInt(1)
var two = big.NewInt(2)
var three = big.NewInt(3)
var four = big.NewInt(4)
var five = big.NewInt(5)
var six = big.NewInt(6)
func primeFactorsWheel(m *big.Int) []*big.Int {
n := new(big.Int).Set(m)
t := new(big.Int)
inc := []*big.Int{four, two, four, two, four, six, two, six}
var factors []*big.Int
for t.Rem(n, two).Cmp(zero) == 0 {
factors = append(factors, two)
n.Quo(n, two)
}
for t.Rem(n, three).Cmp(zero) == 0 {
factors = append(factors, three)
n.Quo(n, three)
}
for t.Rem(n, five).Cmp(zero) == 0 {
factors = append(factors, five)
n.Quo(n, five)
}
k := big.NewInt(7)
i := 0
for t.Mul(k, k).Cmp(n) <= 0 {
if t.Rem(n, k).Cmp(zero) == 0 {
factors = append(factors, new(big.Int).Set(k))
n.Quo(n, k)
} else {
k.Add(k, inc[i])
i = (i + 1) % 8
}
}
if n.Cmp(one) > 0 {
factors = append(factors, n)
}
return factors
}
func pollardRho(n *big.Int) *big.Int {
g := func(x, n *big.Int) *big.Int {
x2 := new(big.Int)
x2.Mul(x, x)
x2.Add(x2, one)
return x2.Mod(x2, n)
}
x, y, d := new(big.Int).Set(two), new(big.Int).Set(two), new(big.Int).Set(one)
t, z := new(big.Int), new(big.Int).Set(one)
count := 0
for {
x = g(x, n)
y = g(g(y, n), n)
t.Sub(x, y)
t.Abs(t)
t.Mod(t, n)
z.Mul(z, t)
count++
if count == 100 {
d.GCD(nil, nil, z, n)
if d.Cmp(one) != 0 {
break
}
z.Set(one)
count = 0
}
}
if d.Cmp(n) == 0 {
return new(big.Int)
}
return d
}
func primeFactors(m *big.Int) []*big.Int {
n := new(big.Int).Set(m)
var factors []*big.Int
lim := big.NewInt(1e9)
for n.Cmp(one) > 0 {
if n.Cmp(lim) > 0 {
d := pollardRho(n)
if d.Cmp(zero) != 0 {
factors = append(factors, primeFactorsWheel(d)...)
n.Quo(n, d)
if n.ProbablyPrime(10) {
factors = append(factors, n)
break
}
} else {
factors = append(factors, primeFactorsWheel(n)...)
break
}
} else {
factors = append(factors, primeFactorsWheel(n)...)
break
}
}
sort.Slice(factors, func(i, j int) bool { return factors[i].Cmp(factors[j]) < 0 })
return factors
}
func main() {
list := make([]int, 20)
for i := 2; i <= 20; i++ {
list[i-2] = i
}
list[19] = 65
for _, i := range list {
if rcu.IsPrime(i) {
fmt.Printf("HP%d = %d\n", i, i)
continue
}
n := 1
j := big.NewInt(int64(i))
h := []*big.Int{j}
for {
pf := primeFactors(j)
k := ""
for _, f := range pf {
k += fmt.Sprintf("%d", f)
}
j, _ = new(big.Int).SetString(k, 10)
h = append(h, j)
if j.ProbablyPrime(10) {
for l := n; l > 0; l-- {
fmt.Printf("HP%d(%d) = ", h[n-l], l)
}
fmt.Println(h[n])
break
} else {
n++
}
}
}
}
| USING: formatting kernel make math math.parser math.primes
math.primes.factors math.ranges present prettyprint sequences
sequences.extras ;
: squish ( seq -- n ) [ present ] map-concat dec> ;
: next ( m -- n ) factors squish ; inline
: (chain) ( n -- ) [ dup prime? ] [ dup , next ] until , ;
: chain ( n -- seq ) [ (chain) ] { } make ;
: prime. ( n -- ) dup "HP%d = %d\n" printf ;
: setup ( seq -- n s r ) unclip-last swap dup length 1 [a,b] ;
: multi. ( n -- ) chain setup [ "HP%d(%d) = " printf ] 2each . ;
: chain. ( n -- ) dup prime? [ prime. ] [ multi. ] if ;
2 20 [a,b] [ chain. ] each
|
Produce a functionally identical Factor code for the snippet given in Go. | package main
import (
"fmt"
"sort"
"strings"
)
func substrings(s string) []string {
var ss []string
n := len(s)
for i := 0; i < n; i++ {
for j := 1; j <= n-i; j++ {
ss = append(ss, s[i:i+j])
}
}
return ss
}
func reversed(s string) string {
var sb strings.Builder
for i := len(s) - 1; i >= 0; i-- {
sb.WriteByte(s[i])
}
return sb.String()
}
func main() {
fmt.Println("Number Palindromes")
for i := 100; i <= 125; i++ {
var pals []string
ss := substrings(fmt.Sprintf("%d", i))
for _, s := range ss {
if s == reversed(s) {
pals = append(pals, s)
}
}
m := make(map[string]bool)
for _, pal := range pals {
m[pal] = true
}
pals = pals[:0]
for k := range m {
pals = append(pals, k)
}
sort.Slice(pals, func(i, j int) bool {
if len(pals[i]) == len(pals[j]) {
return pals[i] < pals[j]
}
return len(pals[i]) < len(pals[j])
})
fmt.Printf("%d %3s\n", i, pals)
}
nums := []string{
"9", "169", "12769", "1238769", "123498769", "12346098769", "1234572098769",
"123456832098769", "12345679432098769", "1234567905432098769", "123456790165432098769",
"83071934127905179083", "1320267947849490361205695",
}
fmt.Println("\nNumber Has no >= 2 digit palindromes")
for _, num := range nums {
tmp := substrings(num)
var ss []string
for _, t := range tmp {
if len(t) > 1 {
ss = append(ss, t)
}
}
none := true
for _, s := range ss {
if s == reversed(s) {
none = false
break
}
}
fmt.Printf("%-25s %t\n", num, none)
}
}
| USING: formatting io kernel math math.ranges present prettyprint
sequences sequences.extras sets ;
: dpal ( n -- seq )
present all-subseqs members [ dup reverse = ] filter ;
"Number Palindromes" print
100 125 [a..b] [ dup pprint bl bl bl bl bl dpal . ] each nl
"Number Has no >= 2 digit-palindromes?" print
{ 9 169 12769 1238769 123498769 12346098769 1234572098769
123456832098769 12345679432098769 1234567905432098769
123456790165432098769 83071934127905179083
1320267947849490361205695 }
[ dup dpal [ length 2 < ] reject empty? "%-25d %u\n" printf ]
each
|
Ensure the translated AutoHotKey code behaves exactly like the original C++ snippet. | #include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string/case_conv.hpp>
using namespace std;
using namespace boost;
typedef boost::tokenizer<boost::char_separator<char> > Tokenizer;
static const char_separator<char> sep(" ","#;,");
struct configs{
string fullname;
string favoritefruit;
bool needspelling;
bool seedsremoved;
vector<string> otherfamily;
} conf;
void parseLine(const string &line, configs &conf)
{
if (line[0] == '#' || line.empty())
return;
Tokenizer tokenizer(line, sep);
vector<string> tokens;
for (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)
tokens.push_back(*iter);
if (tokens[0] == ";"){
algorithm::to_lower(tokens[1]);
if (tokens[1] == "needspeeling")
conf.needspelling = false;
if (tokens[1] == "seedsremoved")
conf.seedsremoved = false;
}
algorithm::to_lower(tokens[0]);
if (tokens[0] == "needspeeling")
conf.needspelling = true;
if (tokens[0] == "seedsremoved")
conf.seedsremoved = true;
if (tokens[0] == "fullname"){
for (unsigned int i=1; i<tokens.size(); i++)
conf.fullname += tokens[i] + " ";
conf.fullname.erase(conf.fullname.size() -1, 1);
}
if (tokens[0] == "favouritefruit")
for (unsigned int i=1; i<tokens.size(); i++)
conf.favoritefruit += tokens[i];
if (tokens[0] == "otherfamily"){
unsigned int i=1;
string tmp;
while (i<=tokens.size()){
if ( i == tokens.size() || tokens[i] ==","){
tmp.erase(tmp.size()-1, 1);
conf.otherfamily.push_back(tmp);
tmp = "";
i++;
}
else{
tmp += tokens[i];
tmp += " ";
i++;
}
}
}
}
int _tmain(int argc, TCHAR* argv[])
{
if (argc != 2)
{
wstring tmp = argv[0];
wcout << L"Usage: " << tmp << L" <configfile.ini>" << endl;
return -1;
}
ifstream file (argv[1]);
if (file.is_open())
while(file.good())
{
char line[255];
file.getline(line, 255);
string linestring(line);
parseLine(linestring, conf);
}
else
{
cout << "Unable to open the file" << endl;
return -2;
}
cout << "Fullname= " << conf.fullname << endl;
cout << "Favorite Fruit= " << conf.favoritefruit << endl;
cout << "Need Spelling= " << (conf.needspelling?"True":"False") << endl;
cout << "Seed Removed= " << (conf.seedsremoved?"True":"False") << endl;
string otherFamily;
for (unsigned int i = 0; i < conf.otherfamily.size(); i++)
otherFamily += conf.otherfamily[i] + ", ";
otherFamily.erase(otherFamily.size()-2, 2);
cout << "Other Family= " << otherFamily << endl;
return 0;
}
|
data = %A_scriptdir%\rosettaconfig.txt
comma := ","
Loop, Read, %data%
{
if NOT (instr(A_LoopReadLine, "#") == 1 OR A_LoopReadLine == "")
{
if instr(A_LoopReadLine, "
{
parameter := RegExReplace(Substr(A_LoopReadLine,2), "^[ \s]+|[ \s]+$", "")
%parameter% = "1"
}
else
{
parameter := RegExReplace(A_LoopReadLine, "^[ \s]+|[ \s]+$", "")
if instr(parameter, A_Space)
{
value := substr(parameter, instr(parameter, A_Space)+1,999)
parameter := substr(parameter, 1, instr(parameter, A_Space)-1)
if (instr(value, ",") <> 0)
{
Loop, Parse, value, %comma% ,%A_Space%
%parameter%%A_Index% := A_Loopfield
}
else
%parameter% = %value%
}
else
%parameter% = "0"
}
}
}
msgbox, FULLNAME %fullname%`nFAVOURITEFRUIT %FAVOURITEFRUIT%`nNEEDSPEELING %NEEDSPEELING%`nSEEDSREMOVED %SEEDSREMOVED%`nOTHERFAMILY %OTHERFAMILY1% + %OTHERFAMILY2%
|
Change the programming language of this snippet from C++ to AutoHotKey without modifying what it does. | #include <iostream>
#include <string>
using namespace std;
int main() {
string dog = "Benjamin", Dog = "Samba", DOG = "Bernie";
cout << "The three dogs are named " << dog << ", " << Dog << ", and " << DOG << endl;
}
| dog := "Benjamin"
Dog := "Samba"
DOG := "Bernie"
MsgBox There is just one dog named %dOG%
|
Port the provided C++ code into AutoHotKey while preserving the original functionality. | #include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
const char* command_table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO "
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT "
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT "
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
class command {
public:
command(const std::string&, size_t);
const std::string& cmd() const { return cmd_; }
size_t min_length() const { return min_len_; }
bool match(const std::string&) const;
private:
std::string cmd_;
size_t min_len_;
};
command::command(const std::string& cmd, size_t min_len)
: cmd_(cmd), min_len_(min_len) {}
bool command::match(const std::string& str) const {
size_t olen = str.length();
return olen >= min_len_ && olen <= cmd_.length()
&& cmd_.compare(0, olen, str) == 0;
}
void uppercase(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
}
size_t get_min_length(const std::string& str) {
size_t len = 0, n = str.length();
while (len < n && std::isupper(static_cast<unsigned char>(str[len])))
++len;
return len;
}
class command_list {
public:
explicit command_list(const char*);
const command* find_command(const std::string&) const;
private:
std::vector<command> commands_;
};
command_list::command_list(const char* table) {
std::vector<command> commands;
std::istringstream is(table);
std::string word;
while (is >> word) {
size_t len = get_min_length(word);
uppercase(word);
commands_.push_back(command(word, len));
}
}
const command* command_list::find_command(const std::string& word) const {
auto iter = std::find_if(commands_.begin(), commands_.end(),
[&word](const command& cmd) { return cmd.match(word); });
return (iter != commands_.end()) ? &*iter : nullptr;
}
std::string test(const command_list& commands, const std::string& input) {
std::string output;
std::istringstream is(input);
std::string word;
while (is >> word) {
if (!output.empty())
output += ' ';
uppercase(word);
const command* cmd_ptr = commands.find_command(word);
if (cmd_ptr)
output += cmd_ptr->cmd();
else
output += "*error*";
}
return output;
}
int main() {
command_list commands(command_table);
std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin");
std::string output(test(commands, input));
std::cout << " input: " << input << '\n';
std::cout << "output: " << output << '\n';
return 0;
}
|
str =
(
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up
)
str := StrReplace(str,"`n")
comTable := StrSplit(RegExReplace(str, "\s+", " "), " ")
comTableCapsCount := []
for cmds in comTable
comTableCapsCount.push(StrLen(RegExReplace(comTable[cmds], "[a-z]")))
InputBox, abbrev, Command, Type in your command(s).`n If you have several commands`, leave spaces between them.
abbrev := Trim(abbrev)
StringLower, lowerCaseAbbrev, abbrev
abbrev := StrSplit(RegExReplace(abbrev, "\s+", " "), " ")
Loop % abbrev.MaxIndex() {
count := A_Index
found := false
for cmds in comTable {
command := SubStr(comTable[cmds], 1, StrLen(abbrev[count]))
StringLower, lowerCaseCommand, command
if (lowerCaseCommand = abbrev[count]) and (StrLen(abbrev[count]) >= comTableCapsCount[cmds]) {
StringUpper, foundCmd, % comTable[cmds]
found := true
}
}
if (found)
result .= " " foundCmd
else
result .= " *error*"
}
MsgBox % Trim(result)
|
Change the following C++ code into AutoHotKey without altering its purpose. | #include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
const char* command_table =
"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy "
"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find "
"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput "
"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO "
"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT "
"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT "
"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up";
class command {
public:
command(const std::string&, size_t);
const std::string& cmd() const { return cmd_; }
size_t min_length() const { return min_len_; }
bool match(const std::string&) const;
private:
std::string cmd_;
size_t min_len_;
};
command::command(const std::string& cmd, size_t min_len)
: cmd_(cmd), min_len_(min_len) {}
bool command::match(const std::string& str) const {
size_t olen = str.length();
return olen >= min_len_ && olen <= cmd_.length()
&& cmd_.compare(0, olen, str) == 0;
}
void uppercase(std::string& str) {
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
}
size_t get_min_length(const std::string& str) {
size_t len = 0, n = str.length();
while (len < n && std::isupper(static_cast<unsigned char>(str[len])))
++len;
return len;
}
class command_list {
public:
explicit command_list(const char*);
const command* find_command(const std::string&) const;
private:
std::vector<command> commands_;
};
command_list::command_list(const char* table) {
std::vector<command> commands;
std::istringstream is(table);
std::string word;
while (is >> word) {
size_t len = get_min_length(word);
uppercase(word);
commands_.push_back(command(word, len));
}
}
const command* command_list::find_command(const std::string& word) const {
auto iter = std::find_if(commands_.begin(), commands_.end(),
[&word](const command& cmd) { return cmd.match(word); });
return (iter != commands_.end()) ? &*iter : nullptr;
}
std::string test(const command_list& commands, const std::string& input) {
std::string output;
std::istringstream is(input);
std::string word;
while (is >> word) {
if (!output.empty())
output += ' ';
uppercase(word);
const command* cmd_ptr = commands.find_command(word);
if (cmd_ptr)
output += cmd_ptr->cmd();
else
output += "*error*";
}
return output;
}
int main() {
command_list commands(command_table);
std::string input("riG rePEAT copies put mo rest types fup. 6 poweRin");
std::string output(test(commands, input));
std::cout << " input: " << input << '\n';
std::cout << "output: " << output << '\n';
return 0;
}
|
str =
(
Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy
COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find
NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput
Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO
MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT
READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT
RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up
)
str := StrReplace(str,"`n")
comTable := StrSplit(RegExReplace(str, "\s+", " "), " ")
comTableCapsCount := []
for cmds in comTable
comTableCapsCount.push(StrLen(RegExReplace(comTable[cmds], "[a-z]")))
InputBox, abbrev, Command, Type in your command(s).`n If you have several commands`, leave spaces between them.
abbrev := Trim(abbrev)
StringLower, lowerCaseAbbrev, abbrev
abbrev := StrSplit(RegExReplace(abbrev, "\s+", " "), " ")
Loop % abbrev.MaxIndex() {
count := A_Index
found := false
for cmds in comTable {
command := SubStr(comTable[cmds], 1, StrLen(abbrev[count]))
StringLower, lowerCaseCommand, command
if (lowerCaseCommand = abbrev[count]) and (StrLen(abbrev[count]) >= comTableCapsCount[cmds]) {
StringUpper, foundCmd, % comTable[cmds]
found := true
}
}
if (found)
result .= " " foundCmd
else
result .= " *error*"
}
MsgBox % Trim(result)
|
Ensure the translated AutoHotKey code behaves exactly like the original C++ snippet. | #include <iostream>
#include <vector>
#include <set>
#include <algorithm>
template<typename T>
std::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {
std::set<T> resultset;
std::vector<T> result;
for (auto& list : ll)
for (auto& item : list)
resultset.insert(item);
for (auto& item : resultset)
result.push_back(item);
std::sort(result.begin(), result.end());
return result;
}
int main() {
std::vector<int> a = {5,1,3,8,9,4,8,7};
std::vector<int> b = {3,5,9,8,4};
std::vector<int> c = {1,3,7,9};
std::vector<std::vector<int>> nums = {a, b, c};
auto csl = common_sorted_list(nums);
for (auto n : csl) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
| Common_sorted_list(nums){
elements := [], output := []
for i, num in nums
for j, d in num
elements[d] := true
for val, bool in elements
output.push(val)
return output
}
|
Rewrite the snippet below in AutoHotKey so it works the same as the original C++ code. | #include <iostream>
#include <vector>
#include <set>
#include <algorithm>
template<typename T>
std::vector<T> common_sorted_list(const std::vector<std::vector<T>>& ll) {
std::set<T> resultset;
std::vector<T> result;
for (auto& list : ll)
for (auto& item : list)
resultset.insert(item);
for (auto& item : resultset)
result.push_back(item);
std::sort(result.begin(), result.end());
return result;
}
int main() {
std::vector<int> a = {5,1,3,8,9,4,8,7};
std::vector<int> b = {3,5,9,8,4};
std::vector<int> c = {1,3,7,9};
std::vector<std::vector<int>> nums = {a, b, c};
auto csl = common_sorted_list(nums);
for (auto n : csl) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
| Common_sorted_list(nums){
elements := [], output := []
for i, num in nums
for j, d in num
elements[d] := true
for val, bool in elements
output.push(val)
return output
}
|
Produce a language-to-language conversion: from C++ to AutoHotKey, same semantics. | #include <iostream>
#include <time.h>
using namespace std;
class stooge
{
public:
void sort( int* arr, int start, int end )
{
if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );
int n = end - start; if( n > 2 )
{
n /= 3; sort( arr, start, end - n );
sort( arr, start + n, end ); sort( arr, start, end - n );
}
}
};
int main( int argc, char* argv[] )
{
srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80;
cout << "before:\n";
for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20; cout << a[x] << " "; }
s.sort( a, 0, m ); cout << "\n\nafter:\n";
for( int x = 0; x < m; x++ ) cout << a[x] << " "; cout << "\n\n";
return system( "pause" );
}
| StoogeSort(L, i:=1, j:=""){
if !j
j := L.MaxIndex()
if (L[j] < L[i]){
temp := L[i]
L[i] := L[j]
L[j] := temp
}
if (j - i > 1){
t := floor((j - i + 1)/3)
StoogeSort(L, i, j-t)
StoogeSort(L, i+t, j)
StoogeSort(L, i, j-t)
}
return L
}
|
Maintain the same structure and functionality when rewriting this code in AutoHotKey. | #include <time.h>
#include <iostream>
using namespace std;
const int MAX = 126;
class shell
{
public:
shell()
{ _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }
void sort( int* a, int count )
{
_cnt = count;
for( int x = 0; x < 9; x++ )
if( count > _gap[x] )
{ _idx = x; break; }
sortIt( a );
}
private:
void sortIt( int* arr )
{
bool sorted = false;
while( true )
{
sorted = true;
int st = 0;
for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )
{
if( arr[st] > arr[x] )
{ swap( arr[st], arr[x] ); sorted = false; }
st = x;
}
if( ++_idx >= 8 ) _idx = 8;
if( sorted && _idx == 8 ) break;
}
}
void swap( int& a, int& b ) { int t = a; a = b; b = t; }
int _gap[9], _idx, _cnt;
};
int main( int argc, char* argv[] )
{
srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];
for( int x = 0; x < MAX; x++ )
arr[x] = rand() % MAX - rand() % MAX;
cout << " Before: \n=========\n";
for( int x = 0; x < 7; x++ )
{
for( int a = 0; a < 18; a++ )
{ cout << arr[x * 18 + a] << " "; }
cout << endl;
}
cout << endl; shell s; s.sort( arr, MAX );
cout << " After: \n========\n";
for( int x = 0; x < 7; x++ )
{
for( int a = 0; a < 18; a++ )
{ cout << arr[x * 18 + a] << " "; }
cout << endl;
}
cout << endl << endl; return system( "pause" );
}
| MsgBox % ShellSort("")
MsgBox % ShellSort("xxx")
MsgBox % ShellSort("3,2,1")
MsgBox % ShellSort("dog,000000,xx,cat,pile,abcde,1,cat,zz,xx,z")
MsgBox % ShellSort("12,11,10,9,8,4,5,6,7,3,2,1,10,13,14,15,19,17,18,16,20,10")
ShellSort(var) {
StringSplit a, var, `,
inc := a0
While inc:=round(inc/2.2)
Loop % a0-inc {
i := A_Index+inc, t := a%i%, j := i, k := j-inc
While j > inc && a%k% > t
a%j% := a%k%, j := k, k -= inc
a%j% := t
}
Loop % a0
s .= "," . a%A_Index%
Return SubStr(s,2)
}
|
Produce a language-to-language conversion: from C++ to AutoHotKey, same semantics. | #include <string>
#include <fstream>
#include <iostream>
int main( ) {
std::cout << "Which file do you want to look at ?\n" ;
std::string input ;
std::getline( std::cin , input ) ;
std::ifstream infile( input.c_str( ) , std::ios::in ) ;
std::string file( input ) ;
std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ;
std::getline( std::cin , input ) ;
int linenumber = std::stoi( input ) ;
int lines_read = 0 ;
std::string line ;
if ( infile.is_open( ) ) {
while ( infile ) {
getline( infile , line ) ;
lines_read++ ;
if ( lines_read == linenumber ) {
std::cout << line << std::endl ;
break ;
}
}
infile.close( ) ;
if ( lines_read < linenumber )
std::cout << "No " << linenumber << " lines in " << file << " !\n" ;
return 0 ;
}
else {
std::cerr << "Could not find file " << file << " !\n" ;
return 1 ;
}
}
| FileReadLine, OutputVar, filename.txt, 7
if ErrorLevel
MsgBox, There was an error reading the 7th line of the file
|
Change the following C++ code into AutoHotKey without altering its purpose. | #include <string>
#include <fstream>
#include <iostream>
int main( ) {
std::cout << "Which file do you want to look at ?\n" ;
std::string input ;
std::getline( std::cin , input ) ;
std::ifstream infile( input.c_str( ) , std::ios::in ) ;
std::string file( input ) ;
std::cout << "Which file line do you want to see ? ( Give a number > 0 ) ?\n" ;
std::getline( std::cin , input ) ;
int linenumber = std::stoi( input ) ;
int lines_read = 0 ;
std::string line ;
if ( infile.is_open( ) ) {
while ( infile ) {
getline( infile , line ) ;
lines_read++ ;
if ( lines_read == linenumber ) {
std::cout << line << std::endl ;
break ;
}
}
infile.close( ) ;
if ( lines_read < linenumber )
std::cout << "No " << linenumber << " lines in " << file << " !\n" ;
return 0 ;
}
else {
std::cerr << "Could not find file " << file << " !\n" ;
return 1 ;
}
}
| FileReadLine, OutputVar, filename.txt, 7
if ErrorLevel
MsgBox, There was an error reading the 7th line of the file
|
Port the provided C++ code into AutoHotKey while preserving the original functionality. | #include <QByteArray>
#include <iostream>
int main( ) {
QByteArray text ( "http:
QByteArray encoded( text.toPercentEncoding( ) ) ;
std::cout << encoded.data( ) << '\n' ;
return 0 ;
}
| MsgBox, % UriEncode("http://foo bar/")
UriEncode(Uri)
{
VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0)
StrPut(Uri, &Var, "UTF-8")
f := A_FormatInteger
SetFormat, IntegerFast, H
While Code := NumGet(Var, A_Index - 1, "UChar")
If (Code >= 0x30 && Code <= 0x39
|| Code >= 0x41 && Code <= 0x5A
|| Code >= 0x61 && Code <= 0x7A)
Res .= Chr(Code)
Else
Res .= "%" . SubStr(Code + 0x100, -1)
SetFormat, IntegerFast, %f%
Return, Res
}
|
Please provide an equivalent version of this C++ code in AutoHotKey. | #include <QByteArray>
#include <iostream>
int main( ) {
QByteArray text ( "http:
QByteArray encoded( text.toPercentEncoding( ) ) ;
std::cout << encoded.data( ) << '\n' ;
return 0 ;
}
| MsgBox, % UriEncode("http://foo bar/")
UriEncode(Uri)
{
VarSetCapacity(Var, StrPut(Uri, "UTF-8"), 0)
StrPut(Uri, &Var, "UTF-8")
f := A_FormatInteger
SetFormat, IntegerFast, H
While Code := NumGet(Var, A_Index - 1, "UChar")
If (Code >= 0x30 && Code <= 0x39
|| Code >= 0x41 && Code <= 0x5A
|| Code >= 0x61 && Code <= 0x7A)
Res .= Chr(Code)
Else
Res .= "%" . SubStr(Code + 0x100, -1)
SetFormat, IntegerFast, %f%
Return, Res
}
|
Write a version of this C++ function in AutoHotKey with identical behavior. | #include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <limits>
#include <numeric>
#include <sstream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type value)
: rows_(rows), columns_(columns), elements_(rows * columns, value) {}
matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<scalar_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const scalar_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
scalar_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
private:
size_t rows_;
size_t columns_;
std::vector<scalar_type> elements_;
};
template <typename scalar_type>
void print(std::wostream& out, const matrix<scalar_type>& a) {
const wchar_t* box_top_left = L"\x23a1";
const wchar_t* box_top_right = L"\x23a4";
const wchar_t* box_left = L"\x23a2";
const wchar_t* box_right = L"\x23a5";
const wchar_t* box_bottom_left = L"\x23a3";
const wchar_t* box_bottom_right = L"\x23a6";
const int precision = 5;
size_t rows = a.rows(), columns = a.columns();
std::vector<size_t> width(columns);
for (size_t column = 0; column < columns; ++column) {
size_t max_width = 0;
for (size_t row = 0; row < rows; ++row) {
std::ostringstream str;
str << std::fixed << std::setprecision(precision) << a(row, column);
max_width = std::max(max_width, str.str().length());
}
width[column] = max_width;
}
out << std::fixed << std::setprecision(precision);
for (size_t row = 0; row < rows; ++row) {
const bool top(row == 0), bottom(row + 1 == rows);
out << (top ? box_top_left : (bottom ? box_bottom_left : box_left));
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << L' ';
out << std::setw(width[column]) << a(row, column);
}
out << (top ? box_top_right : (bottom ? box_bottom_right : box_right));
out << L'\n';
}
}
template <typename scalar_type>
auto lu_decompose(const matrix<scalar_type>& input) {
assert(input.rows() == input.columns());
size_t n = input.rows();
std::vector<size_t> perm(n);
std::iota(perm.begin(), perm.end(), 0);
matrix<scalar_type> lower(n, n);
matrix<scalar_type> upper(n, n);
matrix<scalar_type> input1(input);
for (size_t j = 0; j < n; ++j) {
size_t max_index = j;
scalar_type max_value = 0;
for (size_t i = j; i < n; ++i) {
scalar_type value = std::abs(input1(perm[i], j));
if (value > max_value) {
max_index = i;
max_value = value;
}
}
if (max_value <= std::numeric_limits<scalar_type>::epsilon())
throw std::runtime_error("matrix is singular");
if (j != max_index)
std::swap(perm[j], perm[max_index]);
size_t jj = perm[j];
for (size_t i = j + 1; i < n; ++i) {
size_t ii = perm[i];
input1(ii, j) /= input1(jj, j);
for (size_t k = j + 1; k < n; ++k)
input1(ii, k) -= input1(ii, j) * input1(jj, k);
}
}
for (size_t j = 0; j < n; ++j) {
lower(j, j) = 1;
for (size_t i = j + 1; i < n; ++i)
lower(i, j) = input1(perm[i], j);
for (size_t i = 0; i <= j; ++i)
upper(i, j) = input1(perm[i], j);
}
matrix<scalar_type> pivot(n, n);
for (size_t i = 0; i < n; ++i)
pivot(i, perm[i]) = 1;
return std::make_tuple(lower, upper, pivot);
}
template <typename scalar_type>
void show_lu_decomposition(const matrix<scalar_type>& input) {
try {
std::wcout << L"A\n";
print(std::wcout, input);
auto result(lu_decompose(input));
std::wcout << L"\nL\n";
print(std::wcout, std::get<0>(result));
std::wcout << L"\nU\n";
print(std::wcout, std::get<1>(result));
std::wcout << L"\nP\n";
print(std::wcout, std::get<2>(result));
} catch (const std::exception& ex) {
std::cerr << ex.what() << '\n';
}
}
int main() {
std::wcout.imbue(std::locale(""));
std::wcout << L"Example 1:\n";
matrix<double> matrix1(3, 3,
{{1, 3, 5},
{2, 4, 7},
{1, 1, 0}});
show_lu_decomposition(matrix1);
std::wcout << '\n';
std::wcout << L"Example 2:\n";
matrix<double> matrix2(4, 4,
{{11, 9, 24, 2},
{1, 5, 2, 6},
{3, 17, 18, 1},
{2, 5, 7, 1}});
show_lu_decomposition(matrix2);
std::wcout << '\n';
std::wcout << L"Example 3:\n";
matrix<double> matrix3(3, 3,
{{-5, -6, -3},
{-1, 0, -2},
{-3, -4, -7}});
show_lu_decomposition(matrix3);
std::wcout << '\n';
std::wcout << L"Example 4:\n";
matrix<double> matrix4(3, 3,
{{1, 2, 3},
{4, 5, 6},
{7, 8, 9}});
show_lu_decomposition(matrix4);
return 0;
}
|
LU_decomposition(A){
P := Pivot(A)
A_ := Multiply_Matrix(P, A)
U := [], L := [], n := A_.Count()
loop % n {
i := A_Index
loop % n {
j := A_Index
Sigma := 0, k := 1
while (k <= i-1)
Sigma += (U[k, j] * L[i, k]), k++
U[i, j] := A_[i, j] - Sigma
Sigma := 0, k := 1
while (k <= j-1)
Sigma += (U[k, j] * L[i, k]), k++
L[i, j] := (A_[i, j] - Sigma) / U[j, j]
}
}
return [L, U, P]
}
Pivot(M){
n := M.Count(), P := [], i := 0
while (i++ < n){
P.push([])
j := 0
while (j++ < n)
P[i].push(i=j ? 1 : 0)
}
i := 0
while (i++ < n){
maxm := M[i, i], row := i, j := i
while (j++ < n)
if (M[j, i] > maxm)
maxm := M[j, i], row := j
if (i != row)
tmp := P[i], P[i] := P[row], P[row] := tmp
}
return P
}
Multiply_Matrix(A,B){
if (A[1].Count() <> B.Count())
return
RCols := A[1].Count()>B[1].Count()?A[1].Count():B[1].Count()
RRows := A.Count()>B.Count()?A.Count():B.Count(), R := []
Loop, % RRows {
RRow:=A_Index
loop, % RCols {
RCol:=A_Index, v := 0
loop % A[1].Count()
col := A_Index, v += A[RRow, col] * B[col,RCol]
R[RRow,RCol] := v
}
}
return R
}
ShowMatrix(L, f:=3){
for r, obj in L{
row := ""
for c, v in obj
row .= Format("{:." f "f}", v) ", "
output .= "[" trim(row, ", ") "]`n,"
}
return "[" Trim(output, "`n,") "]"
}
|
Keep all operations the same but rewrite the snippet in AutoHotKey. | #include <vector>
#include <algorithm>
#include <string>
template <class T>
struct sort_table_functor {
typedef bool (*CompFun)(const T &, const T &);
const CompFun ordering;
const int column;
const bool reverse;
sort_table_functor(CompFun o, int c, bool r) :
ordering(o), column(c), reverse(r) { }
bool operator()(const std::vector<T> &x, const std::vector<T> &y) const {
const T &a = x[column],
&b = y[column];
return reverse ? ordering(b, a)
: ordering(a, b);
}
};
template <class T>
bool myLess(const T &x, const T &y) { return x < y; }
template <class T>
void sort_table(std::vector<std::vector<T> > &table,
int column = 0, bool reverse = false,
bool (*ordering)(const T &, const T &) = myLess) {
std::sort(table.begin(), table.end(),
sort_table_functor<T>(ordering, column, reverse));
}
#include <iostream>
template <class T>
void print_matrix(std::vector<std::vector<T> > &data) {
for () {
for (int j = 0; j < 3; j++)
std::cout << data[i][j] << "\t";
std::cout << std::endl;
}
}
bool desc_len_comparator(const std::string &x, const std::string &y) {
return x.length() > y.length();
}
int main() {
std::string data_array[3][3] =
{
{"a", "b", "c"},
{"", "q", "z"},
{"zap", "zip", "Zot"}
};
std::vector<std::vector<std::string> > data_orig;
for (int i = 0; i < 3; i++) {
std::vector<std::string> row;
for (int j = 0; j < 3; j++)
row.push_back(data_array[i][j]);
data_orig.push_back(row);
}
print_matrix(data_orig);
std::vector<std::vector<std::string> > data = data_orig;
sort_table(data);
print_matrix(data);
data = data_orig;
sort_table(data, 2);
print_matrix(data);
data = data_orig;
sort_table(data, 1);
print_matrix(data);
data = data_orig;
sort_table(data, 1, true);
print_matrix(data);
data = data_orig;
sort_table(data, 0, false, desc_len_comparator);
print_matrix(data);
return 0;
}
| Gosub start
sort_table("Text", column := 2, reverse := 1)
Sleep, 2000
sort_table("Integer", column := 2, reverse := 1)
Return
start:
Gui, Add, ListView, r20 w200, 1|2|3
data =
(
1,2,3
b,q,z
c,z,z
)
Loop, Parse, data, `n
{
StringSplit, row, A_LoopField, `,
LV_Add(row, row1, row2, row3)
}
LV_ModifyCol(50)
Gui, Show
Return
sort_table(ordering = "Text", column = 0, reverse = 0)
{
If reverse
desc = desc
LV_ModifyCol(column, "sort" . desc . " " . ordering)
}
GuiClose:
ExitApp
|
Port the provided C++ code into AutoHotKey while preserving the original functionality. | #include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <iomanip>
int main( ) {
std::vector<double> input( 11 ) , results( 11 ) ;
std::cout << "Please enter 11 numbers!\n" ;
for ( int i = 0 ; i < input.size( ) ; i++ )
std::cin >> input[i];
std::transform( input.begin( ) , input.end( ) , results.begin( ) ,
[ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;
for ( int i = 10 ; i > -1 ; i-- ) {
std::cout << "f( " << std::setw( 3 ) << input[ i ] << " ) : " ;
if ( results[ i ] > 400 )
std::cout << "too large!" ;
else
std::cout << results[ i ] << " !" ;
std::cout << std::endl ;
}
return 0 ;
}
| seq := [1,2,3,4,5,6,7,8,9,10,11]
MsgBox % result := TPK(seq, 400)
return
TPK(s, num){
for i, v in reverse(s)
res .= v . " : " . ((x:=f(v)) > num ? "OVERFLOW" : x ) . "`n"
return res
}
reverse(s){
Loop % s.Count()
s.InsertAt(A_Index, s.pop())
return s
}
f(x){
return Sqrt(x) + 5* (x**3)
}
|
Translate the given C++ code snippet into AutoHotKey without altering its behavior. | #include <iostream>
#include <ctime>
class CRateState
{
protected:
time_t m_lastFlush;
time_t m_period;
size_t m_tickCount;
public:
CRateState(time_t period);
void Tick();
};
CRateState::CRateState(time_t period) : m_lastFlush(std::time(NULL)),
m_period(period),
m_tickCount(0)
{ }
void CRateState::Tick()
{
m_tickCount++;
time_t now = std::time(NULL);
if((now - m_lastFlush) >= m_period)
{
size_t tps = 0.0;
if(m_tickCount > 0)
tps = m_tickCount / (now - m_lastFlush);
std::cout << tps << " tics per second" << std::endl;
m_tickCount = 0;
m_lastFlush = now;
}
}
void something_we_do()
{
volatile size_t anchor = 0;
for(size_t x = 0; x < 0xffff; ++x)
{
anchor = x;
}
}
int main()
{
time_t start = std::time(NULL);
CRateState rateWatch(5);
for(time_t latest = start; (latest - start) < 20; latest = std::time(NULL))
{
something_we_do();
rateWatch.Tick();
}
return 0;
}
| SetBatchLines, -1
Tick := A_TickCount
Loop, 1000000 {
Random, x, 1, 1000000
Random, y, 1, 1000000
gcd(x, y)
}
t := A_TickCount - Tick
MsgBox, % t / 1000 " Seconds elapsed.`n" Round(1 / (t / 1000000000), 0) " Loop iterations per second."
gcd(a, b) {
while b
t := b, b := Mod(a, b), a := t
return, a
}
|
Port the following code from C++ to AutoHotKey with equivalent syntax and logic. | #include <iostream>
#include <vector>
template<typename T>
T sum_below_diagonal(const std::vector<std::vector<T>>& matrix) {
T sum = 0;
for (std::size_t y = 0; y < matrix.size(); y++)
for (std::size_t x = 0; x < matrix[y].size() && x < y; x++)
sum += matrix[y][x];
return sum;
}
int main() {
std::vector<std::vector<int>> matrix = {
{1,3,7,8,10},
{2,4,16,14,4},
{3,1,9,18,11},
{12,14,17,18,20},
{7,1,3,9,5}
};
std::cout << sum_below_diagonal(matrix) << std::endl;
return 0;
}
| matrx :=[[1,3,7,8,10]
,[2,4,16,14,4]
,[3,1,9,18,11]
,[12,14,17,18,20]
,[7,1,3,9,5]]
sumA := sumB := sumD := sumAll := 0
for r, obj in matrx
for c, val in obj
sumAll += val
,sumA += r<c ? val : 0
,sumB += r>c ? val : 0
,sumD += r=c ? val : 0
MsgBox % result := "sum above diagonal = " sumA
. "`nsum below diagonal = " sumB
. "`nsum on diagonal = " sumD
. "`nsum all = " sumAll
|
Preserve the algorithm and functionality while converting the code from C++ to AutoHotKey. | #include <windows.h>
#include <string>
#include <iostream>
const int BMP_SIZE = 720, LINE_LEN = 120, BORDER = 100;
class myBitmap {
public:
myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
~myBitmap() {
DeleteObject( pen ); DeleteObject( brush );
DeleteDC( hdc ); DeleteObject( bmp );
}
bool create( int w, int h ) {
BITMAPINFO bi;
ZeroMemory( &bi, sizeof( bi ) );
bi.bmiHeader.biSize = sizeof( bi.bmiHeader );
bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biWidth = w;
bi.bmiHeader.biHeight = -h;
HDC dc = GetDC( GetConsoleWindow() );
bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
if( !bmp ) return false;
hdc = CreateCompatibleDC( dc );
SelectObject( hdc, bmp );
ReleaseDC( GetConsoleWindow(), dc );
width = w; height = h;
return true;
}
void clear( BYTE clr = 0 ) {
memset( pBits, clr, width * height * sizeof( DWORD ) );
}
void setBrushColor( DWORD bClr ) {
if( brush ) DeleteObject( brush );
brush = CreateSolidBrush( bClr );
SelectObject( hdc, brush );
}
void setPenColor( DWORD c ) {
clr = c; createPen();
}
void setPenWidth( int w ) {
wid = w; createPen();
}
void saveBitmap( std::string path ) {
BITMAPFILEHEADER fileheader;
BITMAPINFO infoheader;
BITMAP bitmap;
DWORD wb;
GetObject( bmp, sizeof( bitmap ), &bitmap );
DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );
infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
infoheader.bmiHeader.biCompression = BI_RGB;
infoheader.bmiHeader.biPlanes = 1;
infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
infoheader.bmiHeader.biHeight = bitmap.bmHeight;
infoheader.bmiHeader.biWidth = bitmap.bmWidth;
infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );
fileheader.bfType = 0x4D42;
fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
fileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;
GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );
HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL );
WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
CloseHandle( file );
delete [] dwpBits;
}
HDC getDC() const { return hdc; }
int getWidth() const { return width; }
int getHeight() const { return height; }
private:
void createPen() {
if( pen ) DeleteObject( pen );
pen = CreatePen( PS_SOLID, wid, clr );
SelectObject( hdc, pen );
}
HBITMAP bmp; HDC hdc;
HPEN pen; HBRUSH brush;
void *pBits; int width, height, wid;
DWORD clr;
};
class tree {
public:
tree() {
bmp.create( BMP_SIZE, BMP_SIZE ); bmp.clear();
clr[0] = RGB( 90, 30, 0 ); clr[1] = RGB( 255, 255, 0 );
clr[2] = RGB( 0, 255, 255 ); clr[3] = RGB( 255, 255, 255 );
clr[4] = RGB( 255, 0, 0 ); clr[5] = RGB( 0, 100, 190 );
}
void draw( int it, POINT a, POINT b ) {
if( !it ) return;
bmp.setPenColor( clr[it % 6] );
POINT df = { b.x - a.x, a.y - b.y }; POINT c = { b.x - df.y, b.y - df.x };
POINT d = { a.x - df.y, a.y - df.x };
POINT e = { d.x + ( ( df.x - df.y ) / 2 ), d.y - ( ( df.x + df.y ) / 2 )};
drawSqr( a, b, c, d ); draw( it - 1, d, e ); draw( it - 1, e, c );
}
void save( std::string p ) { bmp.saveBitmap( p ); }
private:
void drawSqr( POINT a, POINT b, POINT c, POINT d ) {
HDC dc = bmp.getDC();
MoveToEx( dc, a.x, a.y, NULL );
LineTo( dc, b.x, b.y );
LineTo( dc, c.x, c.y );
LineTo( dc, d.x, d.y );
LineTo( dc, a.x, a.y );
}
myBitmap bmp;
DWORD clr[6];
};
int main( int argc, char* argv[] ) {
POINT ptA = { ( BMP_SIZE >> 1 ) - ( LINE_LEN >> 1 ), BMP_SIZE - BORDER },
ptB = { ptA.x + LINE_LEN, ptA.y };
tree t; t.draw( 12, ptA, ptB );
t.save( "?:/pt.bmp" );
return 0;
}
| pToken := Gdip_Startup()
gdip1()
Pythagoras_tree(600, 600, 712, 600, 1)
UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)
OnExit, Exit
return
Pythagoras_tree(x1, y1, x2, y2, depth){
global G, hwnd1, hdc, Width, Height
if (depth > 7)
Return
Pen := Gdip_CreatePen(0xFF808080, 1)
Brush1 := Gdip_BrushCreateSolid(0xFFFFE600)
Brush2 := Gdip_BrushCreateSolid(0xFFFAFF00)
Brush3 := Gdip_BrushCreateSolid(0xFFDBFF00)
Brush4 := Gdip_BrushCreateSolid(0xFFDBFF00)
Brush5 := Gdip_BrushCreateSolid(0xFF9EFF00)
Brush6 := Gdip_BrushCreateSolid(0xFF80FF00)
Brush7 := Gdip_BrushCreateSolid(0xFF60FF00)
dx := x2 - x1 , dy := y1 - y2
x3 := x2 - dy , y3 := y2 - dx
x4 := x1 - dy , y4 := y1 - dx
x5 := x4 + (dx - dy) / 2
y5 := y4 - (dx + dy) / 2
Gdip_FillPolygon(G, Brush%depth%, x1 "," y1 "|" x2 "," y2 "|" x3 "," y3 "|" x4 "," y4 "|" x1 "," y1)
Gdip_FillPolygon(G, Brush%depth%, x4 "," y4 "|" x5 "," y5 "|" x3 "," y3 "|" x4 "," y4)
Gdip_DrawLines(G, Pen, x1 "," y1 "|" x2 "," y2 "|" x3 "," y3 "|" x4 "," y4 "|" x1 "," y1)
Gdip_DrawLines(G, Pen, x4 "," y4 "|" x5 "," y5 "|" x3 "," y3 "|" x4 "," y4)
Pythagoras_tree(x4, y4, x5, y5, depth+1)
Pythagoras_tree(x5, y5, x3, y3, depth+1)
}
gdip1(){
global
Width := A_ScreenWidth, Height := A_ScreenHeight
Gui, 1: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop
Gui, 1: Show, NA
hwnd1 := WinExist()
OnMessage(0x201, "WM_LBUTTONDOWN")
hbm := CreateDIBSection(Width, Height)
hdc := CreateCompatibleDC()
obm := SelectObject(hdc, hbm)
G := Gdip_GraphicsFromHDC(hdc)
Gdip_SetSmoothingMode(G, 4)
}
WM_LBUTTONDOWN(){
PostMessage, 0xA1, 2
}
gdip2(){
global
Gdip_DeleteBrush(pBrush)
Gdip_DeletePen(pPen)
SelectObject(hdc, obm)
DeleteObject(hbm)
DeleteDC(hdc)
Gdip_DeleteGraphics(G)
}
exit:
gdip2()
ExitApp
return
|
Translate this program into AutoHotKey but keep the logic exactly as in C++. | #include <string>
#include <vector>
#include <boost/regex.hpp>
bool is_repstring( const std::string & teststring , std::string & repunit ) {
std::string regex( "^(.+)\\1+(.*)$" ) ;
boost::regex e ( regex ) ;
boost::smatch what ;
if ( boost::regex_match( teststring , what , e , boost::match_extra ) ) {
std::string firstbracket( what[1 ] ) ;
std::string secondbracket( what[ 2 ] ) ;
if ( firstbracket.length( ) >= secondbracket.length( ) &&
firstbracket.find( secondbracket ) != std::string::npos ) {
repunit = firstbracket ;
}
}
return !repunit.empty( ) ;
}
int main( ) {
std::vector<std::string> teststrings { "1001110011" , "1110111011" , "0010010010" ,
"1010101010" , "1111111111" , "0100101101" , "0100100" , "101" , "11" , "00" , "1" } ;
std::string theRep ;
for ( std::string myString : teststrings ) {
if ( is_repstring( myString , theRep ) ) {
std::cout << myString << " is a rep string! Here is a repeating string:\n" ;
std::cout << theRep << " " ;
}
else {
std::cout << myString << " is no rep string!" ;
}
theRep.clear( ) ;
std::cout << std::endl ;
}
return 0 ;
}
| In := ["1001110011", "1110111011", "0010010010", "1010101010"
, "1111111111", "0100101101", "0100100", "101", "11", "00", "1"]
for k, v in In
Out .= RepString(v) "`t" v "`n"
MsgBox, % Out
RepString(s) {
Loop, % StrLen(s) // 2 {
i := A_Index
Loop, Parse, s
{
pos := Mod(A_Index, i)
if (A_LoopField != SubStr(s, !pos ? i : pos, 1))
continue, 2
}
return SubStr(s, 1, i)
}
return "N/A"
}
|
Convert the following code from C++ to AutoHotKey, ensuring the logic remains intact. | #include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
int topswops(int n) {
std::vector<int> list(n);
std::iota(std::begin(list), std::end(list), 1);
int max_steps = 0;
do {
auto temp_list = list;
for (int steps = 1; temp_list[0] != 1; ++steps) {
std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]);
if (steps > max_steps) max_steps = steps;
}
} while (std::next_permutation(std::begin(list), std::end(list)));
return max_steps;
}
int main() {
for (int i = 1; i <= 10; ++i) {
std::cout << i << ": " << topswops(i) << std::endl;
}
return 0;
}
| Topswops(Obj, n){
R := []
for i, val in obj{
if (i <=n)
res := val (A_Index=1?"":",") res
else
res .= "," val
}
Loop, Parse, res, `,
R[A_Index]:= A_LoopField
return R
}
|
Generate a AutoHotKey translation of this C++ snippet without changing its computational steps. | #include <iostream>
#define MAX 15
using namespace std;
int count_divisors(int n) {
int count = 0;
for (int i = 1; i * i <= n; ++i) {
if (!(n % i)) {
if (i == n / i)
count++;
else
count += 2;
}
}
return count;
}
int main() {
cout << "The first " << MAX << " terms of the sequence are:" << endl;
for (int i = 1, next = 1; next <= MAX; ++i) {
if (next == count_divisors(i)) {
cout << i << " ";
next++;
}
}
cout << endl;
return 0;
}
| MAX := 15
next := 1, i := 1
while (next <= MAX)
if (next = countDivisors(A_Index))
Res.= A_Index ", ", next++
MsgBox % "The first " MAX " terms of the sequence are:`n" Trim(res, ", ")
return
countDivisors(n){
while (A_Index**2 <= n)
if !Mod(n, A_Index)
count += (A_Index = n/A_Index) ? 1 : 2
return count
}
|
Change the following C++ code into AutoHotKey without altering its purpose. | #include <iostream>
#include <cctype>
#include <functional>
using namespace std;
bool odd()
{
function<void ()> prev = []{};
while(true) {
int c = cin.get();
if (!isalpha(c)) {
prev();
cout.put(c);
return c != '.';
}
prev = [=] { cout.put(c); prev(); };
}
}
bool even()
{
while(true) {
int c;
cout.put(c = cin.get());
if (!isalpha(c)) return c != '.';
}
}
int main()
{
bool e = false;
while( e ? odd() : even() ) e = !e;
return 0;
}
| str := "what,is,the
loop, parse, str
if (A_LoopField ~= "[[:punct:]]")
res .= A_LoopField, toggle:=!toggle
else
res := toggle ? RegExReplace(res, ".*[[:punct:]]\K", A_LoopField ) : res A_LoopField
MsgBox % res
|
Please provide an equivalent version of this C++ code in AutoHotKey. | #include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
std::map<char, int> _map;
std::vector<std::string> _result;
size_t longest = 0;
void make_sequence( std::string n ) {
_map.clear();
for( std::string::iterator i = n.begin(); i != n.end(); i++ )
_map.insert( std::make_pair( *i, _map[*i]++ ) );
std::string z;
for( std::map<char, int>::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) {
char c = ( *i ).second + 48;
z.append( 1, c );
z.append( 1, i->first );
}
if( longest <= z.length() ) {
longest = z.length();
if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) {
_result.push_back( z );
make_sequence( z );
}
}
}
int main( int argc, char* argv[] ) {
std::vector<std::string> tests;
tests.push_back( "9900" ); tests.push_back( "9090" ); tests.push_back( "9009" );
for( std::vector<std::string>::iterator i = tests.begin(); i != tests.end(); i++ ) {
make_sequence( *i );
std::cout << "[" << *i << "] Iterations: " << _result.size() + 1 << "\n";
for( std::vector<std::string>::iterator j = _result.begin(); j != _result.end(); j++ ) {
std::cout << *j << "\n";
}
std::cout << "\n\n";
}
return 0;
}
|
#NoEnv
SetBatchlines -1
ListLines Off
Process, Priority,, high
iterations := 0, seed := "Seeds: "
Loop 1000000
If (newIterations := CountSubString(list := ListSequence(A_Index), "`n")) > iterations
iterations := newiterations
,final := "`nIterations: " iterations+1 "`nSequence:`n`n" A_Index "`n" list
,seed := A_Index " "
else if (newIterations = iterations)
seed .= A_Index " "
MsgBox % "Seeds: " . seed . final
ListSequence(seed){
While !InStr("`n" . out, "`n" (d:=Describe(seed)) "`n")
out .= d "`n", seed := d
return out
}
Describe(n){
Loop 10
If (t:=CountSubString(n, 10-A_Index))
out .= t . (10-A_Index)
return out
}
CountSubstring(fullstring, substring){
StringReplace, junk, fullstring, %substring%, , UseErrorLevel
return errorlevel
}
|
Keep all operations the same but rewrite the snippet in AutoHotKey. |
#include <fstream>
#include <iostream>
#include <vector>
constexpr double sqrt3_2 = 0.86602540378444;
struct point {
double x;
double y;
};
std::vector<point> koch_next(const std::vector<point>& points) {
size_t size = points.size();
std::vector<point> output(4*(size - 1) + 1);
double x0, y0, x1, y1;
size_t j = 0;
for (size_t i = 0; i + 1 < size; ++i) {
x0 = points[i].x;
y0 = points[i].y;
x1 = points[i + 1].x;
y1 = points[i + 1].y;
double dy = y1 - y0;
double dx = x1 - x0;
output[j++] = {x0, y0};
output[j++] = {x0 + dx/3, y0 + dy/3};
output[j++] = {x0 + dx/2 - dy * sqrt3_2/3, y0 + dy/2 + dx * sqrt3_2/3};
output[j++] = {x0 + 2 * dx/3, y0 + 2 * dy/3};
}
output[j] = {x1, y1};
return output;
}
std::vector<point> koch_points(int size, int iterations) {
double length = size * sqrt3_2 * 0.95;
double x = (size - length)/2;
double y = size/2 - length * sqrt3_2/3;
std::vector<point> points{
{x, y},
{x + length/2, y + length * sqrt3_2},
{x + length, y},
{x, y}
};
for (int i = 0; i < iterations; ++i)
points = koch_next(points);
return points;
}
void koch_curve_svg(std::ostream& out, int size, int iterations) {
out << "<svg xmlns='http:
<< size << "' height='" << size << "'>\n";
out << "<rect width='100%' height='100%' fill='black'/>\n";
out << "<path stroke-width='1' stroke='white' fill='none' d='";
auto points(koch_points(size, iterations));
for (size_t i = 0, n = points.size(); i < n; ++i)
out << (i == 0 ? "M" : "L") << points[i].x << ',' << points[i].y << '\n';
out << "z'/>\n</svg>\n";
}
int main() {
std::ofstream out("koch_curve.svg");
if (!out) {
std::cerr << "Cannot open output file\n";
return EXIT_FAILURE;
}
koch_curve_svg(out, 600, 5);
return EXIT_SUCCESS;
}
| gdip1()
KochX := 0, KochY := 0
Koch(0, 0, A_ScreenWidth, A_ScreenHeight, 4, Arr:=[])
xmin := xmax := ymin := ymax := 0
for i, point in Arr
{
xmin := A_Index = 1 ? point.x : xmin < point.x ? xmin : point.x
xmax := point.x > xmax ? point.x : xmax
ymin := A_Index = 1 ? point.y : ymin < point.y ? ymin : point.y
ymax := point.y > ymax ? point.y : ymax
}
for i, point in Arr
points .= point.x - xmin + KochX "," point.y - ymin + KochY "|"
points := Trim(points, "|")
Gdip_DrawLines(G, pPen, Points)
UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)
return
Koch(x1, y1, x2, y2, iter, Arr) {
Pi := 3.141592653589793
angle := Pi / 3
x3 := (x1*2 + x2) / 3
y3 := (y1*2 + y2) / 3
x4 := (x1 + x2*2) / 3
y4 := (y1 + y2*2) / 3
x5 := x3 + (x4-x3)*Cos(angle) + (y4-y3)*Sin(angle)
y5 := y3 - (x4-x3)*Sin(angle) + (y4-y3)*Cos(angle)
if (iter > 0)
{
iter--
koch(x1, y1, x3, y3, iter, Arr)
koch(x3, y3, x5, y5, iter, Arr)
koch(x5, y5, x4, y4, iter, Arr)
koch(x4, y4, x2, y2, iter, Arr)
}
else
{
Arr[Arr.count()+1, "x"] := x1, Arr[Arr.count(), "y"] := y1
Arr[Arr.count()+1, "x"] := x3, Arr[Arr.count(), "y"] := y3
Arr[Arr.count()+1, "x"] := x5, Arr[Arr.count(), "y"] := y5
Arr[Arr.count()+1, "x"] := x4, Arr[Arr.count(), "y"] := y4
Arr[Arr.count()+1, "x"] := x2, Arr[Arr.count(), "y"] := y2
}
}
gdip1(){
global
If !pToken := Gdip_Startup()
{
MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
ExitApp
}
OnExit, Exit
Width := A_ScreenWidth, Height := A_ScreenHeight
Gui, 1: -Caption +E0x80000 +LastFound +OwnDialogs +Owner +AlwaysOnTop
Gui, 1: Show, NA
hwnd1 := WinExist()
hbm := CreateDIBSection(Width, Height)
hdc := CreateCompatibleDC()
obm := SelectObject(hdc, hbm)
G := Gdip_GraphicsFromHDC(hdc)
Gdip_SetSmoothingMode(G, 4)
pPen := Gdip_CreatePen(0xFFFF0000, 2)
}
gdip2(){
global
Gdip_DeleteBrush(pBrush)
Gdip_DeletePen(pPen)
SelectObject(hdc, obm)
DeleteObject(hbm)
DeleteDC(hdc)
Gdip_DeleteGraphics(G)
}
Exit:
gdip2()
Gdip_Shutdown(pToken)
ExitApp
Return
|
Produce a functionally identical AutoHotKey code for the snippet given in C++. | #include <iomanip>
#include <iostream>
bool equal_rises_and_falls(int n) {
int total = 0;
for (int previous_digit = -1; n > 0; n /= 10) {
int digit = n % 10;
if (previous_digit > digit)
++total;
else if (previous_digit >= 0 && previous_digit < digit)
--total;
previous_digit = digit;
}
return total == 0;
}
int main() {
const int limit1 = 200;
const int limit2 = 10000000;
int n = 0;
std::cout << "The first " << limit1 << " numbers in the sequence are:\n";
for (int count = 0; count < limit2; ) {
if (equal_rises_and_falls(++n)) {
++count;
if (count <= limit1)
std::cout << std::setw(3) << n << (count % 20 == 0 ? '\n' : ' ');
}
}
std::cout << "\nThe " << limit2 << "th number in the sequence is " << n << ".\n";
}
| limit1 := 200, limit2 := 10000000
count := 0, result1 := result1 := ""
loop{
num := A_Index
if !Rise_Fall(num)
continue
count++
if (count <= limit1)
result1 .= num . (Mod(count, 20) ? "`t" : "`n")
if (count = limit2){
result2 := num
break
}
if !mod(count, 10000)
ToolTip % count
}
ToolTip
MsgBox % "The first " limit1 " numbers in the sequence:`n" result1 "`nThe " limit2 " number in the sequence is: " result2
return
Rise_Fall(num){
rise := fall := 0
for i, n in StrSplit(num){
if (i=1)
prev := n
else if (n > prev)
rise++
else if (n < prev)
fall++
if (rise > (StrLen(num)-1) /2) || (fall > (StrLen(num)-1) /2)
return 0
prev := n
}
if (fall = rise)
return 1
}
|
Produce a language-to-language conversion: from C++ to AutoHotKey, same semantics. | #include <iostream>
typedef unsigned long long bigint;
using namespace std;
class sdn
{
public:
bool check( bigint n )
{
int cc = digitsCount( n );
return compare( n, cc );
}
void displayAll( bigint s )
{
for( bigint y = 1; y < s; y++ )
if( check( y ) )
cout << y << " is a Self-Describing Number." << endl;
}
private:
bool compare( bigint n, int cc )
{
bigint a;
while( cc )
{
cc--; a = n % 10;
if( dig[cc] != a ) return false;
n -= a; n /= 10;
}
return true;
}
int digitsCount( bigint n )
{
int cc = 0; bigint a;
memset( dig, 0, sizeof( dig ) );
while( n )
{
a = n % 10; dig[a]++;
cc++ ; n -= a; n /= 10;
}
return cc;
}
int dig[10];
};
int main( int argc, char* argv[] )
{
sdn s;
s. displayAll( 1000000000000 );
cout << endl << endl; system( "pause" );
bigint n;
while( true )
{
system( "cls" );
cout << "Enter a positive whole number ( 0 to QUIT ): "; cin >> n;
if( !n ) return 0;
if( s.check( n ) ) cout << n << " is";
else cout << n << " is NOT";
cout << " a Self-Describing Number!" << endl << endl;
system( "pause" );
}
return 0;
}
|
#NoEnv
SetBatchlines -1
ListLines Off
Process, Priority,, high
MsgBox % 2020 ": " IsSelfDescribing(2020) "`n" 1337 ": " IsSelfDescribing(1337) "`n" 1210 ": " IsSelfDescribing(1210)
Loop 100000000
If IsSelfDescribing(A_Index)
list .= A_Index "`n"
MsgBox % "Self-describing numbers < 100000000 :`n" . list
CountSubstring(fullstring, substring){
StringReplace, junk, fullstring, %substring%, , UseErrorLevel
return errorlevel
}
IsSelfDescribing(number){
Loop Parse, number
If Not CountSubString(number, A_Index-1) = A_LoopField
return false
return true
}
|
Ensure the translated AutoHotKey code behaves exactly like the original C++ snippet. | #include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
int hamming_distance(const std::string& str1, const std::string& str2) {
size_t len1 = str1.size();
size_t len2 = str2.size();
if (len1 != len2)
return 0;
int count = 0;
for (size_t i = 0; i < len1; ++i) {
if (str1[i] != str2[i])
++count;
if (count == 2)
break;
}
return count;
}
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string line;
std::vector<std::string> dictionary;
while (getline(in, line)) {
if (line.size() > 11)
dictionary.push_back(line);
}
std::cout << "Changeable words in " << filename << ":\n";
int n = 1;
for (const std::string& word1 : dictionary) {
for (const std::string& word2 : dictionary) {
if (hamming_distance(word1, word2) == 1)
std::cout << std::setw(2) << std::right << n++
<< ": " << std::setw(14) << std::left << word1
<< " -> " << word2 << '\n';
}
}
return EXIT_SUCCESS;
}
| FileRead, db, % A_Desktop "\unixdict.txt"
oWord := [], Found := []
for i, word in StrSplit(db, "`n", "`r")
if (StrLen(word) > 11)
oWord[word] := true
for word1 in oWord
for word2 in oWord
if Changeable(word1, word2) && !Found[word2]
found[word1] := true, result .= word1 . "`t<-> " word2 "`n"
MsgBox, 262144, , % result
return
Changeable(s1, s2) {
if (StrLen(s1) <> StrLen(s2))
return 0
for i, v in StrSplit(s1)
if (v = SubStr(s2, i, 1))
num++
return (StrLen(s1) - num = 1)
}
|
Ensure the translated AutoHotKey code behaves exactly like the original C++ snippet. | #include <iostream>
#include <string>
#include <vector>
const std::vector<std::pair<std::string, std::string>> conditions = {
{"Printer prints", "NNNNYYYY"},
{"A red light is flashing", "YYNNYYNN"},
{"Printer is recognized by computer", "NYNYNYNY"}
};
const std::vector<std::pair<std::string, std::string>> actions = {
{"Check the power cable", "NNYNNNNN"},
{"Check the printer-computer cable", "YNYNNNNN"},
{"Ensure printer software is installed", "YNYNYNYN"},
{"Check/replace ink", "YYNNNYNN"},
{"Check for paper jam", "NYNYNNNN"},
};
int main() {
const size_t nc = conditions.size();
const size_t na = actions.size();
const size_t nr = conditions[0].second.size();
const int np = 7;
auto answers = new bool[nc];
std::string input;
std::cout << "Please answer the following questions with a y or n:\n";
for (size_t c = 0; c < nc; c++) {
char ans;
do {
std::cout << conditions[c].first << "? ";
std::getline(std::cin, input);
ans = std::toupper(input[0]);
} while (ans != 'Y' && ans != 'N');
answers[c] = ans == 'Y';
}
std::cout << "Recommended action(s)\n";
for (size_t r = 0; r < nr; r++) {
for (size_t c = 0; c < nc; c++) {
char yn = answers[c] ? 'Y' : 'N';
if (conditions[c].second[r] != yn) {
goto outer;
}
}
if (r == np) {
std::cout << " None (no problem detected)\n";
} else {
for (auto action : actions) {
if (action.second[r] == 'Y') {
std::cout << " " << action.first << '\n';
}
}
}
break;
outer: {}
}
delete[] answers;
return 0;
}
| Conditions =
(
Printer does not print |Y|Y|Y|Y|N|N|N|N|
A red light is flashing |Y|Y|N|N|Y|Y|N|N|
Printer is unrecognized |Y|N|Y|N|Y|N|Y|N|
)
Actions=
(
Check the power cable | | |x| | | | | |
Check the printer-computer cable |x| |x| | | | | |
Ensure printer software is installed |x| |x| |x| |x| |
Check/replace ink |x|x| | |x|x| | |
Check for paper jam | |x| |x| | | | |
)
Condition:=[], Action:=[], Correlation:=[]
loop, parse, Conditions, `n
{
No:= A_Index, RegExMatch(A_LoopField, "^(.*?)\t+(.*)", m), Cond%No% := m1
for k, v in StrSplit(m2, "|")
Condition[No, k] := v="Y"?1:0
}
loop, parse, Actions, `n
{
No:= A_Index , RegExMatch(A_LoopField, "^(.*?)\t+(.*)", m), Act%No% := m1
for k, v in StrSplit(m2, "|")
Action[No, A_Index] := v="X"?1:0
}
loop, % Condition[1].MaxIndex()
{
j := A_Index, CondLine:=ActLine:=""
loop, % Condition.MaxIndex()
CondLine .= Condition[A_Index,j]
loop, % Action.MaxIndex()
ActLine.= Action[A_Index,j]?1:0
Correlation[CondLine]:=ActLine
}
Gui, font,, Courier
Gui, add, text, w456
Gui, add, text, wp h1 0x7 y+0
loop, parse, Conditions, `n
{
Gui, add, text, y+0 , % A_LoopField
Gui, add, text, wp h1 0x7 y+0
}
Gui, add, text, wp
Gui, add, text, wp h1 0x7 y+0
loop, parse, Actions, `n
{
Gui, add, text, y+0 , % A_LoopField
Gui, add, text, wp h1 0x7 y+0
}
Gui, add, text, wp
loop, % Condition.MaxIndex()
Gui, add, Checkbox,vC%A_Index% gSubmit wp h15, % Cond%A_Index%
Gui, add, text, wp , take the following actions(s):
AM := Action.MaxIndex()
Gui, add, Edit, vOutput ReadOnly r%AM% wp -TabStop
Gui, show
return
Submit:
Gui, Submit, NoHide
CondLine:=Res:=""
loop, % Condition.MaxIndex()
CondLine.= C%A_Index%
MyCorr := Correlation[CondLine]
loop, parse, MyCorr
if A_LoopField
Res .= Act%A_Index% "`n"
GuiControl,, Output, % Res
return
|
Generate an equivalent AutoHotKey version of this C++ code. | #include <iostream>
#include <fstream>
bool test(const std::string &line) {
unsigned int e = 0;
for (char c : line) {
switch(std::tolower(c)) {
case 'a': return false;
case 'i': return false;
case 'o': return false;
case 'u': return false;
case 'e': ++e;
}
}
return e > 3;
}
int main() {
std::ifstream dict{"unixdict.txt"};
if (! dict.is_open()) {
std::cerr << "Cannot open unixdict.txt\n";
return 3;
}
for (std::string line; std::getline(dict, line);) {
if (test(line)) std::cout << line << std::endl;
}
return 0;
}
| FileRead, db, % A_Desktop "\unixdict.txt"
vowelsLessE := ["a", "i", "o", "u"]
oRes := []
main:
for i, word in StrSplit(db, "`n", "`r")
{
for j, v in vowelsLessE
{
StrReplace(word, v, v, c)
if c
continue main
}
StrReplace(word, "e", "e", c)
if c > 3
result .= word "`n"
}
MsgBox, 262144, , % result
|
Rewrite the snippet below in AutoHotKey so it works the same as the original C++ code. | #include <concepts>
#include <iostream>
void PrintMatrix(std::predicate<int, int, int> auto f, int size)
{
for(int y = 0; y < size; y++)
{
for(int x = 0; x < size; x++)
{
std::cout << " " << f(x, y, size);
}
std::cout << "\n";
}
std::cout << "\n";
}
int main()
{
auto mosaic = [](int x, int y, [[maybe_unused]]int size)
{
return (x + y) % 2 == 0;
};
PrintMatrix(mosaic, 8);
PrintMatrix(mosaic, 9);
}
| for i, v in [8, 9]
result .= "Matrix Size: " v "*" v "`n" matrix2txt(mosaicMatrix(v)) "`n"
MsgBox % result
return
mosaicMatrix(size){
M := []
loop % size {
row := A_Index
loop % size
M[row, A_Index] := (Toggle:=!Toggle) ? 1 : 0
, toggle := (A_Index = size && size/2 = floor(size/2)) ? !toggle : toggle
}
return M
}
matrix2txt(M){
for row , obj in M {
for col, v in obj
result .= M[row, col] " "
result .= "`n"
}
return result
}
|
Can you help me rewrite this code in AutoHotKey instead of C++, keeping it the same logically? | #include <iostream>
#include <fstream>
#include <set>
#include <sstream>
#include <string>
#include <vector>
std::vector<std::string> longest_substrings_without_repeats(const std::string& str) {
size_t max_length = 0;
std::vector<std::string> result;
size_t length = str.size();
for (size_t offset = 0; offset < length; ++offset) {
std::set<char> characters;
size_t len = 0;
for (; offset + len < length; ++len) {
if (characters.find(str[offset + len]) != characters.end())
break;
characters.insert(str[offset + len]);
}
if (len > max_length) {
result.clear();
max_length = len;
}
if (len == max_length)
result.push_back(str.substr(offset, max_length));
}
return result;
}
void print_strings(const std::vector<std::string>& strings) {
std::cout << "[";
for (size_t i = 0, n = strings.size(); i < n; ++i) {
if (i > 0)
std::cout << ", ";
std::cout << '\'' << strings[i] << '\'';
}
std::cout << "]";
}
void test1() {
for (std::string str : { "xyzyabcybdfd", "xyzyab", "zzzzz", "a", "thisisastringtest", "" }) {
std::cout << "Input: '" << str << "'\nResult: ";
print_strings(longest_substrings_without_repeats(str));
std::cout << "\n\n";
}
}
std::string slurp(std::istream& in) {
std::ostringstream out;
out << in.rdbuf();
return out.str();
}
void test2(const std::string& filename) {
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return;
}
std::cout << "Longest substring with no repeats found in '" << filename << "': ";
print_strings(longest_substrings_without_repeats(slurp(in)));
std::cout << "\n";
}
int main() {
test1();
test2("unixdict.txt");
}
| LSWRC(str){
found := [], result := [], maxL := 0
if (StrLen(str) = 1)
result[str] := true
else while (StrLen(str) >= 2){
s := str
while StrLen(s) >= maxL{
if !(s ~= "(.).*\1"){
found[s] := true
maxL := maxL < StrLen(s) ? StrLen(s) : maxL
break
}
s := SubStr(s, 1, StrLen(s)-1)
}
str := SubStr(str, 2)
}
maxL := 0
for str in found
maxL := maxL < StrLen(str) ? StrLen(str) : maxL
for str in found
if (StrLen(str) = maxL)
result[str] := true
return result
}
|
Change the following C++ code into AutoHotKey without altering its purpose. | #include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
bool is_vowel(char ch) {
switch (ch) {
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
return true;
}
return false;
}
bool alternating_vowels_and_consonants(const std::string& str) {
for (size_t i = 1, len = str.size(); i < len; ++i) {
if (is_vowel(str[i]) == is_vowel(str[i - 1]))
return false;
}
return true;
}
int main(int argc, char** argv) {
const char* filename = argc < 2 ? "unixdict.txt" : argv[1];
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string line;
for (int n = 1; getline(in, line); ) {
if (line.size() > 9 && alternating_vowels_and_consonants(line))
std::cout << std::setw(2) << n++ << ": " << line << '\n';
}
return EXIT_SUCCESS;
}
| FileRead, db, % A_Desktop "\unixdict.txt"
vowels := {"a":1, "e":1, "i":1, "o":1, "u":1}, c := 0
Main:
for i, word in StrSplit(db, "`n", "`r")
{
if StrLen(word) < 10
continue
vCount := cCount := 0
while (letter := SubStr(word, A_Index, 1))
{
if vowels[letter]
vCount++, cCount:=0
else
vCount:=0, cCount++
if (vCount > 1 || cCount > 1)
continue main
}
c++
result .= word (Mod(c, 9) ? "`t" : "`n")
}
MsgBox, 262144, , % result
return
|
Change the programming language of this snippet from C++ to AutoHotKey without modifying what it does. | #include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
double arcLength(double radius, double angle1, double angle2) {
return (360.0 - abs(angle2 - angle1)) * M_PI * radius / 180.0;
}
int main() {
auto al = arcLength(10.0, 10.0, 120.0);
std::cout << "arc length: " << al << '\n';
return 0;
}
| MsgBox % result := arcLength(10, 10, 120)
return
arcLength(radius, angle1, angle2){
return (360 - Abs(angle2-angle1)) * (π := 3.141592653589793) * radius / 180
}
|
Produce a functionally identical AutoHotKey code for the snippet given in C++. | #include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
template <typename T>
void print(const std::vector<T>& v) {
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " "));
std::cout << '\n';
}
int main() {
std::vector<int> vec{1, 2, 3, 4, 5, 6, 7, 8, 9};
std::cout << "Before: ";
print(vec);
std::rotate(vec.begin(), vec.begin() + 3, vec.end());
std::cout << " After: ";
print(vec);
}
| Shift_list_elements(Arr, dir, n){
nums := Arr.Clone()
loop % n
if InStr(dir, "l")
nums.Push(nums.RemoveAt(1))
else
nums.InsertAt(1, nums.RemoveAt(nums.count()))
return nums
}
|
Ensure the translated AutoHotKey code behaves exactly like the original C++ snippet. | #include <concepts>
#include <iostream>
void PrintMatrix(std::predicate<int, int, int> auto f, int size)
{
for(int y = 0; y < size; y++)
{
for(int x = 0; x < size; x++)
{
std::cout << " " << f(x, y, size);
}
std::cout << "\n";
}
std::cout << "\n";
}
int main()
{
auto diagonals = [](int x, int y, int size)
{
return x == y || ((size - x - 1) == y);
};
PrintMatrix(diagonals, 8);
PrintMatrix(diagonals, 9);
}
| for i, v in [8, 9]
result .= "Matrix Size: " v "*" v "`n" matrix2txt(diagonalMatrix(v)) "`n"
MsgBox % result
return
diagonalMatrix(size){
M := []
loop % size {
row := A_Index
loop % size
M[row, A_Index] := (row = A_Index || row = size-A_Index+1) ? 1 : 0
}
return M
}
matrix2txt(M){
for row , obj in M {
for col, v in obj
result .= M[row, col] " "
result .= "`n"
}
return result
}
|
Write the same algorithm in AutoHotKey as shown in this C++ implementation. | #include <iostream>
#include <fstream>
int main() {
std::string word;
std::ifstream file("unixdict.txt");
if (!file) {
std::cerr << "Cannot open unixdict.txt" << std::endl;
return -1;
}
while (file >> word) {
if (word.length() > 11 && word.find("the") != std::string::npos)
std::cout << word << std::endl;
}
return 0;
}
| FileRead, wList, % A_Desktop "\unixdict.txt"
SubString := "the"
list := ContainSubStr(wList, SubString)
for i, v in list
result .= i "- " v "`n"
MsgBox, 262144, , % result
return
ContainSubStr(wList, SubString){
oRes := []
for i, w in StrSplit(wList, "`n", "`r")
{
if (StrLen(w) < 12 || !InStr(w, SubString))
continue
oRes.Push(w)
}
return oRes
}
|
Ensure the translated AutoHotKey code behaves exactly like the original C++ snippet. | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
std::string lcs(const std::vector<std::string>& strs) {
std::vector<std::string::const_reverse_iterator> backs;
std::string s;
if (strs.size() == 0) return "";
if (strs.size() == 1) return strs[0];
for (auto& str : strs) backs.push_back(str.crbegin());
while (backs[0] != strs[0].crend()) {
char ch = *backs[0]++;
for (std::size_t i = 1; i<strs.size(); i++) {
if (backs[i] == strs[i].crend()) goto done;
if (*backs[i] != ch) goto done;
backs[i]++;
}
s.push_back(ch);
}
done:
reverse(s.begin(), s.end());
return s;
}
void test(const std::vector<std::string>& strs) {
std::cout << "[";
for (std::size_t i = 0; i<strs.size(); i++) {
std::cout << '"' << strs[i] << '"';
if (i != strs.size()-1) std::cout << ", ";
}
std::cout << "] -> `" << lcs(strs) << "`\n";
}
int main() {
std::vector<std::string> t1 = {"baabababc", "baabc", "bbabc"};
std::vector<std::string> t2 = {"baabababc", "baabc", "bbazc"};
std::vector<std::string> t3 =
{"Sunday", "Monday", "Tuesday", "Wednesday", "Friday", "Saturday"};
std::vector<std::string> t4 = {"longest", "common", "suffix"};
std::vector<std::string> t5 = {""};
std::vector<std::string> t6 = {};
std::vector<std::string> t7 = {"foo", "foo", "foo", "foo"};
std::vector<std::vector<std::string>> tests = {t1,t2,t3,t4,t5,t6,t7};
for (auto t : tests) test(t);
return 0;
}
| Longest_common_suffix(data){
for num, v in StrSplit(data.1)
for i, word in data
if (SubStr(word, 1-num) <> SubStr(data.1, 1-num))
return num=1 ? "" : SubStr(word, 2-num)
return SubStr(word, 1-num)
}
|
Can you help me rewrite this code in AutoHotKey instead of C++, keeping it the same logically? | #include <iostream>
int main() {
using namespace std;
cout << "Hello, World!" << endl;
return 0;
}
| MsgBox, Hello World!
|
Change the following C++ code into AutoHotKey without altering its purpose. | #include <iostream>
int main() {
using namespace std;
cout << "Hello, World!" << endl;
return 0;
}
| MsgBox, Hello World!
|
Translate the given C++ code snippet into AutoHotKey without altering its behavior. | #include <iostream>
int main()
{
std::cout <<
R"EOF( A raw string begins with R, then a double-quote ("), then an optional
identifier (here I've used "EOF"), then an opening parenthesis ('('). If you
use an identifier, it cannot be longer than 16 characters, and it cannot
contain a space, either opening or closing parentheses, a backslash, a tab, a
vertical tab, a form feed, or a newline.
It ends with a closing parenthesis (')'), the identifer (if you used one),
and a double-quote.
All characters are okay in a raw string, no escape sequences are necessary
or recognized, and all whitespace is preserved.
)EOF";
}
| MyVar = "This is the text inside MyVar"
MyVariable =
(
Note that whitespace is preserved
As well as newlines.
The LTrim option can be present to remove left whitespace.
Variable references such as %MyVar% are expanded.
)
MsgBox % MyVariable
|
Write a version of this C++ function in AutoHotKey with identical behavior. | #include <iostream>
int main()
{
std::cout <<
R"EOF( A raw string begins with R, then a double-quote ("), then an optional
identifier (here I've used "EOF"), then an opening parenthesis ('('). If you
use an identifier, it cannot be longer than 16 characters, and it cannot
contain a space, either opening or closing parentheses, a backslash, a tab, a
vertical tab, a form feed, or a newline.
It ends with a closing parenthesis (')'), the identifer (if you used one),
and a double-quote.
All characters are okay in a raw string, no escape sequences are necessary
or recognized, and all whitespace is preserved.
)EOF";
}
| MyVar = "This is the text inside MyVar"
MyVariable =
(
Note that whitespace is preserved
As well as newlines.
The LTrim option can be present to remove left whitespace.
Variable references such as %MyVar% are expanded.
)
MsgBox % MyVariable
|
Can you help me rewrite this code in AutoHotKey instead of C++, keeping it the same logically? | #include <time.h>
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
typedef unsigned int uint;
using namespace std;
enum movDir { UP, DOWN, LEFT, RIGHT };
class tile
{
public:
tile() : val( 0 ), blocked( false ) {}
uint val;
bool blocked;
};
class g2048
{
public:
g2048() : done( false ), win( false ), moved( true ), score( 0 ) {}
void loop()
{
addTile();
while( true )
{
if( moved ) addTile();
drawBoard();
if( done ) break;
waitKey();
}
string s = "Game Over!";
if( win ) s = "You've made it!";
cout << s << endl << endl;
}
private:
void drawBoard()
{
system( "cls" );
cout << "SCORE: " << score << endl << endl;
for( int y = 0; y < 4; y++ )
{
cout << "+------+------+------+------+" << endl << "| ";
for( int x = 0; x < 4; x++ )
{
if( !board[x][y].val ) cout << setw( 4 ) << " ";
else cout << setw( 4 ) << board[x][y].val;
cout << " | ";
}
cout << endl;
}
cout << "+------+------+------+------+" << endl << endl;
}
void waitKey()
{
moved = false; char c;
cout << "(W)Up (S)Down (A)Left (D)Right "; cin >> c; c &= 0x5F;
switch( c )
{
case 'W': move( UP );break;
case 'A': move( LEFT ); break;
case 'S': move( DOWN ); break;
case 'D': move( RIGHT );
}
for( int y = 0; y < 4; y++ )
for( int x = 0; x < 4; x++ )
board[x][y].blocked = false;
}
void addTile()
{
for( int y = 0; y < 4; y++ )
for( int x = 0; x < 4; x++ )
if( !board[x][y].val )
{
uint a, b;
do
{ a = rand() % 4; b = rand() % 4; }
while( board[a][b].val );
int s = rand() % 100;
if( s > 89 ) board[a][b].val = 4;
else board[a][b].val = 2;
if( canMove() ) return;
}
done = true;
}
bool canMove()
{
for( int y = 0; y < 4; y++ )
for( int x = 0; x < 4; x++ )
if( !board[x][y].val ) return true;
for( int y = 0; y < 4; y++ )
for( int x = 0; x < 4; x++ )
{
if( testAdd( x + 1, y, board[x][y].val ) ) return true;
if( testAdd( x - 1, y, board[x][y].val ) ) return true;
if( testAdd( x, y + 1, board[x][y].val ) ) return true;
if( testAdd( x, y - 1, board[x][y].val ) ) return true;
}
return false;
}
bool testAdd( int x, int y, uint v )
{
if( x < 0 || x > 3 || y < 0 || y > 3 ) return false;
return board[x][y].val == v;
}
void moveVert( int x, int y, int d )
{
if( board[x][y + d].val && board[x][y + d].val == board[x][y].val && !board[x][y].blocked && !board[x][y + d].blocked )
{
board[x][y].val = 0;
board[x][y + d].val *= 2;
score += board[x][y + d].val;
board[x][y + d].blocked = true;
moved = true;
}
else if( !board[x][y + d].val && board[x][y].val )
{
board[x][y + d].val = board[x][y].val;
board[x][y].val = 0;
moved = true;
}
if( d > 0 ) { if( y + d < 3 ) moveVert( x, y + d, 1 ); }
else { if( y + d > 0 ) moveVert( x, y + d, -1 ); }
}
void moveHori( int x, int y, int d )
{
if( board[x + d][y].val && board[x + d][y].val == board[x][y].val && !board[x][y].blocked && !board[x + d][y].blocked )
{
board[x][y].val = 0;
board[x + d][y].val *= 2;
score += board[x + d][y].val;
board[x + d][y].blocked = true;
moved = true;
}
else if( !board[x + d][y].val && board[x][y].val )
{
board[x + d][y].val = board[x][y].val;
board[x][y].val = 0;
moved = true;
}
if( d > 0 ) { if( x + d < 3 ) moveHori( x + d, y, 1 ); }
else { if( x + d > 0 ) moveHori( x + d, y, -1 ); }
}
void move( movDir d )
{
switch( d )
{
case UP:
for( int x = 0; x < 4; x++ )
{
int y = 1;
while( y < 4 )
{ if( board[x][y].val ) moveVert( x, y, -1 ); y++;}
}
break;
case DOWN:
for( int x = 0; x < 4; x++ )
{
int y = 2;
while( y >= 0 )
{ if( board[x][y].val ) moveVert( x, y, 1 ); y--;}
}
break;
case LEFT:
for( int y = 0; y < 4; y++ )
{
int x = 1;
while( x < 4 )
{ if( board[x][y].val ) moveHori( x, y, -1 ); x++;}
}
break;
case RIGHT:
for( int y = 0; y < 4; y++ )
{
int x = 2;
while( x >= 0 )
{ if( board[x][y].val ) moveHori( x, y, 1 ); x--;}
}
}
}
tile board[4][4];
bool win, done, moved;
uint score;
};
int main( int argc, char* argv[] )
{
srand( static_cast<uint>( time( NULL ) ) );
g2048 g; g.loop();
return system( "pause" );
}
| Grid := [], s := 16, w := h := S * 4.5
Gui, font, s%s%
Gui, add, text, y1
loop, 4
{
row := A_Index
loop, 4
{
col := A_Index
if col = 1
Gui, add, button, v%row%_%col% xs y+1 w%w% h%h% -TabStop, % Grid[row,col] := 0
else
Gui, add, button, v%row%_%col% x+1 yp w%w% h%h% -TabStop, % Grid[row,col] := 0
}
}
Gui, show,, 2048
Start:
for row, obj in Grid
for col, val in obj
Grid[row,col] := 0
Grid[1,1]:=2
ShowGrid()
return
GuiClose:
ExitApp
return
#IfWinActive, 2048
up::
move := false
loop, 4
{
col := A_Index
Loop, 3
{
row := A_Index
if Grid[row, col] && (Grid[row, col] = Grid[row+1, col])
Grid[row, col] *=2 , Grid[row+1, col] := 0, move := true
}
}
loop, 4
{
row := A_Index
loop, 4
{
col := A_Index
loop, 4
if !Grid[row, col]
loop, 3
if !Grid[row, col] && Grid[row+A_Index, col]
{
Grid[row, col] := Grid[row+A_Index, col] , Grid[row+A_Index, col] := 0, move := true
if (Grid[row, col] = Grid[row-1, col])
Grid[row-1, col] *=2 , Grid[row, col] := 0, move := true
}
}
}
gosub, AddNew
return
Down::
move := false
loop, 4
{
col := A_Index
Loop, 3
{
row := 5-A_Index
if Grid[row, col] && (Grid[row, col] = Grid[row-1, col])
Grid[row, col] *=2 , Grid[row-1, col] := 0, move := true
}
}
loop, 4
{
row := 5-A_Index
loop, 4
{
col := A_Index
loop, 4
if !Grid[row, col]
loop, 3
if !Grid[row, col] && Grid[row-A_Index, col]
{
Grid[row, col] := Grid[row-A_Index, col] , Grid[row-A_Index, col] := 0, move := true
if (Grid[row, col] = Grid[row+1, col])
Grid[row+1, col] *=2 , Grid[row, col] := 0, move := true
}
}
}
gosub, AddNew
return
Left::
move := false
loop, 4
{
row := A_Index
Loop, 3
{
col := A_Index
if Grid[row, col] && (Grid[row, col] = Grid[row, col+1])
Grid[row, col] *=2 , Grid[row, col+1] := 0, move := true
}
}
loop, 4
{
col := A_Index
loop, 4
{
row := A_Index
loop, 4
if !Grid[row, col]
loop, 3
if !Grid[row, col] && Grid[row, col+A_Index]
{
Grid[row, col] := Grid[row, col+A_Index] , Grid[row, col+A_Index] := 0, move := true
if (Grid[row, col] = Grid[row, col-1])
Grid[row, col-1] *=2 , Grid[row, col] := 0, move := true
}
}
}
gosub, AddNew
return
Right::
move := false
loop, 4
{
row := A_Index
Loop, 3
{
col := 5-A_Index
if Grid[row, col] && (Grid[row, col] = Grid[row, col-1])
Grid[row, col] *=2 , Grid[row, col-1] := 0, move := true
}
}
loop, 4
{
col := 5-A_Index
loop, 4
{
row := A_Index
loop, 4
if !Grid[row, col]
loop, 3
if !Grid[row, col] && Grid[row, col-A_Index]
{
Grid[row, col] := Grid[row, col-A_Index] , Grid[row, col-A_Index] := 0, move := true
if (Grid[row, col] = Grid[row, col+1])
Grid[row, col+1] *=2 , Grid[row, col] := 0, move := true
}
}
}
gosub, AddNew
return
#IfWinActive
AddNew:
if EndOfGame()
{
MsgBox Done `nPress OK to retry
goto start
}
return
EndOfGame(){
global
if Move
AddRandom()
ShowGrid()
for row, obj in Grid
for col, val in obj
if !grid[row,col]
return 0
for row, obj in Grid
for col, val in obj
if (grid[row,col] = grid[row+1,col]) || (grid[row,col] = grid[row-1,col]) || (grid[row,col] = grid[row,col+1]) || (grid[row,col] = grid[row,col-1])
return 0
return 1
}
ShowGrid(){
global Grid
for row, obj in Grid
for col, val in obj
{
GuiControl,, %row%_%col%, %val%
if val
GuiControl, Show, %row%_%col%
else
GuiControl, Hide, %row%_%col%
}
}
AddRandom(){
global Grid
ShowGrid()
Sleep, 200
for row, obj in Grid
for col, val in obj
if !grid[row,col]
list .= (list?"`n":"") row "," col
Sort, list, random
Rnd := StrSplit(list, "`n").1
Grid[StrSplit(rnd, ",").1, StrSplit(rnd, ",").2] := 2
}
|
Ensure the translated AutoHotKey code behaves exactly like the original C++ snippet. | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
const int PLAYERS = 4, MAX_POINTS = 100;
enum Moves { ROLL, HOLD };
class player
{
public:
player() { current_score = round_score = 0; }
void addCurrScore() { current_score += round_score; }
int getCurrScore() { return current_score; }
int getRoundScore() { return round_score; }
void addRoundScore( int rs ) { round_score += rs; }
void zeroRoundScore() { round_score = 0; }
virtual int getMove() = 0;
virtual ~player() {}
protected:
int current_score, round_score;
};
class RAND_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( rand() % 10 < 5 ) return ROLL;
if( round_score > 0 ) return HOLD;
return ROLL;
}
};
class Q2WIN_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int q = MAX_POINTS - current_score;
if( q < 6 ) return ROLL;
q /= 4;
if( round_score < q ) return ROLL;
return HOLD;
}
};
class AL20_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( round_score < 20 ) return ROLL;
return HOLD;
}
};
class AL20T_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int d = ( 100 * round_score ) / 20;
if( round_score < 20 && d < rand() % 100 ) return ROLL;
return HOLD;
}
};
class Auto_pigGame
{
public:
Auto_pigGame()
{
_players[0] = new RAND_Player();
_players[1] = new Q2WIN_Player();
_players[2] = new AL20_Player();
_players[3] = new AL20T_Player();
}
~Auto_pigGame()
{
delete _players[0];
delete _players[1];
delete _players[2];
delete _players[3];
}
void play()
{
int die, p = 0;
bool endGame = false;
while( !endGame )
{
switch( _players[p]->getMove() )
{
case ROLL:
die = rand() % 6 + 1;
if( die == 1 )
{
cout << "Player " << p + 1 << " rolled " << die << " - current score: " << _players[p]->getCurrScore() << endl << endl;
nextTurn( p );
continue;
}
_players[p]->addRoundScore( die );
cout << "Player " << p + 1 << " rolled " << die << " - round score: " << _players[p]->getRoundScore() << endl;
break;
case HOLD:
_players[p]->addCurrScore();
cout << "Player " << p + 1 << " holds - current score: " << _players[p]->getCurrScore() << endl << endl;
if( _players[p]->getCurrScore() >= MAX_POINTS )
endGame = true;
else nextTurn( p );
}
}
showScore();
}
private:
void nextTurn( int& p )
{
_players[p]->zeroRoundScore();
++p %= PLAYERS;
}
void showScore()
{
cout << endl;
cout << "Player I (RAND): " << _players[0]->getCurrScore() << endl;
cout << "Player II (Q2WIN): " << _players[1]->getCurrScore() << endl;
cout << "Player III (AL20): " << _players[2]->getCurrScore() << endl;
cout << "Player IV (AL20T): " << _players[3]->getCurrScore() << endl << endl << endl;
system( "pause" );
}
player* _players[PLAYERS];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
Auto_pigGame pg;
pg.play();
return 0;
}
| #NoEnv
SetBatchLines, -1
#SingleInstance, Force
#Include Pig_the_dice_game_Optimal_Play.ahkl
Play:=10000
Wins0:=Wins1:=0
Player0(TurnSum, SumMe, SumOpp) {
Return practical(TurnSum, SumMe, SumOpp)
}
Player1(TurnSum, SumMe, SumOpp) {
Return optimal(TurnSum, SumMe, SumOpp)
}
Loop, % Play
{
CurrentPlayer := 0
Sum0:=Sum1:=0
Loop
{
OtherPlayer:=!CurrentPlayer
If (Sum%CurrentPlayer%+TurnSum < 100
and Player%CurrentPlayer%(TurnSum, Sum%CurrentPlayer%, Sum%OtherPlayer%))
{
Random, LastRoll, 1, 6
If (LastRoll != 1)
{
TurnSum += LastRoll
Continue
}
TurnSum := 0
}
Sum%CurrentPlayer% += TurnSum
TurnSum := 0
If (Sum%CurrentPlayer% >= 100)
{
Wins%CurrentPlayer%++
Break
}
CurrentPlayer := !CurrentPlayer
}
}
Msgbox % "Player 0 won " Round(Wins0/Play*100,0) "%`nPlayer 1 won " Round(Wins1/Play*100,0) "%"
Random(TurnSum, SumMe, SumOpp, N=9) {
Random, Roll, 0, N
Return Roll
}
Always(TurnSum, SumMe, SumOpp) {
Return 1
}
RollNx(TurnSum, SumMe, SumOpp, N=6) {
Static Roll=0
Return Roll := TurnSum = 0 ? 1 : mod(Roll+1,N+1)
}
RollToN(TurnSum, SumMe, SumOpp, N=19) {
Return Roll := TurnSum < N
}
Practical(TurnSum, SumMe, SumOpp, N=72) {
Return Roll := SumOpp > N or SumMe > N or TurnSum < 21+(SumOpp-SumMe)/8
}
Optimal(TurnSum, SumMe, SumOpp) {
Global Optimal
Roll := Optimal[SumMe,TurnSum,SumOpp+1]
Return Roll = "" ? 1 : Roll
}
|
Port the provided C++ code into AutoHotKey while preserving the original functionality. | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
const int PLAYERS = 4, MAX_POINTS = 100;
enum Moves { ROLL, HOLD };
class player
{
public:
player() { current_score = round_score = 0; }
void addCurrScore() { current_score += round_score; }
int getCurrScore() { return current_score; }
int getRoundScore() { return round_score; }
void addRoundScore( int rs ) { round_score += rs; }
void zeroRoundScore() { round_score = 0; }
virtual int getMove() = 0;
virtual ~player() {}
protected:
int current_score, round_score;
};
class RAND_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( rand() % 10 < 5 ) return ROLL;
if( round_score > 0 ) return HOLD;
return ROLL;
}
};
class Q2WIN_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int q = MAX_POINTS - current_score;
if( q < 6 ) return ROLL;
q /= 4;
if( round_score < q ) return ROLL;
return HOLD;
}
};
class AL20_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
if( round_score < 20 ) return ROLL;
return HOLD;
}
};
class AL20T_Player : public player
{
virtual int getMove()
{
if( round_score + current_score >= MAX_POINTS ) return HOLD;
int d = ( 100 * round_score ) / 20;
if( round_score < 20 && d < rand() % 100 ) return ROLL;
return HOLD;
}
};
class Auto_pigGame
{
public:
Auto_pigGame()
{
_players[0] = new RAND_Player();
_players[1] = new Q2WIN_Player();
_players[2] = new AL20_Player();
_players[3] = new AL20T_Player();
}
~Auto_pigGame()
{
delete _players[0];
delete _players[1];
delete _players[2];
delete _players[3];
}
void play()
{
int die, p = 0;
bool endGame = false;
while( !endGame )
{
switch( _players[p]->getMove() )
{
case ROLL:
die = rand() % 6 + 1;
if( die == 1 )
{
cout << "Player " << p + 1 << " rolled " << die << " - current score: " << _players[p]->getCurrScore() << endl << endl;
nextTurn( p );
continue;
}
_players[p]->addRoundScore( die );
cout << "Player " << p + 1 << " rolled " << die << " - round score: " << _players[p]->getRoundScore() << endl;
break;
case HOLD:
_players[p]->addCurrScore();
cout << "Player " << p + 1 << " holds - current score: " << _players[p]->getCurrScore() << endl << endl;
if( _players[p]->getCurrScore() >= MAX_POINTS )
endGame = true;
else nextTurn( p );
}
}
showScore();
}
private:
void nextTurn( int& p )
{
_players[p]->zeroRoundScore();
++p %= PLAYERS;
}
void showScore()
{
cout << endl;
cout << "Player I (RAND): " << _players[0]->getCurrScore() << endl;
cout << "Player II (Q2WIN): " << _players[1]->getCurrScore() << endl;
cout << "Player III (AL20): " << _players[2]->getCurrScore() << endl;
cout << "Player IV (AL20T): " << _players[3]->getCurrScore() << endl << endl << endl;
system( "pause" );
}
player* _players[PLAYERS];
};
int main( int argc, char* argv[] )
{
srand( GetTickCount() );
Auto_pigGame pg;
pg.play();
return 0;
}
| #NoEnv
SetBatchLines, -1
#SingleInstance, Force
#Include Pig_the_dice_game_Optimal_Play.ahkl
Play:=10000
Wins0:=Wins1:=0
Player0(TurnSum, SumMe, SumOpp) {
Return practical(TurnSum, SumMe, SumOpp)
}
Player1(TurnSum, SumMe, SumOpp) {
Return optimal(TurnSum, SumMe, SumOpp)
}
Loop, % Play
{
CurrentPlayer := 0
Sum0:=Sum1:=0
Loop
{
OtherPlayer:=!CurrentPlayer
If (Sum%CurrentPlayer%+TurnSum < 100
and Player%CurrentPlayer%(TurnSum, Sum%CurrentPlayer%, Sum%OtherPlayer%))
{
Random, LastRoll, 1, 6
If (LastRoll != 1)
{
TurnSum += LastRoll
Continue
}
TurnSum := 0
}
Sum%CurrentPlayer% += TurnSum
TurnSum := 0
If (Sum%CurrentPlayer% >= 100)
{
Wins%CurrentPlayer%++
Break
}
CurrentPlayer := !CurrentPlayer
}
}
Msgbox % "Player 0 won " Round(Wins0/Play*100,0) "%`nPlayer 1 won " Round(Wins1/Play*100,0) "%"
Random(TurnSum, SumMe, SumOpp, N=9) {
Random, Roll, 0, N
Return Roll
}
Always(TurnSum, SumMe, SumOpp) {
Return 1
}
RollNx(TurnSum, SumMe, SumOpp, N=6) {
Static Roll=0
Return Roll := TurnSum = 0 ? 1 : mod(Roll+1,N+1)
}
RollToN(TurnSum, SumMe, SumOpp, N=19) {
Return Roll := TurnSum < N
}
Practical(TurnSum, SumMe, SumOpp, N=72) {
Return Roll := SumOpp > N or SumMe > N or TurnSum < 21+(SumOpp-SumMe)/8
}
Optimal(TurnSum, SumMe, SumOpp) {
Global Optimal
Roll := Optimal[SumMe,TurnSum,SumOpp+1]
Return Roll = "" ? 1 : Roll
}
|
Keep all operations the same but rewrite the snippet in AutoHotKey. | #include <iostream>
#include <algorithm>
#include <ctime>
#include <string>
#include <vector>
typedef std::vector<char> vecChar;
class master {
public:
master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) {
std::string color = "ABCDEFGHIJKLMNOPQRST";
if( code_len < 4 ) code_len = 4; else if( code_len > 10 ) code_len = 10;
if( !rpt && clr_count < code_len ) clr_count = code_len;
if( clr_count < 2 ) clr_count = 2; else if( clr_count > 20 ) clr_count = 20;
if( guess_count < 7 ) guess_count = 7; else if( guess_count > 20 ) guess_count = 20;
codeLen = code_len; colorsCnt = clr_count; guessCnt = guess_count; repeatClr = rpt;
for( size_t s = 0; s < colorsCnt; s++ ) {
colors.append( 1, color.at( s ) );
}
}
void play() {
bool win = false;
combo = getCombo();
while( guessCnt ) {
showBoard();
if( checkInput( getInput() ) ) {
win = true;
break;
}
guessCnt--;
}
if( win ) {
std::cout << "\n\n--------------------------------\n" <<
"Very well done!\nYou found the code: " << combo <<
"\n--------------------------------\n\n";
} else {
std::cout << "\n\n--------------------------------\n" <<
"I am sorry, you couldn't make it!\nThe code was: " << combo <<
"\n--------------------------------\n\n";
}
}
private:
void showBoard() {
vecChar::iterator y;
for( int x = 0; x < guesses.size(); x++ ) {
std::cout << "\n--------------------------------\n";
std::cout << x + 1 << ": ";
for( y = guesses[x].begin(); y != guesses[x].end(); y++ ) {
std::cout << *y << " ";
}
std::cout << " : ";
for( y = results[x].begin(); y != results[x].end(); y++ ) {
std::cout << *y << " ";
}
int z = codeLen - results[x].size();
if( z > 0 ) {
for( int x = 0; x < z; x++ ) std::cout << "- ";
}
}
std::cout << "\n\n";
}
std::string getInput() {
std::string a;
while( true ) {
std::cout << "Enter your guess (" << colors << "): ";
a = ""; std::cin >> a;
std::transform( a.begin(), a.end(), a.begin(), ::toupper );
if( a.length() > codeLen ) a.erase( codeLen );
bool r = true;
for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {
if( colors.find( *x ) == std::string::npos ) {
r = false;
break;
}
}
if( r ) break;
}
return a;
}
bool checkInput( std::string a ) {
vecChar g;
for( std::string::iterator x = a.begin(); x != a.end(); x++ ) {
g.push_back( *x );
}
guesses.push_back( g );
int black = 0, white = 0;
std::vector<bool> gmatch( codeLen, false );
std::vector<bool> cmatch( codeLen, false );
for( int i = 0; i < codeLen; i++ ) {
if( a.at( i ) == combo.at( i ) ) {
gmatch[i] = true;
cmatch[i] = true;
black++;
}
}
for( int i = 0; i < codeLen; i++ ) {
if (gmatch[i]) continue;
for( int j = 0; j < codeLen; j++ ) {
if (i == j || cmatch[j]) continue;
if( a.at( i ) == combo.at( j ) ) {
cmatch[j] = true;
white++;
break;
}
}
}
vecChar r;
for( int b = 0; b < black; b++ ) r.push_back( 'X' );
for( int w = 0; w < white; w++ ) r.push_back( 'O' );
results.push_back( r );
return ( black == codeLen );
}
std::string getCombo() {
std::string c, clr = colors;
int l, z;
for( size_t s = 0; s < codeLen; s++ ) {
z = rand() % ( int )clr.length();
c.append( 1, clr[z] );
if( !repeatClr ) clr.erase( z, 1 );
}
return c;
}
size_t codeLen, colorsCnt, guessCnt;
bool repeatClr;
std::vector<vecChar> guesses, results;
std::string colors, combo;
};
int main( int argc, char* argv[] ) {
srand( unsigned( time( 0 ) ) );
master m( 4, 8, 12, false );
m.play();
return 0;
}
| w := h := 32, maxRows := 10, numPegs := 8
ww := floor(w/2-2), hh := floor(h/2-2)
grid := [], dx := w*4.5
gosub, Decode
Gui, Font, S18, Consolas
loop, 4
{
i := A_Index-1
Gui, add, button, % "x" (Mod(i, 4)?"+0":"30") " y"
. (Mod(i, 4)?"10" : "10") " w" w " h" h " vGoal" A_Index , ?
}
Gui, Add, Text, % "section x30 h1 0x1000 w" w*6
loop, % maxRows
{
Gui, Font, S18, consolas
row := maxRows - A_Index + 1
loop 4
{
col := A_Index, i:= col-1
Gui, add, button, % "x" (Mod(i, 4)?"+0":"s") " y" (Mod(i, 4)?"p":"+2")
. " w" w " h" h " vButton" row "_" col " gButton"
}
Gui, Font, S13, wingdings 2
loop 2
{
col := A_Index, i:= col-1
Gui, add, text, % "x" (Mod(i,2)?"+1":"s+" dx) " y" (Mod(i,2)?"p":"p+1")
. " w" ww " h" hh " vKeyPeg" row "_" col, % Chr(167)
}
loop 2
{
col := A_Index+2, i:= col-1
Gui, add, text, % "x" (Mod(i,2)?"+1":"s+" dx) " y" (Mod(i,2)?"p":"+1")
. " w" ww " h" hh " vKeyPeg" row "_" col, % Chr(167)
}
Gui, Add, Text, % "section xs h1 0x1000 w" w*6 " y+4"
}
Gui, Font, S12, consolas
Gui, add, Button, % "xs y+10 gSubmit w" W*2 , Submit
Gui, add, Button, % "x+0 gResetMM w" W*2, Reset
Gui, add, Checkbox, % "x+4 vNoDup", No`nDuplicates
Gui, Font, S18
for i, v in pegs
Gui, add, Radio, % "x" (!Mod(i-1, 4)?"10":"+10") " h" h " w" w+20 " vRadio" A_Index, % v
Gui, show
Row := 1
return
GuiClose:
ExitApp
return
Decode:
Gui, Submit, NoHide
pegs:=[], goal := [], usedPeg :=[]
pool := ["😺","🎃","🧨","⚽","😀","☠","👽","❄","🙉","💗"
,"💥","🖐","🏈","🎱","👁","🗨","🤙","👄","🐶","🐴"
,"🦢","🐍","🐞","💣","🐪","🐘","🐰","🐸","🌴","🏀"]
loop, % numPegs
{
Random, rnd, 1, % pool.count()
pegs[A_Index] := pool.RemoveAt(rnd)
}
i := 1
while (goal.count()<4)
{
Random, rnd, 1, % pegs.count()
if (NoDup && usedPeg[pegs[rnd]])
continue
goal[i++] := pegs[rnd]
usedPeg[pegs[rnd]] := true
}
return
Button:
if GameEnd
return
Gui, Submit, NoHide
RegExMatch(A_GuiControl, "Button(\d+)_(\d+)", m)
if (m1 <> row)
{
thisPeg := Grid[m1, m2]
for i, v in pegs
if (v=thisPeg)
GuiControl,, Radio%i%, 1
GuiControl,, % "Button" row "_" m2, % thisPeg
Grid[row,m2] := thisPeg
}
else
{
loop, % pegs.count()
if Radio%A_Index%
GuiControl,, % A_GuiControl , % grid[m1, m2] := pegs[A_Index]
}
return
Submit:
if (grid[row].count()<4) || GameEnd
return
Gui, submit, NoHide
Ans := [], FIP := [], inGoal := []
CIP := CNP := 0, KeyPeg := 1
for i, G in Goal
inGoal[G] := (inGoal[G] ? inGoal[G] : 0) +1
loop, 4
Ans[A_Index] := Grid[row, A_Index]
for i, A in Ans
if (goal[A_Index] = A)
CIP++, FIP.push(i), inGoal[A]:=inGoal[A] -1
for i, v in FIP
Ans.RemoveAt(v-i+1)
for i, A in Ans
if (inGoal[A] > 0)
CNP++, inGoal[A] := inGoal[A] -1
loop % CIP
GuiControl,, % "KeyPeg" row "_" KeyPeg++, % Chr(82)
loop % CNP
GuiControl,, % "KeyPeg" row "_" KeyPeg++, % Chr(83)
if (CIP=4 || row=maxRows)
{
loop 4
GuiControl,, Goal%A_Index%, % Goal[A_Index]
MsgBox % CIP = 4 ? "You Win" : "You lose"
GameEnd := true
}
Row++
return
LAlt::
loop 4
GuiControl,, Goal%A_Index%, % Goal[A_Index]
While GetKeyState("Lalt", "P")
continue
loop 4
GuiControl,, Goal%A_Index%, % "?"
return
ResetMM:
Grid :=[], GameEnd:= false
loop, 4
{
Random, rnd, 1, % pegs.count()
goal[A_Index] := pegs[rnd]
GuiControl,, Goal%A_Index%, ?
}
loop, % maxRows
{
row := maxRows - A_Index + 1
loop 4
{
col := A_Index
GuiControl,, % "KeyPeg" row "_" col, % Chr(167)
GuiControl,, % "Button" row "_" col
}
}
gosub Decode
loop, 8
GuiControl,, Radio%A_Index%, % pegs[A_Index]
return
|
Maintain the same structure and functionality when rewriting this code in AutoHotKey. | #include <cstdlib>
#include <fstream>
#include <iostream>
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string word;
int n = 0;
while (getline(in, word)) {
const size_t len = word.size();
if (len > 5 && word.compare(0, 3, word, len - 3) == 0)
std::cout << ++n << ": " << word << '\n';
}
return EXIT_SUCCESS;
}
| FileRead, db, % A_Desktop "\unixdict.txt"
for i, word in StrSplit(db, "`n", "`r")
if StrLen(word) < 6
continue
else if (SubStr(word, 1, 3) = SubStr(word, -2))
result .= word "`n"
MsgBox, 262144, , % result
return
|
Generate an equivalent AutoHotKey version of this C++ code. | #include <bitset>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <vector>
size_t consonants(const std::string& word) {
std::bitset<26> bits;
size_t bit = 0;
for (char ch : word) {
ch = std::tolower(static_cast<unsigned char>(ch));
if (ch < 'a' || ch > 'z')
continue;
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
break;
default:
bit = ch - 'a';
if (bits.test(bit))
return 0;
bits.set(bit);
break;
}
}
return bits.count();
}
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string word;
std::map<size_t, std::vector<std::string>, std::greater<int>> map;
while (getline(in, word)) {
if (word.size() <= 10)
continue;
size_t count = consonants(word);
if (count != 0)
map[count].push_back(word);
}
const int columns = 4;
for (const auto& p : map) {
std::cout << p.first << " consonants (" << p.second.size() << "):\n";
int n = 0;
for (const auto& word : p.second) {
std::cout << std::left << std::setw(18) << word;
++n;
if (n % columns == 0)
std::cout << '\n';
}
if (n % columns != 0)
std::cout << '\n';
std::cout << '\n';
}
return EXIT_SUCCESS;
}
| FileRead, db, % A_Desktop "\unixdict.txt"
vowels := ["a", "e", "i", "o", "u"]
oRes := []
for i, word in StrSplit(db, "`n", "`r")
{
if StrLen(word) < 11
continue
tWord := word
for j, v in vowels
word := StrReplace(word, v)
if !(word ~= "(.)(?=.*?\1)")
oRes[0-StrLen(word), tword] := 1
}
for l, obj in oRes
{
result .= 0-l " Unique consonants, word count: " obj.Count() "`n"
for word in obj
result .= word (!Mod(A_Index, 9) ? "`n" : "`t")
result .= "`n`n"
}
MsgBox, 262144, , % result
|
Translate this program into AutoHotKey but keep the logic exactly as in C++. | #include <bitset>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
bool contains_all_vowels_once(const std::string& word) {
std::bitset<5> vowels;
for (char ch : word) {
ch = std::tolower(static_cast<unsigned char>(ch));
size_t bit = 0;
switch (ch) {
case 'a': bit = 0; break;
case 'e': bit = 1; break;
case 'i': bit = 2; break;
case 'o': bit = 3; break;
case 'u': bit = 4; break;
default: continue;
}
if (vowels.test(bit))
return false;
vowels.set(bit);
}
return vowels.all();
}
int main(int argc, char** argv) {
const char* filename(argc < 2 ? "unixdict.txt" : argv[1]);
std::ifstream in(filename);
if (!in) {
std::cerr << "Cannot open file '" << filename << "'.\n";
return EXIT_FAILURE;
}
std::string word;
int n = 0;
while (getline(in, word)) {
if (word.size() > 10 && contains_all_vowels_once(word))
std::cout << std::setw(2) << ++n << ": " << word << '\n';
}
return EXIT_SUCCESS;
}
| FileRead, db, % A_Desktop "\unixdict.txt"
vowels := ["a", "e", "i", "o", "u"]
main:
for i, word in StrSplit(db, "`n", "`r")
{
if StrLen(word) < 11
continue
for j, v in vowels
{
StrReplace(word, v, v, c)
if (c<>1)
continue, main
}
result .= word "`n"
}
MsgBox, 262144, , % result
|
Rewrite the snippet below in AutoHotKey so it works the same as the original C++ code. | inline double multiply(double a, double b)
{
return a*b;
}
| MsgBox % multiply(10,2)
multiply(multiplicand, multiplier) {
Return (multiplicand * multiplier)
}
|
Please provide an equivalent version of this C++ code in AutoHotKey. | #include <gmpxx.h>
#include <iomanip>
#include <iostream>
using big_int = mpz_class;
bool is_probably_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;
}
big_int jacobsthal_number(unsigned int n) {
return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;
}
big_int jacobsthal_lucas_number(unsigned int n) {
return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);
}
big_int jacobsthal_oblong_number(unsigned int n) {
return jacobsthal_number(n) * jacobsthal_number(n + 1);
}
int main() {
std::cout << "First 30 Jacobsthal Numbers:\n";
for (unsigned int n = 0; n < 30; ++n) {
std::cout << std::setw(9) << jacobsthal_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 30 Jacobsthal-Lucas Numbers:\n";
for (unsigned int n = 0; n < 30; ++n) {
std::cout << std::setw(9) << jacobsthal_lucas_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 20 Jacobsthal oblong Numbers:\n";
for (unsigned int n = 0; n < 20; ++n) {
std::cout << std::setw(11) << jacobsthal_oblong_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 20 Jacobsthal primes:\n";
for (unsigned int n = 0, count = 0; count < 20; ++n) {
auto jn = jacobsthal_number(n);
if (is_probably_prime(jn)) {
++count;
std::cout << jn << '\n';
}
}
}
| Jacobsthal(n){
return SubStr(" " Format("{:.0f}", (2**n - (-1)**n ) / 3), -8)
}
Jacobsthal_Lucas(n){
return SubStr(" " Format("{:.0f}", 2**n + (-1)**n), -8)
}
prime_numbers(n) {
if (n <= 3)
return [n]
ans := [], done := false
while !done {
if !Mod(n,2)
ans.push(2), n /= 2
else if !Mod(n,3)
ans.push(3), n /= 3
else if (n = 1)
return ans
else {
sr := sqrt(n), done := true, i := 6
while (i <= sr+6) {
if !Mod(n, i-1) {
ans.push(i-1), n /= i-1, done := false
break
}
if !Mod(n, i+1) {
ans.push(i+1), n /= i+1, done := false
break
}
i += 6
}}}
ans.push(n)
return ans
}
|
Maintain the same structure and functionality when rewriting this code in AutoHotKey. | #include <gmpxx.h>
#include <iomanip>
#include <iostream>
using big_int = mpz_class;
bool is_probably_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;
}
big_int jacobsthal_number(unsigned int n) {
return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;
}
big_int jacobsthal_lucas_number(unsigned int n) {
return (big_int(1) << n) + (n % 2 == 0 ? 1 : -1);
}
big_int jacobsthal_oblong_number(unsigned int n) {
return jacobsthal_number(n) * jacobsthal_number(n + 1);
}
int main() {
std::cout << "First 30 Jacobsthal Numbers:\n";
for (unsigned int n = 0; n < 30; ++n) {
std::cout << std::setw(9) << jacobsthal_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 30 Jacobsthal-Lucas Numbers:\n";
for (unsigned int n = 0; n < 30; ++n) {
std::cout << std::setw(9) << jacobsthal_lucas_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 20 Jacobsthal oblong Numbers:\n";
for (unsigned int n = 0; n < 20; ++n) {
std::cout << std::setw(11) << jacobsthal_oblong_number(n)
<< ((n + 1) % 5 == 0 ? '\n' : ' ');
}
std::cout << "\nFirst 20 Jacobsthal primes:\n";
for (unsigned int n = 0, count = 0; count < 20; ++n) {
auto jn = jacobsthal_number(n);
if (is_probably_prime(jn)) {
++count;
std::cout << jn << '\n';
}
}
}
| Jacobsthal(n){
return SubStr(" " Format("{:.0f}", (2**n - (-1)**n ) / 3), -8)
}
Jacobsthal_Lucas(n){
return SubStr(" " Format("{:.0f}", 2**n + (-1)**n), -8)
}
prime_numbers(n) {
if (n <= 3)
return [n]
ans := [], done := false
while !done {
if !Mod(n,2)
ans.push(2), n /= 2
else if !Mod(n,3)
ans.push(3), n /= 3
else if (n = 1)
return ans
else {
sr := sqrt(n), done := true, i := 6
while (i <= sr+6) {
if !Mod(n, i-1) {
ans.push(i-1), n /= i-1, done := false
break
}
if !Mod(n, i+1) {
ans.push(i+1), n /= i+1, done := false
break
}
i += 6
}}}
ans.push(n)
return ans
}
|
Maintain the same structure and functionality when rewriting this code in AutoHotKey. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
int jacobi(int n, int k) {
assert(k > 0 && k % 2 == 1);
n %= k;
int t = 1;
while (n != 0) {
while (n % 2 == 0) {
n /= 2;
int r = k % 8;
if (r == 3 || r == 5)
t = -t;
}
std::swap(n, k);
if (n % 4 == 3 && k % 4 == 3)
t = -t;
n %= k;
}
return k == 1 ? t : 0;
}
void print_table(std::ostream& out, int kmax, int nmax) {
out << "n\\k|";
for (int k = 0; k <= kmax; ++k)
out << ' ' << std::setw(2) << k;
out << "\n----";
for (int k = 0; k <= kmax; ++k)
out << "---";
out << '\n';
for (int n = 1; n <= nmax; n += 2) {
out << std::setw(2) << n << " |";
for (int k = 0; k <= kmax; ++k)
out << ' ' << std::setw(2) << jacobi(k, n);
out << '\n';
}
}
int main() {
print_table(std::cout, 20, 21);
return 0;
}
| result := "n/k|"
loop 20
result .= SubStr(" " A_Index, -1) " "
l := StrLen(result)
result .= "`n"
loop % l
result .= "-"
result .= "`n"
loop 21
{
if !Mod(n := A_Index, 2)
continue
result .= SubStr(" " n, -1) " |"
loop 20
result .= SubStr(" " jacobi(a := A_Index, n), -1) " "
result .= "`n"
}
MsgBox, 262144, , % result
return
jacobi(a, n) {
a := Mod(a, n), t := 1
while (a != 0) {
while !Mod(a, 2)
a := a >> 1, r := Mod(n, 8), t := (r=3 || r=5) ? -t : t
r := n, n := a, a := r
if (Mod(a, 4)=3 && Mod(n, 4)=3)
t := -t
a := Mod(a, n)
}
return (n=1) ? t : 0
}
|
Write the same algorithm in AutoHotKey as shown in this C++ implementation. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
int jacobi(int n, int k) {
assert(k > 0 && k % 2 == 1);
n %= k;
int t = 1;
while (n != 0) {
while (n % 2 == 0) {
n /= 2;
int r = k % 8;
if (r == 3 || r == 5)
t = -t;
}
std::swap(n, k);
if (n % 4 == 3 && k % 4 == 3)
t = -t;
n %= k;
}
return k == 1 ? t : 0;
}
void print_table(std::ostream& out, int kmax, int nmax) {
out << "n\\k|";
for (int k = 0; k <= kmax; ++k)
out << ' ' << std::setw(2) << k;
out << "\n----";
for (int k = 0; k <= kmax; ++k)
out << "---";
out << '\n';
for (int n = 1; n <= nmax; n += 2) {
out << std::setw(2) << n << " |";
for (int k = 0; k <= kmax; ++k)
out << ' ' << std::setw(2) << jacobi(k, n);
out << '\n';
}
}
int main() {
print_table(std::cout, 20, 21);
return 0;
}
| result := "n/k|"
loop 20
result .= SubStr(" " A_Index, -1) " "
l := StrLen(result)
result .= "`n"
loop % l
result .= "-"
result .= "`n"
loop 21
{
if !Mod(n := A_Index, 2)
continue
result .= SubStr(" " n, -1) " |"
loop 20
result .= SubStr(" " jacobi(a := A_Index, n), -1) " "
result .= "`n"
}
MsgBox, 262144, , % result
return
jacobi(a, n) {
a := Mod(a, n), t := 1
while (a != 0) {
while !Mod(a, 2)
a := a >> 1, r := Mod(n, 8), t := (r=3 || r=5) ? -t : t
r := n, n := a, a := r
if (Mod(a, 4)=3 && Mod(n, 4)=3)
t := -t
a := Mod(a, n)
}
return (n=1) ? t : 0
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.