Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Generate a Swift translation of this Go snippet without changing its computational steps. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
"unicode/utf8"
)
func isVowel(c rune) bool { return strings.ContainsRune("aeiou", c) }
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file... | import Foundation
func isVowel(_ char: Character) -> Bool {
switch (char) {
case "a", "A", "e", "E", "i", "I", "o", "O", "u", "U":
return true
default:
return false
}
}
func alternatingVowelsAndConsonants(word: String) -> Bool {
return zip(word, word.dropFirst()).allSatisfy{isVowel... |
Rewrite this program in Swift while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"math"
)
const (
RE = 6371000
DD = 0.001
FIN = 1e7
)
func rho(a float64) float64 { return math.Exp(-a / 8500) }
func radians(degrees float64) float64 { return degrees * math.Pi / 180 }
func height(a, z, d float64) float64 {
aa := RE + a
hh := ... | import Foundation
extension Double {
var radians: Double { self * .pi / 180 }
}
func columnDensity(_ a: Double, _ z: Double) -> Double {
func rho(_ a: Double) -> Double {
exp(-a / 8500)
}
func height(_ d: Double) -> Double {
let aa = 6_371_000 + a
let hh = aa * aa + d * d - 2 * d * aa * cos((180 ... |
Change the following Go code into Swift without altering its purpose. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
"unicode/utf8"
)
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
var words []string
for _... | import Foundation
let minLength = 12
let substring = "the"
do {
try String(contentsOfFile: "unixdict.txt", encoding: String.Encoding.ascii)
.components(separatedBy: "\n")
.filter{$0.count >= minLength && $0.contains(substring)}
.enumerated()
.forEach{print(String(format: "%2d. %@",... |
Convert the following code from Go to Swift, ensuring the logic remains intact. | package main
import (
"fmt"
"unsafe"
)
func main() {
myVar := 3.14
myPointer := &myVar
fmt.Println("Address:", myPointer, &myVar)
fmt.Printf("Address: %p %p\n", myPointer, &myVar)
var addr64 int64
var addr32 int32
ptr := unsafe.Pointer(myPointer)
if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) {
addr64 = ... | class MyClass { }
func printAddress<T>(of pointer: UnsafePointer<T>) {
print(pointer)
}
func test() {
var x = 42
var y = 3.14
var z = "foo"
var obj = MyClass()
withUnsafePointer(to: &x) { print($0) }
withUnsafePointer(to: &y) { print($0) }
withUnsafePointer(to: &z) { print(... |
Translate this program into Swift but keep the logic exactly as in Go. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"unicode/utf8"
)
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
count := 0
for _, bword := range bword... | import Foundation
do {
try String(contentsOfFile: "unixdict.txt", encoding: String.Encoding.ascii)
.components(separatedBy: "\n")
.filter{$0.count > 5 && $0.prefix(3) == $0.suffix(3)}
.enumerated()
.forEach{print("\($0.0 + 1). \($0.1)")}
} catch {
print(error.localizedDescriptio... |
Preserve the algorithm and functionality while converting the code from Go to Swift. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"unicode/utf8"
)
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
var words []string
for _, bword := ran... | import Foundation
func containsAllVowelsOnce(_ word: String) -> Bool {
var vowels = 0
for ch in word {
var bit = 0
switch (ch) {
case "a", "A":
bit = 1
case "e", "E":
bit = 2
case "i", "I":
bit = 4
case "o", "O":
bi... |
Convert the following code from Go to Swift, ensuring the logic remains intact. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"sort"
"strings"
)
func main() {
wordList := "unixdict.txt"
b, err := ioutil.ReadFile(wordList)
if err != nil {
log.Fatal("Error reading file")
}
bwords := bytes.Fields(b)
words := make([]string, len(bwords))... | import Foundation
let minLength = 5
func loadDictionary(_ path: String) throws -> Set<String> {
let contents = try String(contentsOfFile: path, encoding: String.Encoding.ascii)
return Set<String>(contents.components(separatedBy: "\n").filter{$0.count >= minLength})
}
func pad(string: String, width: Int) -> S... |
Ensure the translated Swift code behaves exactly like the original Go snippet. | package main
import (
"fmt"
"math"
)
type rule func(float64, float64) float64
var dxs = []float64{
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0... | import Foundation
let dxs = [
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -... |
Write the same algorithm in Swift as shown in this Go implementation. | package main
import (
"fmt"
"math"
)
type rule func(float64, float64) float64
var dxs = []float64{
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0... | import Foundation
let dxs = [
-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,
-0.095, 0.695, 0.340, -... |
Port the provided Go code into Swift while preserving the original functionality. | package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
var cave = map[int][3]int{
1: {2, 3, 4}, 2: {1, 5, 6}, 3: {1, 7, 8}, 4: {1, 9, 10}, 5: {2, 9, 11},
6: {2, 7, 12}, 7: {3, 6, 13}, 8: {3, 10, 14}, 9: {4, 5, 15}, 10: {4, 8, 16},
11: {5, 12... | import Foundation
var cave: [Int:[Int]] = [
1: [2, 3, 4],
2: [1, 5, 6],
3: [1, 7, 8],
4: [1, 9, 10],
5: [2, 9, 11],
6: [2, 7, 12],
7: [3, 6, 13],
8: [3, 10, 14],
9: [4, 5, 15],
10: [4, 8, 16],
11: [5, 12, 17],
12: [6, 11, 18],
13: [7, 14, 18],
14: [8, 13, 19],
... |
Can you help me rewrite this code in Swift instead of Go, keeping it the same logically? | package main
import "fmt"
func main() {
for {
fmt.Printf("SPAM\n")
}
}
| while true {
println("SPAM")
}
|
Generate a Swift translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"math"
"bytes"
"encoding/binary"
)
type testCase struct {
hashCode string
string
}
var testCases = []testCase{
{"d41d8cd98f00b204e9800998ecf8427e", ""},
{"0cc175b9c0f1b6a831c399e269772661", "a"},
{"900150983cd24fb0d6963f7d28e17f72", "abc"},
{"f96b69... | import Foundation
public class MD5 {
private let s: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, ... |
Write the same code in Swift as shown below in Go. | package main
import (
"fmt"
"sort"
"sync"
"time"
)
type history struct {
timestamp tsFunc
hs []hset
}
type tsFunc func() time.Time
type hset struct {
int
t time.Time
}
func newHistory(ts tsFunc) history {
return history{ts, []hset{{t: ts()}}}
}
... | var historyOfHistory = [Int]()
var history:Int = 0 {
willSet {
historyOfHistory.append(history)
}
}
history = 2
history = 3
history = 4
println(historyOfHistory)
|
Generate a Swift translation of this Go snippet without changing its computational steps. | func multiply(a, b float64) float64 {
return a * b
}
| func multiply(a: Double, b: Double) -> Double {
return a * b
}
|
Write the same algorithm in Swift as shown in this Go implementation. | 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 {
... | import Foundation
func jacobi(a: Int, n: Int) -> Int {
var a = a % n
var n = n
var res = 1
while a != 0 {
while a & 1 == 0 {
a >>= 1
if n % 8 == 3 || n % 8 == 5 {
res = -res
}
}
(a, n) = (n, a)
if a % 4 == 3 && n % 4 == 3 {
res = -res
}
a %= n
... |
Preserve the algorithm and functionality while converting the code from Go to Swift. | 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 {
... | import Foundation
func jacobi(a: Int, n: Int) -> Int {
var a = a % n
var n = n
var res = 1
while a != 0 {
while a & 1 == 0 {
a >>= 1
if n % 8 == 3 || n % 8 == 5 {
res = -res
}
}
(a, n) = (n, a)
if a % 4 == 3 && n % 4 == 3 {
res = -res
}
a %= n
... |
Convert this Go snippet to Swift and keep its semantics consistent. | 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]
}
}
| extension Array {
public mutating func satalloShuffle() {
for i in stride(from: index(before: endIndex), through: 1, by: -1) {
swapAt(i, .random(in: 0..<i))
}
}
public func satalloShuffled() -> [Element] {
var arr = Array(self)
arr.satalloShuffle()
return arr
}
}
let testCases = [
... |
Port the following code from Go to Swift with equivalent syntax and logic. | 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]
}
}
| extension Array {
public mutating func satalloShuffle() {
for i in stride(from: index(before: endIndex), through: 1, by: -1) {
swapAt(i, .random(in: 0..<i))
}
}
public func satalloShuffled() -> [Element] {
var arr = Array(self)
arr.satalloShuffle()
return arr
}
}
let testCases = [
... |
Change the following Go code into Swift without altering its purpose. | 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 ... | struct RecursiveFunc<F> {
let o : RecursiveFunc<F> -> F
}
func Y<A, B>(f: (A -> B) -> A -> B) -> A -> B {
let r = RecursiveFunc<A -> B> { w in f { w.o(w)($0) } }
return r.o(r)
}
let fac = Y { (f: Int -> Int) in
{ $0 <= 1 ? 1 : $0 * f($0-1) }
}
let fib = Y { (f: Int -> Int) in
{ $0 <= 2 ? 1 : f($0-1)+f($0-2)... |
Rewrite the snippet below in Swift so it works the same as the original 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++... | var fact = Array(repeating: 0, count: 12)
fact[0] = 1
for n in 1..<12 {
fact[n] = fact[n - 1] * n
}
for b in 9...12 {
print("The factorions for base \(b) are:")
for i in 1..<1500000 {
var sum = 0
var j = i
while j > 0 {
sum += fact[j % b]
j /= b
}
if sum == i {
print("\... |
Ensure the translated Swift code behaves exactly like the original Go snippet. | 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++... | var fact = Array(repeating: 0, count: 12)
fact[0] = 1
for n in 1..<12 {
fact[n] = fact[n - 1] * n
}
for b in 9...12 {
print("The factorions for base \(b) are:")
for i in 1..<1500000 {
var sum = 0
var j = i
while j > 0 {
sum += fact[j % b]
j /= b
}
if sum == i {
print("\... |
Change the programming language of this snippet from Go to Swift without modifying what it does. |
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) > 1 {
fmt.Println(os.Args[1])
}
}
| #!/usr/bin/swift
import Foundation
print(Process.arguments[1..<Process.arguments.count].joinWithSeparator(" "))
|
Convert the following code from Go to Swift, ensuring the logic remains intact. |
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) > 1 {
fmt.Println(os.Args[1])
}
}
| #!/usr/bin/swift
import Foundation
print(Process.arguments[1..<Process.arguments.count].joinWithSeparator(" "))
|
Convert this Go snippet to Swift and keep its semantics consistent. | 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... | import Foundation
func divisorCount(number: Int) -> Int {
var n = number
var total = 1
while (n & 1) == 0 {
total += 1
n >>= 1
}
var p = 3
while p * p <= n {
var count = 1
while n % p == 0 {
count += 1
n /= p
}
t... |
Ensure the translated Swift code behaves exactly like the original Go snippet. | 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... | import Foundation
func divisorCount(number: Int) -> Int {
var n = number
var total = 1
while (n & 1) == 0 {
total += 1
n >>= 1
}
var p = 3
while p * p <= n {
var count = 1
while n % p == 0 {
count += 1
n /= p
}
t... |
Keep all operations the same but rewrite the snippet in Swift. | package main
import "fmt"
func main() {
bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++
++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>
>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.
<+++++++.--------.<<<<<+.<+++.---.`)
}
func bf(dLen int, is string) {
ds := make([]byt... | import Foundation
let valids = [">", "<", "+", "-", ".", ",", "[", "]"] as Set<Character>
var ip = 0
var dp = 0
var data = [UInt8](count: 30_000, repeatedValue: 0)
let input = Process.arguments
if input.count != 2 {
fatalError("Need one input file")
}
let infile: String!
do {
infile = try String(contentsOf... |
Change the following Go code into Swift without altering its purpose. | package main
import "fmt"
func main() {
bf(10, `++++++++++[>+>+++>++++>+++++++>++++++++>+++++++++>++
++++++++>+++++++++++>++++++++++++<<<<<<<<<-]>>>>+.>>>
>+..<.<++++++++.>>>+.<<+.<<<<++++.<++.>>>+++++++.>>>.+++.
<+++++++.--------.<<<<<+.<+++.---.`)
}
func bf(dLen int, is string) {
ds := make([]byt... | import Foundation
let valids = [">", "<", "+", "-", ".", ",", "[", "]"] as Set<Character>
var ip = 0
var dp = 0
var data = [UInt8](count: 30_000, repeatedValue: 0)
let input = Process.arguments
if input.count != 2 {
fatalError("Need one input file")
}
let infile: String!
do {
infile = try String(contentsOf... |
Convert the following code from Go to Swift, ensuring the logic remains intact. | 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 {
... | import Foundation
func mertensNumbers(max: Int) -> [Int] {
var mertens = Array(repeating: 1, count: max + 1)
for n in 2...max {
for k in 2...n {
mertens[n] -= mertens[n / k]
}
}
return mertens
}
let max = 1000
let mertens = mertensNumbers(max: max)
let count = 200
let colu... |
Convert the following code from Go to Swift, ensuring the logic remains intact. | package cards
import (
"math/rand"
)
type Suit uint8
const (
Spade Suit = 3
Heart Suit = 2
Diamond Suit = 1
Club Suit = 0
)
func (s Suit) String() string {
const suites = "CDHS"
return suites[s : s+1]
}
type Rank uint8
const (
Ace Rank = 1
Two Rank = 2
Three Rank = 3
Four Rank = 4
Fiv... | struct Card: CustomStringConvertible
{
enum Suit: String, CaseIterable, CustomStringConvertible
{
case clubs = "♣️"
case diamonds = "♦️"
case hearts = "♥️"
case spades = "♠️"
var description: String { rawValue }
}
let suit: Suit
let value: Int
var description: String
{
let valueAsString: String
... |
Rewrite the snippet below in Swift so it works the same as the original Go code. | package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
... | public func totient(n: Int) -> Int {
var n = n
var i = 2
var tot = n
while i * i <= n {
if n % i == 0 {
while n % i == 0 {
n /= i
}
tot -= tot / i
}
if i == 2 {
i = 1
}
i += 2
}
if n > 1 {
tot -= tot / n
}
return tot
}
public struct PerfectT... |
Convert the following code from Go to Swift, ensuring the logic remains intact. | package main
import "fmt"
func gcd(n, k int) int {
if n < k || k < 1 {
panic("Need n >= k and k >= 1")
}
s := 1
for n&1 == 0 && k&1 == 0 {
n >>= 1
k >>= 1
s <<= 1
}
t := n
if n&1 != 0 {
t = -k
}
for t != 0 {
for t&1 == 0 {
... | public func totient(n: Int) -> Int {
var n = n
var i = 2
var tot = n
while i * i <= n {
if n % i == 0 {
while n % i == 0 {
n /= i
}
tot -= tot / i
}
if i == 2 {
i = 1
}
i += 2
}
if n > 1 {
tot -= tot / n
}
return tot
}
public struct PerfectT... |
Ensure the translated Swift code behaves exactly like the original Go snippet. | 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)
}
... | import BigInt
import Foundation
@inlinable
public func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n != 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
@inlinable
public func lah<T: BinaryInteger>(n: T, k: T) -> T {
if k == 1 {
return factorial(n)
} else if k == n {
... |
Generate a Swift translation of this Go snippet without changing its computational steps. | 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)
}
... | import BigInt
import Foundation
@inlinable
public func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n != 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
@inlinable
public func lah<T: BinaryInteger>(n: T, k: T) -> T {
if k == 1 {
return factorial(n)
} else if k == n {
... |
Write the same algorithm in Swift as shown in this Go implementation. | package main
import (
"fmt"
"math/rand"
"time"
)
func cocktailShakerSort(a []int) {
var begin = 0
var end = len(a) - 2
for begin <= end {
newBegin := end
newEnd := begin
for i := begin; i <= end; i++ {
if a[i] > a[i+1] {
a[i+1], a[i] = a[i],... | func cocktailShakerSort<T: Comparable>(_ a: inout [T]) {
var begin = 0
var end = a.count
if end == 0 {
return
}
end -= 1
while begin < end {
var new_begin = end
var new_end = begin
var i = begin
while i < end {
if a[i + 1] < a[i] {
... |
Please provide an equivalent version of this Go code in Swift. | 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
... | 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:... |
Change the following Go code into Swift without altering its purpose. | 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... | import Foundation
func divisorCount(number: Int) -> Int {
var n = number
var total = 1
while (n & 1) == 0 {
total += 1
n >>= 1
}
var p = 3
while p * p <= n {
var count = 1
while n % p == 0 {
count += 1
n /= p
}
t... |
Convert the following code from Go to Swift, ensuring the logic remains intact. |
package main
import "fmt"
func MeaningOfLife() int {
return 42
}
func libMain() {
fmt.Println("The meaning of life is", MeaningOfLife())
}
| import Foundation
public class ScriptedMain {
public var meaningOfLife = 42
public init() {}
public class func main() {
var meaning = ScriptedMain().meaningOfLife
println("Main: The meaning of life is \(meaning)")
}
}
#if SCRIPTEDMAIN
@objc class ScriptedMainAutoload {
@objc class func load() {
... |
Please provide an equivalent version of this Go code in Swift. |
package main
import "fmt"
func MeaningOfLife() int {
return 42
}
func libMain() {
fmt.Println("The meaning of life is", MeaningOfLife())
}
| import Foundation
public class ScriptedMain {
public var meaningOfLife = 42
public init() {}
public class func main() {
var meaning = ScriptedMain().meaningOfLife
println("Main: The meaning of life is \(meaning)")
}
}
#if SCRIPTEDMAIN
@objc class ScriptedMainAutoload {
@objc class func load() {
... |
Write a version of this Go function in Swift with identical behavior. | package main
import (
"fmt"
"time"
)
func main() {
var year int
var t time.Time
var lastDay = [12]int { 31,29,31,30,31,30,31,31,30,31,30,31 }
for {
fmt.Print("Please select a year: ")
_, err := fmt.Scanf("%d", &year)
if err != nil {
fmt.Println(err)
continue
} else {
break
}
}
fmt.Prin... | import Foundation
func lastSundays(of year: Int) -> [Date] {
let calendar = Calendar.current
var dates = [Date]()
for month in 1...12 {
var dateComponents = DateComponents(calendar: calendar,
year: year,
month: month + 1,
... |
Write the same algorithm in Swift as shown in this Go implementation. | package main
import (
"fmt"
"time"
)
func main() {
var year int
var t time.Time
var lastDay = [12]int { 31,29,31,30,31,30,31,31,30,31,30,31 }
for {
fmt.Print("Please select a year: ")
_, err := fmt.Scanf("%d", &year)
if err != nil {
fmt.Println(err)
continue
} else {
break
}
}
fmt.Prin... | import Foundation
func lastSundays(of year: Int) -> [Date] {
let calendar = Calendar.current
var dates = [Date]()
for month in 1...12 {
var dateComponents = DateComponents(calendar: calendar,
year: year,
month: month + 1,
... |
Produce a functionally identical Swift code for the snippet given in Go. | package main
import (
"bufio"
"fmt"
"log"
"os"
"sort"
"strings"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func readWords(fileName string) []string {
file, err := os.Open(fileName)
check(err)
defer file.Close()
var words []string
scanner :... | import Foundation
func loadDictionary(_ path: String) throws -> Set<String> {
let contents = try String(contentsOfFile: path, encoding: String.Encoding.ascii)
return Set<String>(contents.components(separatedBy: "\n").filter{!$0.isEmpty})
}
func rotate<T>(_ array: inout [T]) {
guard array.count > 1 else {
... |
Rewrite the snippet below in Swift so it works the same as the original Go code. | package main
import (
"fmt"
"strconv"
)
func uabs(a, b uint64) uint64 {
if a > b {
return a - b
}
return b - a
}
func isEsthetic(n, b uint64) bool {
if n == 0 {
return false
}
i := n % b
n /= b
for n > 0 {
j := n % b
if uabs(i, j) != 1 {
... | extension Sequence {
func take(_ n: Int) -> [Element] {
var res = [Element]()
for el in self {
guard res.count != n else {
return res
}
res.append(el)
}
return res
}
}
extension String {
func isEsthetic(base: Int = 10) -> Bool {
zip(dropFirst(0), dropFirst())
... |
Convert this Go snippet to Swift and keep its semantics consistent. | var i int
var u rune
for i, u = range "voilà" {
fmt.Println(i, u)
}
| let flag = "🇵🇷"
print(flag.characters.count)
print(flag.unicodeScalars.count)
print(flag.utf16.count)
print(flag.utf8.count)
let nfc = "\u{01FA}"
let nfd = "\u{0041}\u{030A}\u{0301}"
let nfkx = "\u{FF21}\u{030A}\u{0301}"
print(nfc == nfd)
print(nfc == nfkx)
|
Change the programming language of this snippet from Go to Swift without modifying what it does. | package permute
func Iter(p []int) func() int {
f := pf(len(p))
return func() int {
return f(p)
}
}
func pf(n int) func([]int) int {
sign := 1
switch n {
case 0, 1:
return func([]int) (s int) {
s = sign
sign = 0
return
}
defa... |
func generate<T>(array: inout [T], output: (_: [T], _: Int) -> Void) {
let n = array.count
var c = Array(repeating: 0, count: n)
var i = 1
var sign = 1
output(array, sign)
while i < n {
if c[i] < i {
if (i & 1) == 0 {
array.swapAt(0, i)
} else {
... |
Write the same code in Swift as shown below in Go. | package main
import "fmt"
func countDivisors(n int) int {
count := 0
for i := 1; i*i <= n; i++ {
if n%i == 0 {
if i == n/i {
count++
} else {
count += 2
}
}
}
return count
}
func main() {
const max = 15
seq :=... |
func divisorCount(number: Int) -> Int {
var n = number
var total = 1
while n % 2 == 0 {
total += 1
n /= 2
}
var p = 3
while p * p <= n {
var count = 1
while n % p == 0 {
count += 1
n /= p
}
total *= count
... |
Write a version of this Go function in Swift with identical behavior. | package main
import (
"fmt"
"sort"
)
type Node struct {
val int
back *Node
}
func lis (n []int) (result []int) {
var pileTops []*Node
for _, x := range n {
j := sort.Search(len(pileTops), func (i int) bool { return pileTops[i].val >= x })
node := &Node{ x, nil }
if j != 0 { node.back =... | import Foundation
extension Array where Element: Comparable {
@inlinable
public func longestIncreasingSubsequence() -> [Element] {
var startI = [Int](repeating: 0, count: count)
var endI = [Int](repeating: 0, count: count + 1)
var len = 0
for i in 0..<count {
var lo = 1
var hi = len
... |
Change the following Go code into Swift without altering its purpose. | package main
import (
"fmt"
"math"
"rcu"
"sort"
)
var primes = rcu.Primes(1e8 - 1)
type res struct {
bc interface{}
next int
}
func getBrilliant(digits, limit int, countOnly bool) res {
var brilliant []int
count := 0
pow := 1
next := math.MaxInt
for k := 1; k <= digits;... |
func primeArray(n: Int) -> [Bool] {
var primeArr = [Bool](repeating: true, count: n + 1)
primeArr[0] = false
primeArr[1] = false
var p = 2
while (p * p) <= n {
if primeArr[p] == true {
for j in stride(from: p * 2, through: n, by: p) {
primeA... |
Translate the given Go code snippet into Swift without altering its behavior. | package main
import (
"fmt"
"math"
"rcu"
"sort"
)
var primes = rcu.Primes(1e8 - 1)
type res struct {
bc interface{}
next int
}
func getBrilliant(digits, limit int, countOnly bool) res {
var brilliant []int
count := 0
pow := 1
next := math.MaxInt
for k := 1; k <= digits;... |
func primeArray(n: Int) -> [Bool] {
var primeArr = [Bool](repeating: true, count: n + 1)
primeArr[0] = false
primeArr[1] = false
var p = 2
while (p * p) <= n {
if primeArr[p] == true {
for j in stride(from: p * 2, through: n, by: p) {
primeA... |
Change the programming language of this snippet from Go to Swift without modifying what it does. | package main
import (
"fmt"
"sort"
"strings"
)
type indexSort struct {
val sort.Interface
ind []int
}
func (s indexSort) Len() int { return len(s.ind) }
func (s indexSort) Less(i, j int) bool { return s.ind[i] < s.ind[j] }
func (s indexSort) Swap(i, j int) {
s.val.Swap(s.ind[i], s.ind[j])
s.ind[i], ... | func disjointOrder<T: Hashable>(m: [T], n: [T]) -> [T] {
let replaceCounts = n.reduce(into: [T: Int](), { $0[$1, default: 0] += 1 })
let reduced = m.reduce(into: ([T](), n, replaceCounts), {cur, el in
cur.0.append(cur.2[el, default: 0] > 0 ? cur.1.removeFirst() : el)
cur.2[el]? -= 1
})
return reduced.0... |
Translate the given Go code snippet into Swift without altering its behavior. | package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
)
func isPrime(n int) bool {
if n < 2 {
return false
}
if n%2 == 0 {
return n == 2
}
if n%3 == 0 {
return n == 3
}
d := 5
for d*d <= n {
if n%d == 0 {
return ... | 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 (
"bytes"
"fmt"
"io/ioutil"
"log"
"strings"
)
func isPrime(n int) bool {
if n < 2 {
return false
}
if n%2 == 0 {
return n == 2
}
if n%3 == 0 {
return n == 3
}
d := 5
for d*d <= n {
if n%d == 0 {
return ... | 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:... |
Can you help me rewrite this code in Swift instead of Go, keeping it the same logically? | package main
import (
"fmt"
"math/big"
)
func main() {
one := big.NewInt(1)
two := big.NewInt(2)
next := new(big.Int)
sylvester := []*big.Int{two}
prod := new(big.Int).Set(two)
count := 1
for count < 10 {
next.Add(prod, one)
sylvester = append(sylvester, new(big.Int... | import BigNumber
func sylvester(n: Int) -> BInt {
var a = BInt(2)
for _ in 0..<n {
a = a * a - a + 1
}
return a
}
var sum = BDouble(0)
for n in 0..<10 {
let syl = sylvester(n: n)
sum += BDouble(1) / BDouble(syl)
print(syl)
}
print("Sum of the reciprocals of first ten in sequence: \(sum)")
|
Produce a functionally identical Swift code for the snippet given in Go. | package main
import (
"fmt"
"log"
"math/rand"
"time"
)
func generate(from, to int64) {
if to < from || from < 0 {
log.Fatal("Invalid range.")
}
span := to - from + 1
generated := make([]bool, span)
count := span
for count > 0 {
n := from + rand.Int63n(span) ... | var array = Array(1...20)
array.shuffle()
print(array)
|
Rewrite the snippet below in Swift so it works the same as the original Go code. | package main
import "fmt"
func circleSort(a []int, lo, hi, swaps int) int {
if lo == hi {
return swaps
}
high, low := hi, lo
mid := (hi - lo) / 2
for lo < hi {
if a[lo] > a[hi] {
a[lo], a[hi] = a[hi], a[lo]
swaps++
}
lo++
hi--
}
... | func circleSort<T: Comparable>(_ array: inout [T]) {
func circSort(low: Int, high: Int, swaps: Int) -> Int {
if low == high {
return swaps
}
var lo = low
var hi = high
let mid = (hi - lo) / 2
var s = swaps
while lo < hi {
if array[lo] >... |
Write the same algorithm in Swift as shown in this Go implementation. | package main
import (
"fmt"
"math"
)
var (
Two = "Two circles."
R0 = "R==0.0 does not describe circles."
Co = "Coincident points describe an infinite number of circles."
CoR0 = "Coincident points with r==0.0 describe a degenerate circle."
Diam = "Points form a diameter and describe on... | import Foundation
struct Point: Equatable {
var x: Double
var y: Double
}
struct Circle {
var center: Point
var radius: Double
static func circleBetween(
_ p1: Point,
_ p2: Point,
withRadius radius: Double
) -> (Circle, Circle?)? {
func applyPoint(_ p1: Point, _ p2: Point, op: (Double... |
Convert this Go block to Swift, preserving its control flow and logic. | package main
import (
"fmt"
"math"
)
var (
Two = "Two circles."
R0 = "R==0.0 does not describe circles."
Co = "Coincident points describe an infinite number of circles."
CoR0 = "Coincident points with r==0.0 describe a degenerate circle."
Diam = "Points form a diameter and describe on... | import Foundation
struct Point: Equatable {
var x: Double
var y: Double
}
struct Circle {
var center: Point
var radius: Double
static func circleBetween(
_ p1: Point,
_ p2: Point,
withRadius radius: Double
) -> (Circle, Circle?)? {
func applyPoint(_ p1: Point, _ p2: Point, op: (Double... |
Can you help me rewrite this code in Swift instead of Go, keeping it the same logically? | package main
import (
"fmt"
"math"
)
func max(a, b uint64) uint64 {
if a > b {
return a
}
return b
}
func min(a, b uint64) uint64 {
if a < b {
return a
}
return b
}
func ndigits(x uint64) (n int) {
for ; x > 0; x /= 10 {
n++
}
return
}
fu... | import Foundation
func vampire<T>(n: T) -> [(T, T)] where T: BinaryInteger, T.Stride: SignedInteger {
let strN = String(n).sorted()
let fangLength = strN.count / 2
let start = T(pow(10, Double(fangLength - 1)))
let end = T(Double(n).squareRoot())
var fangs = [(T, T)]()
for i in start...end where n % i ==... |
Can you help me rewrite this code in Swift instead of Go, keeping it the same logically? | package main
import (
"log"
"os"
"os/exec"
)
func main() {
args := []string{
"-m", "-v", "0.75", "a.wav", "-v", "0.25", "b.wav",
"-d",
"trim", "4", "6",
"repeat", "5",
}
cmd := exec.Command("sox", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
... | import AVFoundation
class PlayerControl: NSObject, AVAudioPlayerDelegate {
let player1:AVAudioPlayer!
let player2:AVAudioPlayer!
var playedBoth = false
var volume:Float {
get {
return player1.volume
}
set {
player1.volume = newValue
... |
Convert the following code from Go to Swift, ensuring the logic remains intact. | package main
import (
"fmt"
"strings"
)
func printBlock(data string, le int) {
a := []byte(data)
sumBytes := 0
for _, b := range a {
sumBytes += int(b - 48)
}
fmt.Printf("\nblocks %c, cells %d\n", a, le)
if le-sumBytes <= 0 {
fmt.Println("No solution")
return
... | import Foundation
func nonoblock(cells: Int, blocks: [Int]) {
print("\(cells) cells and blocks \(blocks):")
let totalBlockSize = blocks.reduce(0, +)
if cells < totalBlockSize + blocks.count - 1 {
print("no solution")
return
}
func solve(cells: Int, index: Int, totalBlockSize: Int, ... |
Generate a Swift translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"strings"
)
func printBlock(data string, le int) {
a := []byte(data)
sumBytes := 0
for _, b := range a {
sumBytes += int(b - 48)
}
fmt.Printf("\nblocks %c, cells %d\n", a, le)
if le-sumBytes <= 0 {
fmt.Println("No solution")
return
... | import Foundation
func nonoblock(cells: Int, blocks: [Int]) {
print("\(cells) cells and blocks \(blocks):")
let totalBlockSize = blocks.reduce(0, +)
if cells < totalBlockSize + blocks.count - 1 {
print("no solution")
return
}
func solve(cells: Int, index: Int, totalBlockSize: Int, ... |
Port the following code from Go to Swift with equivalent syntax and logic. | package main
import "fmt"
type Item struct {
name string
weight, value, qty int
}
var items = []Item{
{"map", 9, 150, 1},
{"compass", 13, 35, 1},
{"water", 153, 200, 2},
{"sandwich", 50, 60, 2},
{"glucose", 15, 60, 2},
{"tin", 68, 45, 3},
{"banana", 27, 60, 3},
{"apple", 39, 40, 3},... | public struct KnapsackItem: Hashable {
public var name: String
public var weight: Int
public var value: Int
public init(name: String, weight: Int, value: Int) {
self.name = name
self.weight = weight
self.value = value
}
}
public func knapsack(items: [KnapsackItem], limit: Int) -> [KnapsackItem] ... |
Convert the following code from Go to Swift, ensuring the logic remains intact. | package main
import (
"fmt"
"math"
"strconv"
"strings"
)
func d2d(d float64) float64 { return math.Mod(d, 360) }
func g2g(g float64) float64 { return math.Mod(g, 400) }
func m2m(m float64) float64 { return math.Mod(m, 6400) }
func r2r(r float64) float64 { return math.Mod(r, 2*math.Pi) }
func d2g(d... | import Foundation
func normalize(_ f: Double, N: Double) -> Double {
var a = f
while a < -N { a += N }
while a >= N { a -= N }
return a
}
func normalizeToDeg(_ f: Double) -> Double {
return normalize(f, N: 360)
}
func normalizeToGrad(_ f: Double) -> Double {
return normalize(f, N: 400)
}
func normaliz... |
Please provide an equivalent version of this Go code in Swift. | package main
import (
"bufio"
"fmt"
"log"
"os"
"regexp"
"strings"
)
func main() {
f, err := os.Open("unixdict.txt")
if err != nil {
log.Fatalln(err)
}
defer f.Close()
s := bufio.NewScanner(f)
rie := regexp.MustCompile("^ie|[^c]ie")
rei := regexp.MustCompile("^ei|[^c]ei")
var cie, ie int
var cei, ei ... | import Foundation
let request = NSURLRequest(URL: NSURL(string: "http:
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) {res, data, err in
if (data != nil) {
if let fileAsString = NSString(data: data, encoding: NSUTF8StringEncoding) {
var firstCase = false
... |
Rewrite the snippet below in Swift so it works the same as the original Go code. | package main
import (
"bufio"
"fmt"
"log"
"os"
"regexp"
"strings"
)
func main() {
f, err := os.Open("unixdict.txt")
if err != nil {
log.Fatalln(err)
}
defer f.Close()
s := bufio.NewScanner(f)
rie := regexp.MustCompile("^ie|[^c]ie")
rei := regexp.MustCompile("^ei|[^c]ei")
var cie, ie int
var cei, ei ... | import Foundation
let request = NSURLRequest(URL: NSURL(string: "http:
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) {res, data, err in
if (data != nil) {
if let fileAsString = NSString(data: data, encoding: NSUTF8StringEncoding) {
var firstCase = false
... |
Translate the given Go code snippet into Swift without altering its behavior. | package raster
import "math"
func ipart(x float64) float64 {
return math.Floor(x)
}
func round(x float64) float64 {
return ipart(x + .5)
}
func fpart(x float64) float64 {
return x - ipart(x)
}
func rfpart(x float64) float64 {
return 1 - fpart(x)
}
func (g *Grmap) AaLine(x1, y1, x2, y2 float64) {
... | import Darwin
public func pixel(color: Color, x: Int, y: Int) {
let idx = x + y * self.width
if idx >= 0 && idx < self.bitmap.count {
self.bitmap[idx] = self.blendColors(bot: self.bitmap[idx], top: color)
}
}
func fpart(_ x: Double) -> Double {
return modf(x).1
}
func rfpart(_ x: Double) ->... |
Generate an equivalent Swift version of this Go code. | package main
import (
"fmt"
"math"
"strings"
)
func main() {
for _, n := range [...]int64{
0, 4, 6, 11, 13, 75, 100, 337, -164,
math.MaxInt64,
} {
fmt.Println(fourIsMagic(n))
}
}
func fourIsMagic(n int64) string {
s := say(n)
s = strings.ToUpper(s[:1]) + s[1:]
t := s
for n != 4 {
n = int64(len(s))
... | import Foundation
func fourIsMagic(_ number: NSNumber) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .spellOut
formatter.locale = Locale(identifier: "en_EN")
var result: [String] = []
var numberString = formatter.string(from: number)!
result.append(numberString.capital... |
Produce a functionally identical Swift code for the snippet given in Go. | package main
import (
"bytes"
"fmt"
"strings"
)
var in = `
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
01110001111000001110000000000000
01111111110000001110000000000000
01110111100000001110000111000000
0111001111001110... | import UIKit
let beforeTxt = """
1100111
1100111
1100111
1100111
1100110
1100110
1100110
1100110
1100110
1100110
1100110
1100110
1111110
0000000
"""
let smallrc01 = """
00000000000000000000000000000000
01111111110000000111111110000000
01110001111000001111001111000000
01110000111000001110000111000000
0111000111100000... |
Convert this Go snippet to Swift and keep its semantics consistent. | package main
import (
"fmt"
"math/rand"
)
type symbols struct{ k, q, r, b, n rune }
var A = symbols{'K', 'Q', 'R', 'B', 'N'}
var W = symbols{'♔', '♕', '♖', '♗', '♘'}
var B = symbols{'♚', '♛', '♜', '♝', '♞'}
var krn = []string{
"nnrkr", "nrnkr", "nrknr", "nrkrn",
"rnnkr", "rnknr", "rnkrn",
"rknnr... | func isValid960Position(_ firstRank: String) -> Bool {
var rooksPlaced = 0
var bishopColor = -1
for (i, piece) in firstRank.enumerated() {
switch piece {
case "♚" where rooksPlaced != 1:
return false
case "♜":
rooksPlaced += 1
case "♝" where bishopColor == -1:
bishopColor = i & ... |
Please provide an equivalent version of this Go code in Swift. | import (
"fmt"
"strings"
)
func main() {
for _, n := range []int64{
1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003,
} {
fmt.Println(sayOrdinal(n))
}
}
var irregularOrdinals = map[string]string{
"one": "first",
"two": "second",
"three": "third",
"five": "fifth",
"eight": "eighth"... | fileprivate class NumberNames {
let cardinal: String
let ordinal: String
init(cardinal: String, ordinal: String) {
self.cardinal = cardinal
self.ordinal = ordinal
}
func getName(_ ordinal: Bool) -> String {
return ordinal ? self.ordinal : self.cardinal
}
cl... |
Transform the following Go implementation into Swift, maintaining the same output and logic. | package main
import "fmt"
import "C"
func main() {
code := []byte{
0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d,
0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75,
0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75,
0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3,
}
le := len(code)
buf := C.mmap(nil, C.size_t(le), C.PROT... | import Foundation
typealias TwoIntsOneInt = @convention(c) (Int, Int) -> Int
let code = [
144,
144,
106, 12,
184, 7, 0, 0, 0,
72, 193, 224, 32,
80,
139, 68, 36, 4, 3, 68, 36, 8,
76, 137, 227,
137, 195,
72, 193, 227, 4,
128, 203, 2,
72, 131, 196, 16,
195,
] as [UInt8]
func fudge(x: Int... |
Port the provided Go code into Swift while preserving the original functionality. | package main
import (
"fmt"
"math"
)
const eps = 1e-14
type point struct{ x, y float64 }
func (p point) String() string {
if p.x == 0 {
p.x = 0
}
if p.y == 0 {
p.y = 0
}
return fmt.Sprintf("(%g, %g)", p.x, p.y)
}
func sq(x float64) float64 { return x * x }
... | import Foundation
import CoreGraphics
func lineCircleIntersection(start: NSPoint, end: NSPoint, center: NSPoint,
radius: CGFloat, segment: Bool) -> [NSPoint] {
var result: [NSPoint] = []
let angle = atan2(end.y - start.y, end.x - start.x)
var at = AffineTransform(rotationByRadia... |
Generate a Swift translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"github.com/rivo/uniseg"
"log"
"regexp"
"strings"
)
func join(words, seps []string) string {
lw := len(words)
ls := len(seps)
if lw != ls+1 {
log.Fatal("mismatch between number of words and separators")
}
var sb strings.Builder
for i := 0... | import Foundation
struct RedactionOptions: OptionSet {
let rawValue: Int
static let wholeWord = RedactionOptions(rawValue: 1 << 0)
static let overKill = RedactionOptions(rawValue: 1 << 1)
static let caseInsensitive = RedactionOptions(rawValue: 1 << 2)
}
func redact(text: String, target: ... |
Convert this Go snippet to Swift and keep its semantics consistent. | package main
import (
"fmt"
"strconv"
"strings"
)
var atomicMass = map[string]float64{
"H": 1.008,
"He": 4.002602,
"Li": 6.94,
"Be": 9.0121831,
"B": 10.81,
"C": 12.011,
"N": 14.007,
"O": 15.999,
"F": 18.998403163,
"Ne": 20.1797,
"Na": 22.9897692... | import Foundation
struct Chem {
struct Molecule {
var formula: String
var parts: [Molecule]
var quantity = 1
var molarMass: Double {
switch parts.count {
case 0:
return Chem.atomicWeights[formula]! * Double(quantity)
case _:
return parts.lazy.map({ $0.molarMass }).r... |
Translate the given Go code snippet into Swift without altering its behavior. | package main
import "fmt"
type frac struct{ num, den int }
func (f frac) String() string {
return fmt.Sprintf("%d/%d", f.num, f.den)
}
func f(l, r frac, n int) {
m := frac{l.num + r.num, l.den + r.den}
if m.den <= n {
f(l, m, n)
fmt.Print(m, " ")
f(m, r, n)
}
}
func main() {... | class Farey {
let n: Int
init(_ x: Int) {
n = x
}
var sequence: [(Int,Int)] {
var a = 0
var b = 1
var c = 1
var d = n
var results = [(a, b)]
while c <= n {
let k = (n + b) / d
let oldA = a
let oldB = b
... |
Port the following code from Go to Swift with equivalent syntax and logic. | package main
import "fmt"
type frac struct{ num, den int }
func (f frac) String() string {
return fmt.Sprintf("%d/%d", f.num, f.den)
}
func f(l, r frac, n int) {
m := frac{l.num + r.num, l.den + r.den}
if m.den <= n {
f(l, m, n)
fmt.Print(m, " ")
f(m, r, n)
}
}
func main() {... | class Farey {
let n: Int
init(_ x: Int) {
n = x
}
var sequence: [(Int,Int)] {
var a = 0
var b = 1
var c = 1
var d = n
var results = [(a, b)]
while c <= n {
let k = (n + b) / d
let oldA = a
let oldB = b
... |
Produce a functionally identical Swift code for the snippet given in Go. | package main
import (
"fmt"
"math"
"strings"
)
const threshold = uint64(1) << 47
func indexOf(s []uint64, search uint64) int {
for i, e := range s {
if e == search {
return i
}
}
return -1
}
func contains(s []uint64, search uint64) bool {
return indexOf(s, sea... | extension BinaryInteger {
@inlinable
public func factors(sorted: Bool = true) -> [Self] {
let maxN = Self(Double(self).squareRoot())
var res = Set<Self>()
for factor in stride(from: 1, through: maxN, by: 1) where self % factor == 0 {
res.insert(factor)
res.insert(self / factor)
}
r... |
Produce a language-to-language conversion: from Go to Swift, same semantics. | package main
import (
"fmt"
"math"
"strings"
)
const threshold = uint64(1) << 47
func indexOf(s []uint64, search uint64) int {
for i, e := range s {
if e == search {
return i
}
}
return -1
}
func contains(s []uint64, search uint64) bool {
return indexOf(s, sea... | extension BinaryInteger {
@inlinable
public func factors(sorted: Bool = true) -> [Self] {
let maxN = Self(Double(self).squareRoot())
var res = Set<Self>()
for factor in stride(from: 1, through: maxN, by: 1) where self % factor == 0 {
res.insert(factor)
res.insert(self / factor)
}
r... |
Rewrite the snippet below in Swift so it works the same as the original Go code. | package main
import "fmt"
func isPrime(n uint64) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := uint64(5)
for d*d <= n {
if n%d == 0 {
return false
}
... | import Foundation
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
if n % 2 == 0 {
return n == 2
}
if n % 3 == 0 {
return n == 3
}
var p = 5
while p * p <= n {
if n % p == 0 {
return false
}
p += 2
if n % p ==... |
Rewrite this program in Swift while keeping its functionality equivalent to the Go version. | package main
import (
"container/heap"
"fmt"
"strings"
)
type CubeSum struct {
x, y uint16
value uint64
}
func (c *CubeSum) fixvalue() { c.value = cubes[c.x] + cubes[c.y] }
type CubeSumHeap []*CubeSum
func (h CubeSumHeap) Len() int { return len(h) }
func (h CubeSumHeap) Less(i, j int) bool { retu... | extension Array {
func combinations(_ k: Int) -> [[Element]] {
return Self._combinations(slice: self[startIndex...], k)
}
static func _combinations(slice: Self.SubSequence, _ k: Int) -> [[Element]] {
guard k != 1 else {
return slice.map({ [$0] })
}
guard k != slice.count else {
retur... |
Write the same code in Swift as shown below in Go. | 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
}
... | import Foundation
class PrimeSieve {
var composite: [Bool]
init(size: Int) {
composite = Array(repeating: false, count: size/2)
var p = 3
while p * p <= size {
if !composite[p/2 - 1] {
let inc = p * 2
var q = p * p
while q... |
Port the following code from Go to Swift with equivalent syntax and logic. | package main
import (
"fmt"
"math/big"
)
func main() {
fmt.Print("!0 through !10: 0")
one := big.NewInt(1)
n := big.NewInt(1)
f := big.NewInt(1)
l := big.NewInt(1)
next := func() { f.Mul(f, n); l.Add(l, f); n.Add(n, one) }
for ; ; next() {
fmt.Print(" ", l)
if n.Int... | import BigInt
func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n != 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
prefix func ! <T: BinaryInteger>(n: T) -> T {
guard n != 0 else {
return 0
}
return stride(from: 0, to: n, by: 1).lazy.map(factorial).reduce(0, +)
}
... |
Translate the given Go code snippet into Swift without altering its behavior. | package main
import (
"fmt"
"math/big"
)
func main() {
fmt.Print("!0 through !10: 0")
one := big.NewInt(1)
n := big.NewInt(1)
f := big.NewInt(1)
l := big.NewInt(1)
next := func() { f.Mul(f, n); l.Add(l, f); n.Add(n, one) }
for ; ; next() {
fmt.Print(" ", l)
if n.Int... | import BigInt
func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n != 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
prefix func ! <T: BinaryInteger>(n: T) -> T {
guard n != 0 else {
return 0
}
return stride(from: 0, to: n, by: 1).lazy.map(factorial).reduce(0, +)
}
... |
Produce a language-to-language conversion: from Go to Swift, same semantics. | 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... | import Foundation
func primeSieve(limit: Int) -> [Bool] {
guard limit > 0 else {
return []
}
var sieve = Array(repeating: true, count: limit)
sieve[0] = false
if limit > 1 {
sieve[1] = false
}
if limit > 4 {
for i in stride(from: 4, to: limit, by: 2) {
si... |
Port the following code from Go to Swift with equivalent syntax and logic. | package main
import "fmt"
func isPrime(n int) bool {
switch {
case n < 2:
return false
case n%2 == 0:
return n == 2
case n%3 == 0:
return n == 3
default:
d := 5
for d*d <= n {
if n%d == 0 {
return false
}
d... | import Foundation
func primeSieve(limit: Int) -> [Bool] {
guard limit > 0 else {
return []
}
var sieve = Array(repeating: true, count: limit)
sieve[0] = false
if limit > 1 {
sieve[1] = false
}
if limit > 4 {
for i in stride(from: 4, to: limit, by: 2) {
si... |
Change the programming language of this snippet from Go to Swift without modifying what it does. | package main
import (
"fmt"
"rcu"
)
func motzkin(n int) []int {
m := make([]int, n+1)
m[0] = 1
m[1] = 1
for i := 2; i <= n; i++ {
m[i] = (m[i-1]*(2*i+1) + m[i-2]*(3*i-3)) / (i + 2)
}
return m
}
func main() {
fmt.Println(" n M[n] Prime?")
fmt.Printl... | 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 % i == 0 {
... |
Convert this Go snippet to Swift and keep its semantics consistent. | package main
import (
"fmt"
"math/big"
)
var b = new(big.Int)
func isSPDSPrime(n uint64) bool {
nn := n
for nn > 0 {
r := nn % 10
if r != 2 && r != 3 && r != 5 && r != 7 {
return false
}
nn /= 10
}
b.SetUint64(n)
if b.ProbablyPrime(0) {
... | func isPrime(number: Int) -> Bool {
if number < 2 {
return false
}
if number % 2 == 0 {
return number == 2
}
if number % 3 == 0 {
return number == 3
}
if number % 5 == 0 {
return number == 5
}
var p = 7
let wheel = [4,2,4,2,4,6,2,6]
while true ... |
Transform the following Go implementation into Swift, maintaining the same output and logic. | package main
import "rcu"
func main() {
var res []int
for n := 1; n <= 70; n++ {
m := 1
for rcu.DigitSum(m*n, 10) != n {
m++
}
res = append(res, m)
}
rcu.PrintTable(res, 7, 10, true)
}
| import Foundation
func digitSum(_ num: Int) -> Int {
var sum = 0
var n = num
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
for n in 1...70 {
for m in 1... {
if digitSum(m * n) == n {
print(String(format: "%8d", m), terminator: n % 10 == 0 ? "\n" : " ")
... |
Ensure the translated Swift code behaves exactly like the original Go snippet. | package main
import "fmt"
const (
N = 2200
N2 = N * N * 2
)
func main() {
s := 3
var s1, s2 int
var r [N + 1]bool
var ab [N2 + 1]bool
for a := 1; a <= N; a++ {
a2 := a * a
for b := a; b <= N; b++ {
ab[a2 + b * b] = true
}
}
for c := 1; ... | func missingD(upTo n: Int) -> [Int] {
var a2 = 0, s = 3, s1 = 0, s2 = 0
var res = [Int](repeating: 0, count: n + 1)
var ab = [Int](repeating: 0, count: n * n * 2 + 1)
for a in 1...n {
a2 = a * a
for b in a...n {
ab[a2 + b * b] = 1
}
}
for c in 1..<n {
s1 = s
s += 2
s2 = s
... |
Translate the given Go code snippet into Swift without altering its behavior. | package main
import "fmt"
func sieve(limit uint64) []bool {
limit++
c := make([]bool, limit)
c[0] = true
c[1] = true
for i := uint64(4); i < limit; i += 2 {
c[i] = true
}
p := uint64(3)
for {
p2 := p * p
if p2 >= limit {
break
}
... | import Foundation
class PrimeSieve {
var composite: [Bool]
init(size: Int) {
composite = Array(repeating: false, count: size/2)
var p = 3
while p * p <= size {
if !composite[p/2 - 1] {
let inc = p * 2
var q = p * p
while q... |
Please provide an equivalent version of this Go code in Swift. | package main
import "fmt"
func main() {
tableA := []struct {
value int
key string
}{
{27, "Jonah"}, {18, "Alan"}, {28, "Glory"}, {18, "Popeye"},
{28, "Alan"},
}
tableB := []struct {
key string
value string
}{
{"Jonah", "Whales"}, {"Jonah"... | func hashJoin<A, B, K: Hashable>(_ first: [(K, A)], _ second: [(K, B)]) -> [(A, K, B)] {
var map = [K: [B]]()
for (key, val) in second {
map[key, default: []].append(val)
}
var res = [(A, K, B)]()
for (key, val) in first {
guard let vals = map[key] else {
continue
}
res += vals.map({... |
Convert this Go snippet to Swift and keep its semantics consistent. | package main
import (
"fmt"
"time"
)
func main() {
fmt.Print("\033[?1049h\033[H")
fmt.Println("Alternate screen buffer\n")
s := "s"
for i := 5; i > 0; i-- {
if i == 1 {
s = ""
}
fmt.Printf("\rgoing back in %d second%s...", i, s)
time.Sleep(time.Secon... | public let CSI = ESC+"["
func write(_ text: String...) {
for txt in text { write(STDOUT_FILENO, txt, txt.utf8.count) }
}
write(CSI,"?1049h")
print("Alternate screen buffer\n")
for n in (1...5).reversed() {
print("Going back in \(n)...")
sleep(1)
}
write(CSI,"?1049l")
|
Transform the following Go implementation into Swift, maintaining the same output and logic. | package main
import (
"go/build"
"log"
"path/filepath"
"github.com/unixpickle/gospeech"
"github.com/unixpickle/wav"
)
const pkgPath = "github.com/unixpickle/gospeech"
const input = "This is an example of speech synthesis."
func main() {
p, err := build.Import(pkgPath, ".", build.FindOnly)
... | import Foundation
let task = NSTask()
task.launchPath = "/usr/bin/say"
task.arguments = ["This is an example of speech synthesis."]
task.launch()
|
Rewrite this program in Swift while keeping its functionality equivalent to the Go version. | package main
import (
"fmt"
"math/rand"
"time"
)
const (
op_num = iota
op_add
op_sub
op_mul
op_div
)
type frac struct {
num, denom int
}
type Expr struct {
op int
left, right *Expr
value frac
}
var n_cards = 4
var goal = 24
var digit_range = 9
func (x *Expr) String() string {
if x.op... | import Darwin
import Foundation
var solution = ""
println("24 Game")
println("Generating 4 digits...")
func randomDigits() -> [Int] {
var result = [Int]()
for i in 0 ..< 4 {
result.append(Int(arc4random_uniform(9)+1))
}
return result
}
let digits = randomDigits()
print("Make 24 using these digits : ")... |
Convert the following code from Go to Swift, ensuring the logic remains intact. | package main
import (
"fmt"
"math/rand"
"time"
)
const (
op_num = iota
op_add
op_sub
op_mul
op_div
)
type frac struct {
num, denom int
}
type Expr struct {
op int
left, right *Expr
value frac
}
var n_cards = 4
var goal = 24
var digit_range = 9
func (x *Expr) String() string {
if x.op... | import Darwin
import Foundation
var solution = ""
println("24 Game")
println("Generating 4 digits...")
func randomDigits() -> [Int] {
var result = [Int]()
for i in 0 ..< 4 {
result.append(Int(arc4random_uniform(9)+1))
}
return result
}
let digits = randomDigits()
print("Make 24 using these digits : ")... |
Maintain the same structure and functionality when rewriting this code in Swift. | package main
import (
"fmt"
"math/big"
"strings"
"time"
)
func main() {
start := time.Now()
rd := []string{"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"}
one := big.NewInt(1)
nine := big.NewInt(9)
for i := big.NewInt(2); i.Cmp(nine) <= 0; i.Add(i, one) ... | import BigInt
import Foundation
let rd = ["22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"]
for d in 2...9 {
print("First 10 super-\(d) numbers:")
var count = 0
var n = BigInt(3)
var k = BigInt(0)
while true {
k = n.power(d)
k *= BigInt(d)
if let _ = String(k).range(... |
Port the following code from Go to Swift with equivalent syntax and logic. | package main
import (
"fmt"
"math/big"
"strings"
"time"
)
func main() {
start := time.Now()
rd := []string{"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"}
one := big.NewInt(1)
nine := big.NewInt(9)
for i := big.NewInt(2); i.Cmp(nine) <= 0; i.Add(i, one) ... | import BigInt
import Foundation
let rd = ["22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"]
for d in 2...9 {
print("First 10 super-\(d) numbers:")
var count = 0
var n = BigInt(3)
var k = BigInt(0)
while true {
k = n.power(d)
k *= BigInt(d)
if let _ = String(k).range(... |
Transform the following Go implementation into Swift, maintaining the same output and logic. | package main
import (
"fmt"
"math"
"math/big"
"strings"
)
func padovanRecur(n int) []int {
p := make([]int, n)
p[0], p[1], p[2] = 1, 1, 1
for i := 3; i < n; i++ {
p[i] = p[i-2] + p[i-3]
}
return p
}
func padovanFloor(n int) []int {
var p, s, t, u = new(big.Rat), new(bi... | import Foundation
class PadovanRecurrence: Sequence, IteratorProtocol {
private var p = [1, 1, 1]
private var n = 0
func next() -> Int? {
let pn = n < 3 ? p[n] : p[0] + p[1]
p[0] = p[1]
p[1] = p[2]
p[2] = pn
n += 1
return pn
}
}
class PadovanFloor: ... |
Port the provided Go code into Swift while preserving the original functionality. | package main
import (
"fmt"
"strconv"
)
type maybe struct{ value *int }
func (m maybe) bind(f func(p *int) maybe) maybe {
return f(m.value)
}
func unit(p *int) maybe {
return maybe{p}
}
func decrement(p *int) maybe {
if p == nil {
return unit(nil)
} else {
q := *p - 1
... | precedencegroup MonadPrecedence {
higherThan: BitwiseShiftPrecedence
associativity: left
}
infix operator >>-: MonadPrecedence
typealias Maybe = Optional
extension Maybe
{
static func unit(_ x: Wrapped) -> Maybe<Wrapped>
{
return Maybe(x)
}
func bind<T>(_ f: (Wrapped) -> Maybe<T>) -> Maybe<T>
{
return s... |
Write the same algorithm in Swift as shown in this Go implementation. | package main
import "fmt"
type mlist struct{ value []int }
func (m mlist) bind(f func(lst []int) mlist) mlist {
return f(m.value)
}
func unit(lst []int) mlist {
return mlist{lst}
}
func increment(lst []int) mlist {
lst2 := make([]int, len(lst))
for i, v := range lst {
lst2[i] = v + 1
}
... | precedencegroup MonadPrecedence {
higherThan: BitwiseShiftPrecedence
associativity: left
}
infix operator >>-: MonadPrecedence
extension Array
{
static func unit(_ x: Element) -> [Element]
{
return [x]
}
func bind<T>(_ f: (Element) -> [T]) -> [T]
{
return flatMap(f)
}
static func >>- <U>(_ m: [Element... |
Produce a language-to-language conversion: from Go to Swift, same semantics. | package main
import (
"bufio"
"flag"
"fmt"
"io"
"log"
"os"
"strings"
"unicode"
)
func main() {
log.SetFlags(0)
log.SetPrefix("textonyms: ")
wordlist := flag.String("wordlist", "wordlist", "file containing the list of words to check")
flag.Parse()
if flag.NArg() != 0 {
flag.Usage()
os.Exit(2)
}
t ... | import Foundation
func textCharacter(_ ch: Character) -> Character? {
switch (ch) {
case "a", "b", "c":
return "2"
case "d", "e", "f":
return "3"
case "g", "h", "i":
return "4"
case "j", "k", "l":
return "5"
case "m", "n", "o":
return "6"
case "p", "q... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.