Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Transform the following Go implementation into Swift, maintaining the same output and logic.
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } fun...
func succ<A, B, C>(_ n: @escaping (@escaping (A) -> B) -> (C) -> A) -> (@escaping (A) -> B) -> (C) -> B { return {f in return {x in return f(n(f)(x)) } } } func zero<A, B>(_ a: A) -> (B) -> B { return {b in return b } } func three<A>(_ f: @escaping (A) -> A) -> (A) -> A { return {x in ...
Preserve the algorithm and functionality while converting the code from Go to Swift.
package main import "fmt" type any = interface{} type fn func(any) any type church func(fn) fn func zero(f fn) fn { return func(x any) any { return x } } func (c church) succ() church { return func(f fn) fn { return func(x any) any { return f(c(f)(x)) } } } fun...
func succ<A, B, C>(_ n: @escaping (@escaping (A) -> B) -> (C) -> A) -> (@escaping (A) -> B) -> (C) -> B { return {f in return {x in return f(n(f)(x)) } } } func zero<A, B>(_ a: A) -> (B) -> B { return {b in return b } } func three<A>(_ f: @escaping (A) -> A) -> (A) -> A { return {x in ...
Write the same code in Swift as shown below in Go.
package main import ( "fmt" "reflect" ) type example struct{} func (example) Foo() int { return 42 } func main() { var e example m := reflect.ValueOf(e).MethodByName("Foo") r := m.Call(nil) fmt.Println(r[0].Int()) }
import Foundation class MyUglyClass: NSObject { @objc func myUglyFunction() { print("called myUglyFunction") } } let someObject: NSObject = MyUglyClass() someObject.perform(NSSelectorFromString("myUglyFunction"))
Generate an equivalent Swift version of this Go code.
package main import ( "fmt" "math/big" ) func main() { one := big.NewInt(1) pm := big.NewInt(1) var px, nx int var pb big.Int primes(4000, func(p int64) bool { pm.Mul(pm, pb.SetInt64(p)) px++ if pb.Add(pm, one).ProbablyPrime(0) || pb.Sub(pm, one).Pro...
import BigInt import Foundation extension BinaryInteger { @inlinable public var isPrime: Bool { if self == 0 || self == 1 { return false } else if self == 2 { return true } let max = Self(ceil((Double(self).squareRoot()))) for i in stride(from: 2, through: max, by: 1) where self ...
Convert this Go snippet to Swift and keep its semantics consistent.
package main import ( "fmt" "math/big" ) func main() { var n, p int64 fmt.Printf("A sample of permutations from 1 to 12:\n") for n = 1; n < 13; n++ { p = n / 3 fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) } fmt.Printf("\nA sample of combinations from 10 to 60:\n") for n = 10; n ...
import BigInt func permutations(n: Int, k: Int) -> BigInt { let l = n - k + 1 guard l <= n else { return 1 } return (l...n).reduce(BigInt(1), { $0 * BigInt($1) }) } func combinations(n: Int, k: Int) -> BigInt { let fact = {() -> BigInt in guard k > 1 else { return 1 } return (2...k)...
Generate an equivalent Swift version of this Go code.
package main import "fmt" func sieve(limit int) []int { var primes []int c := make([]bool, limit + 1) p := 3 p2 := p * p for p2 <= limit { for i := p2; i <= limit; i += 2 * p { c[i] = true } for ok := true; ok; ok = c[p] { p += 2 } ...
public struct Eratosthenes: Sequence, IteratorProtocol { private let n: Int private let limit: Int private var i = 2 private var sieve: [Int] public init(upTo: Int) { if upTo <= 1 { self.n = 0 self.limit = -1 self.sieve = [] } else { self.n = upTo self.limit = Int(Doubl...
Please provide an equivalent version of this Go code in Swift.
package main import ( "fmt" "strings" ) var input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" var opa = map[string]struct { prec int rAssoc bool }{ "^": {4, true}, "*": {3, false}, "/": {3, false}, "+": {2, false}, "-": {2, false}, } func main() { fmt.Println("infix: ", input) f...
import Foundation struct Stack<T> { private(set) var elements = [T]() var isEmpty: Bool { elements.isEmpty } var top: T? { elements.last } mutating func push(_ newElement: T) { elements.append(newElement) } mutating func pop() -> T? { self.isEmpty ? nil : elements.removeLast() } } struct Qu...
Please provide an equivalent version of this Go code in Swift.
package main import ( "fmt" "math" ) func main() { fmt.Println(noise(3.14, 42, 7)) } func noise(x, y, z float64) float64 { X := int(math.Floor(x)) & 255 Y := int(math.Floor(y)) & 255 Z := int(math.Floor(z)) & 255 x -= math.Floor(x) y -= math.Floor(y) z -= math.Floor(z) u := fa...
import Foundation struct Perlin { private static let permutation = [ 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, ...
Change the programming language of this snippet from Go to Swift without modifying what it does.
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(...
import BigInt public struct Lychrel<T: ReversibleNumeric & CustomStringConvertible>: Sequence, IteratorProtocol { @usableFromInline let seed: T @usableFromInline var done = false @usableFromInline var n: T @usableFromInline var iterations: T @inlinable public init(seed: T, iterations: T = 500) ...
Port the following code from Go to Swift with equivalent syntax and logic.
package main import ( "flag" "fmt" "math" "math/big" "os" ) var maxRev = big.NewInt(math.MaxUint64 / 10) var ten = big.NewInt(10) func reverseInt(v *big.Int, result *big.Int) *big.Int { if v.Cmp(maxRev) <= 0 { result.SetUint64(reverseUint64(v.Uint64())) } else { if true { s := reverseString(...
import BigInt public struct Lychrel<T: ReversibleNumeric & CustomStringConvertible>: Sequence, IteratorProtocol { @usableFromInline let seed: T @usableFromInline var done = false @usableFromInline var n: T @usableFromInline var iterations: T @inlinable public init(seed: T, iterations: T = 500) ...
Convert the following code from Go to Swift, ensuring the logic remains intact.
package main import ( "fmt" "math" "time" ) const ld10 = math.Ln2 / math.Ln10 func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func p(L, n uint64) uint64 { i := L digits :=...
let ld10 = log(2.0) / log(10.0) func p(L: Int, n: Int) -> Int { var l = L var digits = 1 while l >= 10 { digits *= 10 l /= 10 } var count = 0 var i = 0 while count < n { let rhs = (Double(i) * ld10).truncatingRemainder(dividingBy: 1) let e = exp(log(10.0) * rhs) if Int(e * Double(...
Write the same code in Swift as shown below in Go.
package main import ( "fmt" "math" "time" ) const ld10 = math.Ln2 / math.Ln10 func commatize(n uint64) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s } func p(L, n uint64) uint64 { i := L digits :=...
let ld10 = log(2.0) / log(10.0) func p(L: Int, n: Int) -> Int { var l = L var digits = 1 while l >= 10 { digits *= 10 l /= 10 } var count = 0 var i = 0 while count < n { let rhs = (Double(i) * ld10).truncatingRemainder(dividingBy: 1) let e = exp(log(10.0) * rhs) if Int(e * Double(...
Rewrite the snippet below in Swift so it works the same as the original Go code.
package main import ( "fmt" big "github.com/ncw/gmp" "sort" ) var ( one = new(big.Int).SetUint64(1) two = new(big.Int).SetUint64(2) three = new(big.Int).SetUint64(3) ) func pierpont(ulim, vlim int, first bool) []*big.Int { p := new(big.Int) p2 := new(big.Int).Set(one) p3 := ne...
import BigInt import Foundation public func pierpoint(n: Int) -> (first: [BigInt], second: [BigInt]) { var primes = (first: [BigInt](repeating: 0, count: n), second: [BigInt](repeating: 0, count: n)) primes.first[0] = 2 var count1 = 1, count2 = 0 var s = [BigInt(1)] var i2 = 0, i3 = 0, k = 1 var n2 = Big...
Convert the following code from Go to Swift, ensuring the logic remains intact.
package main import ( "fmt" "log" "math/big" ) var ( primes []*big.Int smallPrimes []int ) func init() { two := big.NewInt(2) three := big.NewInt(3) p521 := big.NewInt(521) p29 := big.NewInt(29) primes = append(primes, two) smallPrimes = append(smallPrimes, 2) fo...
import BigInt import Foundation extension BinaryInteger { @inlinable public var isPrime: Bool { if self == 0 || self == 1 { return false } else if self == 2 { return true } let max = Self(ceil((Double(self).squareRoot()))) for i in stride(from: 2, through: max, by: 1) { if s...
Can you help me rewrite this code in Swift instead of Go, keeping it the same logically?
package main import ( "fmt" "log" ) var ( primes = sieve(100000) foundCombo = false ) func sieve(limit uint) []uint { primes := []uint{2} c := make([]bool, limit+1) p := uint(3) for { p2 := p * p if p2 > limit { break } for i := p2...
import Foundation class BitArray { var array: [UInt32] init(size: Int) { array = Array(repeating: 0, count: (size + 31)/32) } func get(index: Int) -> Bool { let bit = UInt32(1) << (index & 31) return (array[index >> 5] & bit) != 0 } func set(index: Int, value:...
Ensure the translated Swift code behaves exactly like the original Go snippet.
package main import ( "fmt" "math" ) type point struct{ x, y float64 } func RDP(l []point, ε float64) []point { x := 0 dMax := -1. last := len(l) - 1 p1 := l[0] p2 := l[last] x21 := p2.x - p1.x y21 := p2.y - p1.y for i, p := range l[1:last] { if d := math.Abs(y21*p.x -...
struct Point: CustomStringConvertible { let x: Double, y: Double var description: String { return "(\(x), \(y))" } } func perpendicularDistance(p: Point, p1: Point, p2: Point) -> Double { let dx = p2.x - p1.x let dy = p2.y - p1.y let d = (p.x * dy - p.y * dx + p2.x * p1.y - p2.y * p1....
Please provide an equivalent version of this Go code in Swift.
package main import ( "fmt" "math" ) type point struct{ x, y float64 } func RDP(l []point, ε float64) []point { x := 0 dMax := -1. last := len(l) - 1 p1 := l[0] p2 := l[last] x21 := p2.x - p1.x y21 := p2.y - p1.y for i, p := range l[1:last] { if d := math.Abs(y21*p.x -...
struct Point: CustomStringConvertible { let x: Double, y: Double var description: String { return "(\(x), \(y))" } } func perpendicularDistance(p: Point, p1: Point, p2: Point) -> Double { let dx = p2.x - p1.x let dy = p2.y - p1.y let d = (p.x * dy - p.y * dx + p2.x * p1.y - p2.y * p1....
Port the following code from Go to Swift with equivalent syntax and logic.
package main import ( "fmt" "math" ) type cheb struct { c []float64 min, max float64 } func main() { fn := math.Cos c := newCheb(0, 1, 10, 10, fn) fmt.Println("coefficients:") for _, c := range c.c { fmt.Printf("% .15f\n", c) } fmt.Println("\nx computed a...
import Foundation typealias DFunc = (Double) -> Double func mapRange(x: Double, min: Double, max: Double, minTo: Double, maxTo: Double) -> Double { return (x - min) / (max - min) * (maxTo - minTo) + minTo } func chebCoeffs(fun: DFunc, n: Int, min: Double, max: Double) -> [Double] { var res = [Double](repeating: ...
Generate a Swift translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "math" ) type cheb struct { c []float64 min, max float64 } func main() { fn := math.Cos c := newCheb(0, 1, 10, 10, fn) fmt.Println("coefficients:") for _, c := range c.c { fmt.Printf("% .15f\n", c) } fmt.Println("\nx computed a...
import Foundation typealias DFunc = (Double) -> Double func mapRange(x: Double, min: Double, max: Double, minTo: Double, maxTo: Double) -> Double { return (x - min) / (max - min) * (maxTo - minTo) + minTo } func chebCoeffs(fun: DFunc, n: Int, min: Double, max: Double) -> [Double] { var res = [Double](repeating: ...
Preserve the algorithm and functionality while converting the code from Go to Swift.
package main import ( "fmt" "sort" "strings" ) const stx = "\002" const etx = "\003" func bwt(s string) (string, error) { if strings.Index(s, stx) >= 0 || strings.Index(s, etx) >= 0 { return "", fmt.Errorf("String can't contain STX or ETX") } s = stx + s + etx le := len(s) tab...
import Foundation private let stx = "\u{2}" private let etx = "\u{3}" func bwt(_ str: String) -> String? { guard !str.contains(stx), !str.contains(etx) else { return nil } let ss = stx + str + etx let table = ss.indices.map({i in ss[i...] + ss[ss.startIndex..<i] }).sorted() return String(table.map({st...
Ensure the translated Swift code behaves exactly like the original Go snippet.
package main import ( "fmt" "sort" "strings" ) const stx = "\002" const etx = "\003" func bwt(s string) (string, error) { if strings.Index(s, stx) >= 0 || strings.Index(s, etx) >= 0 { return "", fmt.Errorf("String can't contain STX or ETX") } s = stx + s + etx le := len(s) tab...
import Foundation private let stx = "\u{2}" private let etx = "\u{3}" func bwt(_ str: String) -> String? { guard !str.contains(stx), !str.contains(etx) else { return nil } let ss = stx + str + etx let table = ss.indices.map({i in ss[i...] + ss[ss.startIndex..<i] }).sorted() return String(table.map({st...
Port the following code from Go to Swift with equivalent syntax and logic.
package main import ( "fmt" "log" "os" "strconv" "strings" ) const luckySize = 60000 var luckyOdd = make([]int, luckySize) var luckyEven = make([]int, luckySize) func init() { for i := 0; i < luckySize; i++ { luckyOdd[i] = i*2 + 1 luckyEven[i] = i*2 + 2 } } func filterLu...
struct LuckyNumbers : Sequence, IteratorProtocol { let even: Bool let through: Int private var drainI = 0 private var n = 0 private var lst: [Int] init(even: Bool = false, through: Int = 1_000_000) { self.even = even self.through = through self.lst = Array(stride(from: even ? 2 : 1, throug...
Write the same algorithm in Swift as shown in this Go implementation.
package main import "fmt" const ( empty = iota black white ) const ( bqueen = 'B' wqueen = 'W' bbullet = '•' wbullet = '◦' ) type position struct{ i, j int } func iabs(i int) int { if i < 0 { return -i } return i } func place(m, n int, pBlackQueens, pWhiteQueens *...
enum Piece { case empty, black, white } typealias Position = (Int, Int) func place(_ m: Int, _ n: Int, pBlackQueens: inout [Position], pWhiteQueens: inout [Position]) -> Bool { guard m != 0 else { return true } var placingBlack = true for i in 0..<n { inner: for j in 0..<n { let pos = (i, j)...
Convert this Go snippet to Swift and keep its semantics consistent.
package main import ( "fmt" "math" "os" ) type vector struct{ x, y, z float64 } func (v vector) add(w vector) vector { return vector{v.x + w.x, v.y + w.y, v.z + w.z} } func (v vector) sub(w vector) vector { return vector{v.x - w.x, v.y - w.y, v.z - w.z} } func (v vector) scale(m float64) vector...
import Foundation public struct Vector { public var px = 0.0 public var py = 0.0 public var pz = 0.0 public init(px: Double, py: Double, pz: Double) { (self.px, self.py, self.pz) = (px, py, pz) } public init?(array: [Double]) { guard array.count == 3 else { return nil } (self.px, s...
Port the following code from Go to Swift with equivalent syntax and logic.
package main import "fmt" func getDivisors(n int) []int { divs := []int{1, n} for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs = append(divs, i) if i != j { divs = append(divs, j) } } } return divs } func sum(div...
import Foundation extension BinaryInteger { @inlinable public var isZumkeller: Bool { let divs = factors(sorted: false) let sum = divs.reduce(0, +) guard sum & 1 != 1 else { return false } guard self & 1 != 1 else { let abundance = sum - 2*self return abundance > 0 && abund...
Rewrite the snippet below in Swift so it works the same as the original Go code.
package main import ( "fmt" "regexp" "strings" ) var reg = regexp.MustCompile(`(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)`) func reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) } func commatiz...
import Foundation extension String { private static let commaReg = try! NSRegularExpression(pattern: "(\\.[0-9]+|[1-9]([0-9]+)?(\\.[0-9]+)?)") public func commatize(start: Int = 0, period: Int = 3, separator: String = ",") -> String { guard separator != "" else { return self } let sep = Array(s...
Keep all operations the same but rewrite the snippet in Swift.
package main import "fmt" var g = [][]int{ 0: {1}, 1: {2}, 2: {0}, 3: {1, 2, 4}, 4: {3, 5}, 5: {2, 6}, 6: {5}, 7: {4, 6, 7}, } func main() { fmt.Println(kosaraju(g)) } func kosaraju(g [][]int) []int { vis := make([]bool, len(g)) L := make([]int, len(g)) x := len(...
func kosaraju(graph: [[Int]]) -> [Int] { let size = graph.count var x = size var vis = [Bool](repeating: false, count: size) var l = [Int](repeating: 0, count: size) var c = [Int](repeating: 0, count: size) var t = [[Int]](repeating: [], count: size) func visit(_ u: Int) { guard !vis[u] else { ...
Translate the given Go code snippet into Swift without altering its behavior.
package main import ( "fmt" "strings" ) type dict map[string]bool func newDict(words ...string) dict { d := dict{} for _, w := range words { d[w] = true } return d } func (d dict) wordBreak(s string) (broken []string, ok bool) { if s == "" { return nil, true } typ...
infix operator ??= : AssignmentPrecedence @inlinable public func ??= <T>(lhs: inout T?, rhs: T?) { lhs = lhs ?? rhs } private func createString(_ from: String, _ v: [Int?]) -> String { var idx = from.count var sliceVec = [Substring]() while let prev = v[idx] { let s = from.index(from.startIndex, offsetBy...
Preserve the algorithm and functionality while converting the code from Go to Swift.
package main import ( "fmt" "strconv" ) func ownCalcPass(password, nonce string) uint32 { start := true num1 := uint32(0) num2 := num1 i, _ := strconv.Atoi(password) pwd := uint32(i) for _, c := range nonce { if c != '0' { if start { num2 = pwd ...
func openAuthenticationResponse(_password: String, operations: String) -> String? { var num1 = UInt32(0) var num2 = UInt32(0) var start = true let password = UInt32(_password)! for c in operations { if (c != "0") { if start { num2 = password } ...
Produce a functionally identical Swift code for the snippet given in Go.
package main import ( "fmt" "math/big" "time" ) var p []*big.Int var pd []int func partDiffDiff(n int) int { if n&1 == 1 { return (n + 1) / 2 } return n + 1 } func partDiff(n int) int { if n < 2 { return 1 } pd[n] = pd[n-1] + partDiffDiff(n-1) return pd[n] } ...
import BigInt func partitions(n: Int) -> BigInt { var p = [BigInt(1)] for i in 1...n { var num = BigInt(0) var k = 1 while true { var j = (k * (3 * k - 1)) / 2 if j > i { break } if k & 1 == 1 { num += p[i - j] } else { num -= p[i - j] } ...
Transform the following Go implementation into Swift, maintaining the same output and logic.
package main import ( "fmt" "rcu" ) func reversed(n int) int { rev := 0 for n > 0 { rev = rev*10 + n%10 n = n / 10 } return rev } func main() { var special []int for n := 1; n < 200; n++ { divs := rcu.Divisors(n) revN := reversed(n) all := true ...
import Foundation func reverse(_ number: Int) -> Int { var rev = 0 var n = number while n > 0 { rev = rev * 10 + n % 10 n /= 10 } return rev } func special(_ number: Int) -> Bool { var n = 2 let rev = reverse(number) while n * n <= number { if number % n == 0 { ...
Translate this program into Swift but keep the logic exactly as in Go.
package main import ( "fmt" "strings" ) func hpo2(n uint) uint { return n & (-n) } func lhpo2(n uint) uint { q := uint(0) m := hpo2(n) for m%2 == 0 { m = m >> 1 q++ } return q } func nimsum(x, y uint) uint { return x ^ y } func nimprod(x, y uint) uint { if x < 2 ...
import Foundation func hpo2(_ n: Int) -> Int { n & -n } func lhpo2(_ n: Int) -> Int { var q: Int = 0 var m: Int = hpo2(n) while m % 2 == 0 { m >>= 1 q += 1 } return q } func nimSum(x: Int, y: Int) -> Int { x ^ y } func nimProduct(x: Int, y: Int) -> Int { if x < 2 ...
Convert the following code from Go to Swift, ensuring the logic remains intact.
package main import ( "fmt" "log" "math" "rcu" ) func cantorPair(x, y int) int { if x < 0 || y < 0 { log.Fatal("Arguments must be non-negative integers.") } return (x*x + 3*x + 2*x*y + y + y*y) / 2 } func pi(n int) int { if n < 2 { return 0 } if n == 2 { ...
import Foundation extension Numeric where Self: Strideable { @inlinable public func power(_ n: Self) -> Self { return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *) } } func eratosthenes(limit: Int) -> [Int] { guard limit >= 3 else { return limit < 2 ? [] : [2] } let ndxLimit =...
Translate the given Go code snippet into Swift without altering its behavior.
package main import ( "fmt" "rcu" "sort" ) func areSame(l1, l2 []int) bool { if len(l1) != len(l2) { return false } sort.Ints(l2) for i := 0; i < len(l1); i++ { if l1[i] != l2[i] { return false } } return true } func main() { i := 100 ...
func getDigits(_ num: Int) -> Array<Int> { var n = num var digits = Array(repeating: 0, count: 10) while true { digits[n % 10] += 1 n /= 10 if n == 0 { break } } return digits } func sameDigits(_ n: Int) -> Bool { let digits = getDigits(n) for i ...
Port the following code from Go to Swift with equivalent syntax and logic.
package main import ( "fmt" "rcu" "sort" ) func areSame(l1, l2 []int) bool { if len(l1) != len(l2) { return false } sort.Ints(l2) for i := 0; i < len(l1); i++ { if l1[i] != l2[i] { return false } } return true } func main() { i := 100 ...
func getDigits(_ num: Int) -> Array<Int> { var n = num var digits = Array(repeating: 0, count: 10) while true { digits[n % 10] += 1 n /= 10 if n == 0 { break } } return digits } func sameDigits(_ n: Int) -> Bool { let digits = getDigits(n) for i ...
Change the programming language of this snippet from Go to Swift without modifying what it does.
package main import "fmt" var canFollow [][]bool var arrang []int var bFirst = true var pmap = make(map[int]bool) func init() { for _, i := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37} { pmap[i] = true } } func ptrs(res, n, done int) int { ad := arrang[done-1] if n-done <= 1 { ...
import Foundation func isPrime(_ n: Int) -> Bool { guard n > 0 && n < 64 else { return false } return ((UInt64(1) << n) & 0x28208a20a08a28ac) != 0 } func primeTriangleRow(_ a: inout [Int], start: Int, length: Int) -> Bool { if length == 2 { return isPrime(a[start] + a[start + 1]) }...
Write the same algorithm in Swift as shown in this Go implementation.
package main import ( "bytes" "fmt" "io/ioutil" "log" "strings" ) func contains(a []string, s string) bool { for _, e := range a { if e == s { return true } } return false } func oneAway(a, b string) bool { sum := 0 for i := 0; i < len(a); i++ { ...
import Foundation func oneAway(string1: [Character], string2: [Character]) -> Bool { if string1.count != string2.count { return false } var result = false var i = 0 while i < string1.count { if string1[i] != string2[i] { if result { return false ...
Convert this Go block to Swift, preserving its control flow and logic.
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) st...
let base32 = "0123456789bcdefghjkmnpqrstuvwxyz" extension String { subscript(i: Int) -> String { String(self[index(startIndex, offsetBy: i)]) } } struct Coordinate { var latitude: Double var longitude: Double func toString() -> String { var latitudeHemisphere = "" var longitudeHemisphere = "" ...
Maintain the same structure and functionality when rewriting this code in Swift.
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...
func digitProduct(base: Int, num: Int) -> Int { var product = 1 var n = num while n != 0 { product *= n % base n /= base } return product } func primeFactorSum(_ num: Int) -> Int { var sum = 0 var n = num while (n & 1) == 0 { sum += 2 n >>= 1 } va...
Please provide an equivalent version of this Go code in Swift.
package main import ( "bytes" "fmt" "log" ) func wordle(answer, guess string) []int { n := len(guess) if n != len(answer) { log.Fatal("The words must be of the same length.") } answerBytes := []byte(answer) result := make([]int, n) for i := 0; i < n; i++ { if guess...
enum Colour : CustomStringConvertible { case grey case yellow case green var description : String { switch self { case .grey: return "grey" case .yellow: return "yellow" case .green: return "green" } } } func wordle(answer: String, guess: String) -> [Colour]? { guard answer.count =...
Transform the following Go implementation into Swift, maintaining the same output and logic.
package main import ( "fmt" "strings" ) const limit = 50000 var ( divs, subs []int mins [][]string ) func minsteps(n int) { if n == 1 { mins[1] = []string{} return } min := limit var p, q int var op byte for _, div := range divs { if n%div == 0 ...
func minToOne(divs: [Int], subs: [Int], upTo n: Int) -> ([Int], [[String]]) { var table = Array(repeating: n + 2, count: n + 1) var how = Array(repeating: [""], count: n + 2) table[1] = 0 how[1] = ["="] for t in 1..<n { let thisPlus1 = table[t] + 1 for div in divs { let dt = div * t if...
Produce a language-to-language conversion: from Go to Swift, same semantics.
package main import "fmt" type FCNode struct { name string weight int coverage float64 children []*FCNode parent *FCNode } func newFCN(name string, weight int, coverage float64) *FCNode { return &FCNode{name, weight, coverage, nil, nil} } func (n *FCNode) addChildren(nodes []*FCNode)...
import Foundation extension String { func paddedLeft(totalLen: Int) -> String { let needed = totalLen - count guard needed > 0 else { return self } return String(repeating: " ", count: needed) + self } } class FCNode { let name: String let weight: Int var coverage: Double { didS...
Change the following Go code into Swift without altering its purpose.
package bank import ( "bytes" "errors" "fmt" "log" "sort" "sync" ) type PID string type RID string type RMap map[RID]int func (m RMap) String() string { rs := make([]string, len(m)) i := 0 for r := range m { rs[i] = string(r) i++ } sort.Strings(rs) var...
import Foundation print("Enter the number of resources: ", terminator: "") guard let resources = Int(readLine(strippingNewline: true)!) else { fatalError() } print("Enter the number of processes: ", terminator: "") guard let processes = Int(readLine(strippingNewline: true)!) else { fatalError() } var running =...
Transform the following Go implementation into Swift, maintaining the same output and logic.
package main import "rcu" func isIdoneal(n int) bool { for a := 1; a < n; a++ { for b := a + 1; b < n; b++ { if a*b+a+b > n { break } for c := b + 1; c < n; c++ { sum := a*b + b*c + a*c if sum == n { re...
import Foundation func isIdoneal(_ n: Int) -> Bool { for a in 1..<n { for b in a + 1..<n { if a * b + a + b > n { break } for c in b + 1..<n { let sum = a * b + b * c + a * c if sum == n { return false ...
Port the following code from Go to Swift with equivalent syntax and logic.
package main import "fmt" const ( right = 1 left = -1 straight = 0 ) func normalize(tracks []int) string { size := len(tracks) a := make([]byte, size) for i := 0; i < size; i++ { a[i] = "abc"[tracks[i]+1] } norm := string(a) for i := 0; i < size; i++ { ...
enum Track: Int, Hashable { case left = -1, straight, right } extension Track: Comparable { static func < (lhs: Track, rhs: Track) -> Bool { return lhs.rawValue < rhs.rawValue } } func < (lhs: [Track], rhs: [Track]) -> Bool { for (l, r) in zip(lhs, rhs) where l != r { return l < r } return false ...
Generate a F# translation of this Go snippet without changing its computational steps.
package main import ( "fmt" "rcu" ) func main() { var numbers []int for i := 2; i < 200; i++ { bds := rcu.DigitSum(i, 2) if rcu.IsPrime(bds) { tds := rcu.DigitSum(i, 3) if rcu.IsPrime(tds) { numbers = append(numbers, i) } } ...
let fN2,fN3=let rec fG n g=function l when l<n->l+g |l->fG n (g+l%n)(l/n) in (fG 2 0, fG 3 0) {0..200}|>Seq.filter(fun n->isPrime(fN2 n) && isPrime(fN3 n))|>Seq.iter(printf "%d "); printfn ""
Produce a language-to-language conversion: from Go to F#, same semantics.
package main import "fmt" func isPrime(n int) bool { if n == 1 { return false } i := 2 for i*i <= n { if n%i == 0 { return false } i++ } return true } func main() { var final, pNum int for i := 1; pNum < 10001; i++ { if isPrime(i) {...
printfn $"%d{Seq.item 10000 (primes32())}"
Rewrite this program in F# while keeping its functionality equivalent to the Go version.
package main import "fmt" func isPrime(n int) bool { if n == 1 { return false } i := 2 for i*i <= n { if n%i == 0 { return false } i++ } return true } func main() { var final, pNum int for i := 1; pNum < 10001; i++ { if isPrime(i) {...
printfn $"%d{Seq.item 10000 (primes32())}"
Change the following Go code into F# without altering its purpose.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(999) sum, n, c := 0, 0, 0 fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:") fmt.Println(" n cumulative sum") for _, p := range primes { n++ sum += p if rcu.IsPri...
primes32()|>Seq.takeWhile((>)1000)|>Seq.scan(fun(n,g) p->(n+1,g+p))(0,0)|>Seq.filter(snd>>isPrime)|>Seq.iter(fun(n,g)->printfn "%3d->%d" n g)
Rewrite the snippet below in F# so it works the same as the original Go code.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(999) sum, n, c := 0, 0, 0 fmt.Println("Summing the first n primes (<1,000) where the sum is itself prime:") fmt.Println(" n cumulative sum") for _, p := range primes { n++ sum += p if rcu.IsPri...
primes32()|>Seq.takeWhile((>)1000)|>Seq.scan(fun(n,g) p->(n+1,g+p))(0,0)|>Seq.filter(snd>>isPrime)|>Seq.iter(fun(n,g)->printfn "%3d->%d" n g)
Translate this program into F# but keep the logic exactly as in Go.
package main import ( "fmt" "os" "golang.org/x/crypto/ssh/terminal" ) func main() { w, h, err := terminal.GetSize(int(os.Stdout.Fd())) if err != nil { fmt.Println(err) return } fmt.Println(h, w) }
open System let bufferHeight = Console.BufferHeight let bufferWidth = Console.BufferWidth let windowHeight = Console.WindowHeight let windowWidth = Console.WindowWidth Console.Write("Buffer Height: ") Console.WriteLine(bufferHeight) Console.Write("Buffer Width: ") Console.WriteLine(bufferWidth) Console.Write("Window ...
Rewrite the snippet below in F# so it works the same as the original Go code.
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } ...
let mP=let mutable n,g=2,0 in primes32()|>Seq.choose(fun y->match y-n>g,n with (true,i)->g<-y-n; n<-y; Some(i,g,y) |_->None) mP|>Seq.takeWhile(fun(_,_,n)->n<1050)|>Seq.iteri(fun i (n,g,l)->printfn "n%d=%d n%d=%d n%d-n%d=%d" i n (i+1) l (i+1) i g)
Can you help me rewrite this code in F# instead of Go, keeping it the same logically?
package main import "fmt" func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true } ...
let mP=let mutable n,g=2,0 in primes32()|>Seq.choose(fun y->match y-n>g,n with (true,i)->g<-y-n; n<-y; Some(i,g,y) |_->None) mP|>Seq.takeWhile(fun(_,_,n)->n<1050)|>Seq.iteri(fun i (n,g,l)->printfn "n%d=%d n%d=%d n%d-n%d=%d" i n (i+1) l (i+1) i g)
Please provide an equivalent version of this Go code in F#.
package main import ( "fmt" "log" "math/big" ) func jacobi(a, n uint64) int { if n%2 == 0 { log.Fatal("'n' must be a positive odd integer") } a %= n result := 1 for a != 0 { for a%2 == 0 { a /= 2 nn := n % 8 if nn == 3 || nn == 5 { ...
let J n m=let rec J n m g=match n with 0->if m=1 then g else 0 |n when n%2=0->J(n/2) m (if m%8=3 || m%8=5 then -g else g) |n->J (m%n) n (if m%4=3 && n%4=3 then -g else g) J (n%m) m 1 printfn "n\m 1 2 3 4 5 6 7 8 ...
Translate this program into F# but keep the logic exactly as in Go.
package main import ( "fmt" "log" "math/big" ) func jacobi(a, n uint64) int { if n%2 == 0 { log.Fatal("'n' must be a positive odd integer") } a %= n result := 1 for a != 0 { for a%2 == 0 { a /= 2 nn := n % 8 if nn == 3 || nn == 5 { ...
let J n m=let rec J n m g=match n with 0->if m=1 then g else 0 |n when n%2=0->J(n/2) m (if m%8=3 || m%8=5 then -g else g) |n->J (m%n) n (if m%4=3 && n%4=3 then -g else g) J (n%m) m 1 printfn "n\m 1 2 3 4 5 6 7 8 ...
Rewrite this program in F# while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math/big" "rcu" ) func main() { count := 0 limit := 25 n := int64(17) repunit := big.NewInt(1111111111111111) t := new(big.Int) zero := new(big.Int) eleven := big.NewInt(11) hundred := big.NewInt(100) var deceptive []int64 for count < li...
Seq.unfold(fun n->Some(n|>Seq.filter(isPrime>>not)|>Seq.filter(fun n->(10I**(n-1)-1I)%(bigint n)=0I),n|>Seq.map((+)30)))(seq{1;7;11;13;17;19;23;29})|>Seq.concat|>Seq.skip 1 |>Seq.chunkBySize 10|>Seq.take 7|>Seq.iter(fun n->n|>Array.iter(printf "%7d "); printfn "")
Produce a language-to-language conversion: from Go to F#, same semantics.
package main import ( "fmt" "math/big" "rcu" ) func main() { count := 0 limit := 25 n := int64(17) repunit := big.NewInt(1111111111111111) t := new(big.Int) zero := new(big.Int) eleven := big.NewInt(11) hundred := big.NewInt(100) var deceptive []int64 for count < li...
Seq.unfold(fun n->Some(n|>Seq.filter(isPrime>>not)|>Seq.filter(fun n->(10I**(n-1)-1I)%(bigint n)=0I),n|>Seq.map((+)30)))(seq{1;7;11;13;17;19;23;29})|>Seq.concat|>Seq.skip 1 |>Seq.chunkBySize 10|>Seq.take 7|>Seq.iter(fun n->n|>Array.iter(printf "%7d "); printfn "")
Port the following code from Go to F# with equivalent syntax and logic.
package main import ( "fmt" "rcu" "strings" ) func main() { var numbers []int for n := 0; n < 1000; n++ { ns := fmt.Sprintf("%d", n) ds := fmt.Sprintf("%d", rcu.DigitSum(n, 10)) if strings.Contains(ns, ds) { numbers = append(numbers, n) } } fmt.P...
let rec fG n g=match (n/10,n%(if g<10 then 10 else 100)) with (_,n) when n=g->true |(0,_)->false |(n,_)->fG n g let rec fN g=function n when n<10->n+g |n->fN(g+n%10)(n/10) {1..999}|>Seq.filter(fun n->fG n (fN 0 n))|>Seq.iter(printf "%d "); printfn ""
Please provide an equivalent version of this Go code in F#.
package main import ( "fmt" "rcu" "strings" ) func main() { var numbers []int for n := 0; n < 1000; n++ { ns := fmt.Sprintf("%d", n) ds := fmt.Sprintf("%d", rcu.DigitSum(n, 10)) if strings.Contains(ns, ds) { numbers = append(numbers, n) } } fmt.P...
let rec fG n g=match (n/10,n%(if g<10 then 10 else 100)) with (_,n) when n=g->true |(0,_)->false |(n,_)->fG n g let rec fN g=function n when n<10->n+g |n->fN(g+n%10)(n/10) {1..999}|>Seq.filter(fun n->fG n (fN 0 n))|>Seq.iter(printf "%d "); printfn ""
Write the same code in F# as shown below in Go.
package main import ( "math/rand" "fmt" ) func main() { list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} for i := 1; i <= 10; i++ { sattoloCycle(list) fmt.Println(list) } } func sattoloCycle(list []int) { for x := len(list) -1; x > 0; x-- { j := rand.Intn(x) list[x], list[j] = list[j], list[x] } }
let rnd=System.Random() let sottolo(n:int[])=let rec fN g=match g with -1|0->() |_->let e=rnd.Next(g-1) in let l=n.[g] in n.[g]<-n.[e]; n.[e]<-l; fN (g-1) in fN((Array.length n)-1) [[||];[|10|];[|10;20|];[|10;20;30|];[|11..22|]]|>List.iter(fun n->printf "%A->" n; sottolo n; printfn "%A" n)
Produce a functionally identical F# code for the snippet given in Go.
package main import ( "math/rand" "fmt" ) func main() { list := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} for i := 1; i <= 10; i++ { sattoloCycle(list) fmt.Println(list) } } func sattoloCycle(list []int) { for x := len(list) -1; x > 0; x-- { j := rand.Intn(x) list[x], list[j] = list[j], list[x] } }
let rnd=System.Random() let sottolo(n:int[])=let rec fN g=match g with -1|0->() |_->let e=rnd.Next(g-1) in let l=n.[g] in n.[g]<-n.[e]; n.[e]<-l; fN (g-1) in fN((Array.length n)-1) [[||];[|10|];[|10;20|];[|10;20;30|];[|11..22|]]|>List.iter(fun n->printf "%A->" n; sottolo n; printfn "%A" n)
Write the same code in F# as shown below in Go.
package main import "fmt" func sieve(limit uint64) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := uint64(3) for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i += 2 * p { c[i] = true ...
printfn "twin primes below 100000: %d" (primes64()|>Seq.takeWhile(fun n->n<=100000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length) printfn "twin primes below 1000000: %d" (primes64()|>Seq.takeWhile(fun n->n<=1000000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length) printfn "twin primes below 1000000...
Keep all operations the same but rewrite the snippet in F#.
package main import "fmt" func sameDigits(n, b int) bool { f := n % b n /= b for n > 0 { if n%b != f { return false } n /= b } return true } func isBrazilian(n int) bool { if n < 7 { return false } if n%2 == 0 && n >= 8 { return true...
let isBraz α=let mutable n,i,g=α,α+1,1 in (fun β->(while (i*g)<β do if g<α-1 then g<-g+1 else (n<-n*α; i<-n+i; g<-1)); β=i*g) let Brazilian()=let rec fN n g=seq{if List.exists(fun α->α n) g then yield n yield! fN (n+1) ((isBraz (n-1))::g)} fN 4 [isBraz 2]
Write the same code in F# as shown below in Go.
package main import "fmt" func sameDigits(n, b int) bool { f := n % b n /= b for n > 0 { if n%b != f { return false } n /= b } return true } func isBrazilian(n int) bool { if n < 7 { return false } if n%2 == 0 && n >= 8 { return true...
let isBraz α=let mutable n,i,g=α,α+1,1 in (fun β->(while (i*g)<β do if g<α-1 then g<-g+1 else (n<-n*α; i<-n+i; g<-1)); β=i*g) let Brazilian()=let rec fN n g=seq{if List.exists(fun α->α n) g then yield n yield! fN (n+1) ((isBraz (n-1))::g)} fN 4 [isBraz 2]
Can you help me rewrite this code in F# instead of Go, keeping it the same logically?
package main import ( "archive/tar" "compress/gzip" "flag" "io" "log" "os" "time" ) func main() { filename := flag.String("file", "TAPE.FILE", "filename within TAR") data := flag.String("data", "", "data for file") outfile := flag.String(...
open System open System.IO let env = Environment.OSVersion.Platform let msg = "Hello Rosetta!" match env with | PlatformID.Win32NT | PlatformID.Win32S | PlatformID.Win32Windows | PlatformID.WinCE -> File.WriteAllText("TAPE.FILE", msg) | _ -> File.WriteAllText("/dev/tape", msg)
Please provide an equivalent version of this Go code in F#.
package main import "fmt" type Func func(int) int type FuncFunc func(Func) Func type RecursiveFunc func (RecursiveFunc) Func func main() { fac := Y(almost_fac) fib := Y(almost_fib) fmt.Println("fac(10) = ", fac(10)) fmt.Println("fib(10) = ", fib(10)) } func Y(f FuncFunc) Func { g := func(r RecursiveFunc) Func ...
type 'a mu = Roll of ('a mu -> 'a) let unroll (Roll x) = x let fix f = let g = fun x a -> f (unroll x x) a in g (Roll g) let fac = fix (fun f n i -> if i < 2 then n else f (bigint i * n) (i - 1)) <| 1I let fib = fix (fun fnc f s i -> if i < 2 then f else fnc s (f + s) (i - 1)) 1I 1I [<...
Write the same code in F# as shown below in Go.
package main import ( "fmt" "strconv" ) func main() { var fact [12]uint64 fact[0] = 1 for n := uint64(1); n < 12; n++ { fact[n] = fact[n-1] * n } for b := 9; b <= 12; b++ { fmt.Printf("The factorions for base %d are:\n", b) for i := uint64(1); i < 1500000; i++...
let N=[|let mutable n=1 in yield n; for g in 1..11 do n<-n*g; yield n|] let fG n g=let rec fN g=function i when i<n->g+N.[i] |i->fN(g+N.[i%n])(i/n) in fN 0 g {9..12}|>Seq.iter(fun n->printf $"In base %d{n} Factorians are:"; {1..1500000}|>Seq.iter(fun g->if g=fG n g then printf $" %d{g}"); printfn "")
Generate an equivalent F# version of this Go code.
package main import ( "fmt" "strconv" ) func main() { var fact [12]uint64 fact[0] = 1 for n := uint64(1); n < 12; n++ { fact[n] = fact[n-1] * n } for b := 9; b <= 12; b++ { fmt.Printf("The factorions for base %d are:\n", b) for i := uint64(1); i < 1500000; i++...
let N=[|let mutable n=1 in yield n; for g in 1..11 do n<-n*g; yield n|] let fG n g=let rec fN g=function i when i<n->g+N.[i] |i->fN(g+N.[i%n])(i/n) in fN 0 g {9..12}|>Seq.iter(fun n->printf $"In base %d{n} Factorians are:"; {1..1500000}|>Seq.iter(fun g->if g=fG n g then printf $" %d{g}"); printfn "")
Change the programming language of this snippet from Go to F# without modifying what it does.
package main import "fmt" func sumDivisors(n int) int { sum := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { sum += i j := n / i if j != i { sum += j } } i += k } return...
let sod u=let P=primes32() let rec fN g=match u%g with 0->g |_->fN(Seq.head P) let rec fG n i g e l=match n=u,u%l with (true,_)->e*g |(_,0)->fG (n*i) i g (e+l)(l*i) |_->let q=fN(Seq.head P) in fG n q (g*e) 1 q let n=Seq.head P in fG 1 n 1 1 n [1..100]|>Seq.iter(sod>>printf "%d "); printfn...
Generate an equivalent F# version of this Go code.
package main import "fmt" func sumDivisors(n int) int { sum := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { sum += i j := n / i if j != i { sum += j } } i += k } return...
let sod u=let P=primes32() let rec fN g=match u%g with 0->g |_->fN(Seq.head P) let rec fG n i g e l=match n=u,u%l with (true,_)->e*g |(_,0)->fG (n*i) i g (e+l)(l*i) |_->let q=fN(Seq.head P) in fG n q (g*e) 1 q let n=Seq.head P in fG 1 n 1 1 n [1..100]|>Seq.iter(sod>>printf "%d "); printfn...
Preserve the algorithm and functionality while converting the code from Go to F#.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(79) ix := 0 n := 1 count := 0 var pi []int for { if primes[ix] <= n { count++ if count == 22 { break } ix++ } n++ pi =...
let fN=let i=primes32() in Seq.unfold(fun(n,g,l)->Some(l,if n=g then (n+1,Seq.head i,l+1) else (n+1,g,l)))(1,Seq.head i,0) fN|>Seq.takeWhile((>)22)|>Seq.chunkBySize 20|>Seq.iter(fun n->Array.iter(printf "%2d ") n; printfn "")
Translate this program into F# but keep the logic exactly as in Go.
package main import ( "fmt" "rcu" ) func main() { primes := rcu.Primes(79) ix := 0 n := 1 count := 0 var pi []int for { if primes[ix] <= n { count++ if count == 22 { break } ix++ } n++ pi =...
let fN=let i=primes32() in Seq.unfold(fun(n,g,l)->Some(l,if n=g then (n+1,Seq.head i,l+1) else (n+1,g,l)))(1,Seq.head i,0) fN|>Seq.takeWhile((>)22)|>Seq.chunkBySize 20|>Seq.iter(fun n->Array.iter(printf "%2d ") n; printfn "")
Convert this Go snippet to F# and keep its semantics consistent.
package main import ( "fmt" "sort" "strings" ) var count int = 0 func interactiveCompare(s1, s2 string) bool { count++ fmt.Printf("(%d) Is %s < %s? ", count, s1, s2) var response string _, err := fmt.Scanln(&response) return err == nil && strings.HasPrefix(response, "y") } func main...
let clrs=let n=System.Random() in lN2p [|for g in 7..-1..2->n.Next(g)|] [|"Red";"Orange";"Yellow";"Green";"Blue";"Indigo";"Violet"|] let rec fG n g=printfn "Is %s less than %s" n g; match System.Console.ReadLine() with "Yes"-> -1|"No"->1 |_->printfn "Enter Yes or No"; fG n g let mutable z=0 in printfn "%A sorted to %A...
Convert this Go snippet to F# and keep its semantics consistent.
package main import ( "fmt" "sync" ) var a = []int{170, 45, 75, 90, 802, 24, 2, 66} var aMax = 1000 const bead = 'o' func main() { fmt.Println("before:", a) beadSort() fmt.Println("after: ", a) } func beadSort() { all := make([]byte, aMax*len(a)) abacus := make([][]byte, ...
open System let removeEmptyLists lists = lists |> List.filter (not << List.isEmpty) let flip f x y = f y x let rec transpose = function | [] -> [] | lists -> (List.map List.head lists) :: transpose(removeEmptyLists (List.map List.tail lists)) let beadSort = List.map List.sum << transpose << transpose << ...
Transform the following Go implementation into F#, maintaining the same output and logic.
package main import "fmt" func countDivisors(n int) int { count := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { count++ j := n / i if j != i { count++ } } i += k } retu...
let tau u=let P=primes32() let rec fN g=match u%g with 0->g |_->fN(Seq.head P) let rec fG n i g e l=match n=u,u%l with (true,_)->e |(_,0)->fG (n*i) i g (e+g)(l*i) |_->let q=fN(Seq.head P) in fG (n*q) q e (e+e) (q*q) let n=Seq.head P in fG 1 n 1 1 n [1..100]|>Seq.iter(tau>>printf "%d "); p...
Generate an equivalent F# version of this Go code.
package main import "fmt" func countDivisors(n int) int { count := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { count++ j := n / i if j != i { count++ } } i += k } retu...
let tau u=let P=primes32() let rec fN g=match u%g with 0->g |_->fN(Seq.head P) let rec fG n i g e l=match n=u,u%l with (true,_)->e |(_,0)->fG (n*i) i g (e+g)(l*i) |_->let q=fN(Seq.head P) in fG (n*q) q e (e+e) (q*q) let n=Seq.head P in fG 1 n 1 1 n [1..100]|>Seq.iter(tau>>printf "%d "); p...
Transform the following Go implementation into F#, maintaining the same output and logic.
package main import "fmt" func möbius(to int) []int { if to < 1 { to = 1 } mobs := make([]int, to+1) primes := []int{2} for i := 1; i <= to; i++ { j := i cp := 0 spf := false for _, p := range primes { if p > j { break ...
let fN g=let n=primes32() let rec fN i g e l=match (l/g,l%g,e) with (1,0,false)->i |(n,0,false)->fN (0-i) g true n |(_,0,true) ->0 |_ ->fN i (Seq.head ...
Convert this Go snippet to F# and keep its semantics consistent.
package main import ( "fmt" "rcu" ) func contains(a []int, v int) bool { for _, e := range a { if e == v { return true } } return false } func main() { const limit = 50 cpt := []int{1, 2} for { m := 1 l := len(cpt) for contains(cpt, ...
let rec fN g=function 0->g=1 |n->fN n (g%n) let rec fG t n1 n2=seq{let n=seq{1..0x0FFFFFFF}|>Seq.find(fun n->not(List.contains n t) && fN n1 n && fN n2 n) in yield n; yield! cT(n::t) n2 n} let cT=seq{yield 1; yield 2; yield! fG [1;2] 1 2} cT|>Seq.takeWhile((>)50)|>Seq.iter(printf "%d "); printfn ""
Please provide an equivalent version of this Go code in F#.
package main import ( "fmt" "rcu" ) func contains(a []int, v int) bool { for _, e := range a { if e == v { return true } } return false } func main() { const limit = 50 cpt := []int{1, 2} for { m := 1 l := len(cpt) for contains(cpt, ...
let rec fN g=function 0->g=1 |n->fN n (g%n) let rec fG t n1 n2=seq{let n=seq{1..0x0FFFFFFF}|>Seq.find(fun n->not(List.contains n t) && fN n1 n && fN n2 n) in yield n; yield! cT(n::t) n2 n} let cT=seq{yield 1; yield 2; yield! fG [1;2] 1 2} cT|>Seq.takeWhile((>)50)|>Seq.iter(printf "%d "); printfn ""
Convert this Go snippet to F# and keep its semantics consistent.
package main import "fmt" func mertens(to int) ([]int, int, int) { if to < 1 { to = 1 } merts := make([]int, to+1) primes := []int{2} var sum, zeros, crosses int for i := 1; i <= to; i++ { j := i cp := 0 spf := false for _, p := range primes { ...
let mertens=mobius|>Seq.scan((+)) 0|>Seq.tail mertens|>Seq.take 500|>Seq.chunkBySize 25|>Seq.iter(fun n->Array.iter(printf "%3d") n;printfn "\n####") let n=mertens|>Seq.take 1000|>Seq.mapi(fun n g->(n+1,g))|>Seq.groupBy snd|>Map.ofSeq n|>Map.iter(fun n g->printf "%3d->" n; g|>Seq.iter(fun(n,_)->printf "%3d " n); print...
Rewrite the snippet below in F# so it works the same as the original Go code.
package main import ( "fmt" "rcu" ) func main() { limit := int(1e6) lowerLimit := 2500 c := rcu.PrimeSieve(limit-1, true) var erdos []int lastErdos := 0 ec := 0 for i := 2; i < limit; { if !c[i] { found := true for j, fact := 1, 1; fact < i; { ...
let rec fN g=function 1->g |n->fN(g*n)(n-1) let rec fG n g=seq{let i=fN 1 n in if i<g then yield (isPrime>>not)(g-i); yield! fG(n+1) g} let eP()=primes32()|>Seq.filter(fG 1>>Seq.forall id) eP()|>Seq.takeWhile((>)2500)|>Seq.iter(printf "%d "); printfn "\n\n7875th Erdős prime is %d" (eP()|>Seq.item 7874)
Rewrite the snippet below in F# so it works the same as the original Go code.
package main import ( "fmt" "rcu" ) func main() { limit := int(1e6) lowerLimit := 2500 c := rcu.PrimeSieve(limit-1, true) var erdos []int lastErdos := 0 ec := 0 for i := 2; i < limit; { if !c[i] { found := true for j, fact := 1, 1; fact < i; { ...
let rec fN g=function 1->g |n->fN(g*n)(n-1) let rec fG n g=seq{let i=fN 1 n in if i<g then yield (isPrime>>not)(g-i); yield! fG(n+1) g} let eP()=primes32()|>Seq.filter(fG 1>>Seq.forall id) eP()|>Seq.takeWhile((>)2500)|>Seq.iter(printf "%d "); printfn "\n\n7875th Erdős prime is %d" (eP()|>Seq.item 7874)
Ensure the translated F# code behaves exactly like the original Go snippet.
package main import ( "fmt" "rcu" ) func main() { pairs := [][2]int{{21, 15}, {17, 23}, {36, 12}, {18, 29}, {60, 15}} fmt.Println("The following pairs of numbers are coprime:") for _, pair := range pairs { if rcu.Gcd(pair[0], pair[1]) == 1 { fmt.Println(pair) } } }
let rec fN g=function 0->g=1 |n->fN n (g%n) [(21,15);(17,23);(36,12);(18,29);(60,15)] |> List.filter(fun(n,g)->fN n g)|>List.iter(fun(n,g)->printfn "%d and %d are coprime" n g)
Convert this Go block to F#, preserving its control flow and logic.
package main import ( "fmt" "rcu" ) func main() { pairs := [][2]int{{21, 15}, {17, 23}, {36, 12}, {18, 29}, {60, 15}} fmt.Println("The following pairs of numbers are coprime:") for _, pair := range pairs { if rcu.Gcd(pair[0], pair[1]) == 1 { fmt.Println(pair) } } }
let rec fN g=function 0->g=1 |n->fN n (g%n) [(21,15);(17,23);(36,12);(18,29);(60,15)] |> List.filter(fun(n,g)->fN n g)|>List.iter(fun(n,g)->printfn "%d and %d are coprime" n g)
Rewrite this program in F# while keeping its functionality equivalent to the Go version.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 unsigned := true l := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { l[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { l[n][k] = new(big.Int) } ...
let fact(n:int)=let rec fact=function n when n=0I->1I |n->n*fact(n-1I) in fact(bigint n) let rec lah=function (_,0)|(0,_)->0I |(n,1)->fact n |(n,g) when n=g->1I |(n,g)->((fact n)*(fact(n-1)))/((fact g)*(fact(g-1)))/(fact(n-g)) for n in {0..12} do (for g in {0..n} do printf $"%A{lah(n,g)} "); printfn "" printfn $"\n\n%...
Transform the following Go implementation into F#, maintaining the same output and logic.
package main import ( "fmt" "math/big" ) func main() { limit := 100 last := 12 unsigned := true l := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { l[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { l[n][k] = new(big.Int) } ...
let fact(n:int)=let rec fact=function n when n=0I->1I |n->n*fact(n-1I) in fact(bigint n) let rec lah=function (_,0)|(0,_)->0I |(n,1)->fact n |(n,g) when n=g->1I |(n,g)->((fact n)*(fact(n-1)))/((fact g)*(fact(g-1)))/(fact(n-g)) for n in {0..12} do (for g in {0..n} do printf $"%A{lah(n,g)} "); printfn "" printfn $"\n\n%...
Keep all operations the same but rewrite the snippet in F#.
package main import "fmt" func twoSum(a []int, targetSum int) (int, int, bool) { len := len(a) if len < 2 { return 0, 0, false } for i := 0; i < len - 1; i++ { if a[i] <= targetSum { for j := i + 1; j < len; j++ { sum := a[i] + a[j] if sum ==...
let fN n i = let rec fN n e = match n with |n::g when n < i -> match List.mapi(fun g i-> (n,i,g)) g |> List.tryFind(fun (n,g,l)->(n+g)=i) with |Some (n,g,l) -> [e;e+l+1] |_ -> fN g (e+1) |_ -> [] fN n 0 printfn "%A" (fN [0; 2; 11;...
Convert this Go snippet to F# and keep its semantics consistent.
package main import "fmt" func twoSum(a []int, targetSum int) (int, int, bool) { len := len(a) if len < 2 { return 0, 0, false } for i := 0; i < len - 1; i++ { if a[i] <= targetSum { for j := i + 1; j < len; j++ { sum := a[i] + a[j] if sum ==...
let fN n i = let rec fN n e = match n with |n::g when n < i -> match List.mapi(fun g i-> (n,i,g)) g |> List.tryFind(fun (n,g,l)->(n+g)=i) with |Some (n,g,l) -> [e;e+l+1] |_ -> fN g (e+1) |_ -> [] fN n 0 printfn "%A" (fN [0; 2; 11;...
Can you help me rewrite this code in F# instead of Go, keeping it the same logically?
package main import ( "fmt" "strconv" ) func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false ...
let rec fN i g e l=seq{yield! [0..9]|>Seq.map(fun n->n*g+e+l); if g>1 then let g=g/10 in yield! fN(i+g*(e/g)) g (e%g) i} let fG(n,g)=fN(n*(g/n)) n (g%n) 0|>Seq.exists(isPrime) let uP()=let rec fN n g=seq{yield! {n..g-1}|>Seq.map(fun g->(n,g)); yield! fN(g)(g*10)} in fN 1 10|>Seq.filter(fG>>not)|>Seq.map snd
Write the same code in F# as shown below in Go.
package main import "fmt" func countDivisors(n int) int { count := 0 i := 1 k := 2 if n%2 == 0 { k = 1 } for i*i <= n { if n%i == 0 { count++ j := n / i if j != i { count++ } } i += k } retu...
Seq.initInfinite((+)1)|>Seq.filter(fun n->n%(tau n)=0)|>Seq.take 100|>Seq.iter(printf "%d "); printfn ""
Maintain the same structure and functionality when rewriting this code in F#.
package main import ( "fmt" big "github.com/ncw/gmp" "time" ) func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i...
let rec fN g=function n when n<10->n+g=25 |n->fN(g+n%10)(n/10) primes32()|>Seq.takeWhile((>)5000)|>Seq.filter fN|>Seq.iter(printf "%d "); printfn ""
Ensure the translated F# code behaves exactly like the original Go snippet.
package main import ( "fmt" big "github.com/ncw/gmp" "time" ) func sieve(limit int) []bool { limit++ c := make([]bool, limit) c[0] = true c[1] = true p := 3 for { p2 := p * p if p2 >= limit { break } for i := p2; i < limit; i...
let rec fN g=function n when n<10->n+g=25 |n->fN(g+n%10)(n/10) primes32()|>Seq.takeWhile((>)5000)|>Seq.filter fN|>Seq.iter(printf "%d "); printfn ""
Produce a functionally identical F# code for the snippet given in Go.
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) }...
let rec fN g=let g=[for n in [2;3;5;7] do for g in g->n::g]|>List.groupBy(fun n->match List.sum n with 13->'n' |n when n<12->'g' |_->'x')|>Map.ofSeq [yield! (if g.ContainsKey 'n' then g.['n'] else []); yield! (if g.ContainsKey 'g' then fN g.['g'] else [])] fN [[]] |> Seq.iter(fun n->n|>List.iter(printf "%...
Write a version of this Go function in F# with identical behavior.
package main import ( "fmt" "sort" "strconv" ) func combrep(n int, lst []byte) [][]byte { if n == 0 { return [][]byte{nil} } if len(lst) == 0 { return nil } r := combrep(n, lst[1:]) for _, x := range combrep(n-1, lst) { r = append(r, append(x, lst[0])) }...
let rec fN g=let g=[for n in [2;3;5;7] do for g in g->n::g]|>List.groupBy(fun n->match List.sum n with 13->'n' |n when n<12->'g' |_->'x')|>Map.ofSeq [yield! (if g.ContainsKey 'n' then g.['n'] else []); yield! (if g.ContainsKey 'g' then fN g.['g'] else [])] fN [[]] |> Seq.iter(fun n->n|>List.iter(printf "%...
Please provide an equivalent version of this Go code in F#.
package main import ( "fmt" big "github.com/ncw/gmp" "strings" ) func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { ...
let fG n g=let rec fG y=if y=g then true else if y>g && isPrime y then fG(10*(y%n)+y/n) else false in fG(10*(g%n)+g/n) let rec fN g l=seq{let g=[for n in g do for g in [1;3;7;9] do let g=n*10+g in yield g] in yield! g|>List.filter(fun n->isPrime n && fG l n); yield! fN g (l*10)} let circP()=seq{yield! [2;3;5;7]; yield...
Generate a F# translation of this Go snippet without changing its computational steps.
package main import "fmt" func main() { fmt.Println(root(3, 8)) fmt.Println(root(3, 9)) fmt.Println(root(2, 2e18)) } func root(N, X int) int { for r := 1; ; { x := X for i := 1; i < N; i++ { x /= r } x -= r Δ...
open System let iroot (base_ : bigint) n = if base_ < bigint.Zero || n <= 0 then raise (ArgumentException "Bad parameter") let n1 = n - 1 let n2 = bigint n let n3 = bigint n1 let mutable c = bigint.One let mutable d = (n3 + base_) / n2 let mutable e = ((n3 * d) + (base_ / bigint.Po...
Produce a functionally identical F# code for the snippet given in Go.
package main import "fmt" func main() { fmt.Println(root(3, 8)) fmt.Println(root(3, 9)) fmt.Println(root(2, 2e18)) } func root(N, X int) int { for r := 1; ; { x := X for i := 1; i < N; i++ { x /= r } x -= r Δ...
open System let iroot (base_ : bigint) n = if base_ < bigint.Zero || n <= 0 then raise (ArgumentException "Bad parameter") let n1 = n - 1 let n2 = bigint n let n3 = bigint n1 let mutable c = bigint.One let mutable d = (n3 + base_) / n2 let mutable e = ((n3 * d) + (base_ / bigint.Po...
Rewrite the snippet below in F# so it works the same as the original Go code.
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
namespace ScriptedMain module ScriptedMain = let meaningOfLife = 42 let main = printfn "Main: The meaning of life is %d" meaningOfLife
Change the following Go code into F# without altering its purpose.
package main import "fmt" func MeaningOfLife() int { return 42 } func libMain() { fmt.Println("The meaning of life is", MeaningOfLife()) }
namespace ScriptedMain module ScriptedMain = let meaningOfLife = 42 let main = printfn "Main: The meaning of life is %d" meaningOfLife
Maintain the same structure and functionality when rewriting this code in F#.
package main import "fmt" func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d...
let fN g=1+((g-1)%9) in primes32()|>Seq.skipWhile((>)500)|>Seq.takeWhile((>)1000)|>Seq.filter(fN>>isPrime)|>Seq.iter(printf "%d "); printfn ""