Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write a version of this Python function in Scala with identical behavior. | from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None
self.n = None
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
... |
fun main(args: Array<String>) {
val a = mutableListOf(0)
val used = mutableSetOf(0)
val used1000 = mutableSetOf(0)
var foundDup = false
var n = 1
while (n <= 15 || !foundDup || used1000.size < 1001) {
var next = a[n - 1] - n
if (next < 1 || used.contains(next)) next += 2 * n
... |
Convert this Python snippet to Scala and keep its semantics consistent. | from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None
self.n = None
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
... |
fun main(args: Array<String>) {
val a = mutableListOf(0)
val used = mutableSetOf(0)
val used1000 = mutableSetOf(0)
var foundDup = false
var n = 1
while (n <= 15 || !foundDup || used1000.size < 1001) {
var next = a[n - 1] - n
if (next < 1 || used.contains(next)) next += 2 * n
... |
Ensure the translated Scala code behaves exactly like the original Python snippet. | >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))
>>> [ Y(fac)(i) for i in range(10) ]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))
>>> [ Y(fib)(i) for i i... |
typealias Func<T, R> = (T) -> R
class RecursiveFunc<T, R>(val p: (RecursiveFunc<T, R>) -> Func<T, R>)
fun <T, R> y(f: (Func<T, R>) -> Func<T, R>): Func<T, R> {
val rec = RecursiveFunc<T, R> { r -> f { r.p(r)(it) } }
return rec.p(rec)
}
fun fac(f: Func<Int, Int>) = { x: Int -> if (x <= 1) 1 else x * f(x - ... |
Transform the following Python implementation into Scala, maintaining the same output and logic. | from collections import namedtuple
Circle = namedtuple("Circle", "x y r")
circles = [
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Circ... |
class Circle(val x: Double, val y: Double, val r: Double)
val circles = arrayOf(
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Circle(-... |
Convert the following code from Python to Scala, ensuring the logic remains intact. | from collections import namedtuple
Circle = namedtuple("Circle", "x y r")
circles = [
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Circ... |
class Circle(val x: Double, val y: Double, val r: Double)
val circles = arrayOf(
Circle( 1.6417233788, 1.6121789534, 0.0848270516),
Circle(-1.4944608174, 1.2077959613, 1.1039549836),
Circle( 0.6110294452, -0.6907087527, 0.9089162485),
Circle( 0.3844862411, 0.2923344616, 0.2375743054),
Circle(-... |
Produce a functionally identical Scala code for the snippet given in Python. | fact = [1]
for n in range(1, 12):
fact.append(fact[n-1] * n)
for b in range(9, 12+1):
print(f"The factorions for base {b} are:")
for i in range(1, 1500000):
fact_sum = 0
j = i
while j > 0:
d = j % b
fact_sum += fact[d]
j = j//b
if fact_su... | object Factorion extends App {
private def is_factorion(i: Int, b: Int): Boolean = {
var sum = 0L
var j = i
while (j > 0) {
sum += f(j % b)
j /= b
}
sum == i
}
private val f = Array.ofDim[Long](12)
f(0) = 1L
(1 until 12).foreach(n => ... |
Convert the following code from Python to Scala, ensuring the logic remains intact. | fact = [1]
for n in range(1, 12):
fact.append(fact[n-1] * n)
for b in range(9, 12+1):
print(f"The factorions for base {b} are:")
for i in range(1, 1500000):
fact_sum = 0
j = i
while j > 0:
d = j % b
fact_sum += fact[d]
j = j//b
if fact_su... | object Factorion extends App {
private def is_factorion(i: Int, b: Int): Boolean = {
var sum = 0L
var j = i
while (j > 0) {
sum += f(j % b)
j /= b
}
sum == i
}
private val f = Array.ofDim[Long](12)
f(0) = 1L
(1 until 12).foreach(n => ... |
Keep all operations the same but rewrite the snippet in Scala. | def factorize(n):
assert(isinstance(n, int))
if n < 0:
n = -n
if n < 2:
return
k = 0
while 0 == n%2:
k += 1
n //= 2
if 0 < k:
yield (2,k)
p = 3
while p*p <= n:
k = 0
while 0 == n%p:
k += 1
n //... | fun divisorSum(n: Long): Long {
var nn = n
var total = 1L
var power = 2L
while ((nn and 1) == 0L) {
total += power
power = power shl 1
nn = nn shr 1
}
var p = 3L
while (p * p <= nn) {
var sum = 1L
power = p
while (nn % p == 0L) {
... |
Preserve the algorithm and functionality while converting the code from Python to Scala. | def factorize(n):
assert(isinstance(n, int))
if n < 0:
n = -n
if n < 2:
return
k = 0
while 0 == n%2:
k += 1
n //= 2
if 0 < k:
yield (2,k)
p = 3
while p*p <= n:
k = 0
while 0 == n%p:
k += 1
n //... | fun divisorSum(n: Long): Long {
var nn = n
var total = 1L
var power = 2L
while ((nn and 1) == 0L) {
total += power
power = power shl 1
nn = nn shr 1
}
var p = 3L
while (p * p <= nn) {
var sum = 1L
power = p
while (nn % p == 0L) {
... |
Convert this Python block to Scala, preserving its control flow and logic. | def factors(x):
factors = []
i = 2
s = int(x ** 0.5)
while i < s:
if x % i == 0:
factors.append(i)
x = int(x / i)
s = int(x ** 0.5)
i += 1
factors.append(x)
return factors
print("First 10 Fermat numbers:")
for i in range(10):
fermat = 2 **... | import java.math.BigInteger
import kotlin.math.pow
fun main() {
println("First 10 Fermat numbers:")
for (i in 0..9) {
println("F[$i] = ${fermat(i)}")
}
println()
println("First 12 Fermat numbers factored:")
for (i in 0..12) {
println("F[$i] = ${getString(getFactors(i, fermat(i))... |
Convert this Python block to Scala, preserving its control flow and logic. |
from itertools import zip_longest
def beadsort(l):
return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))
print(beadsort([5,3,1,7,4,1,1]))
|
fun beadSort(a: IntArray) {
val n = a.size
if (n < 2) return
var max = a.max()!!
val beads = ByteArray(max * n)
for (i in 0 until n)
for (j in 0 until a[i])
beads[i * max + j] = 1
for (j in 0 until max) {
var sum = 0
for (i in 0 until n) {
... |
Keep all operations the same but rewrite the snippet in Scala. |
def CastOut(Base=10, Start=1, End=999999):
ran = [y for y in range(Base-1) if y%(Base-1) == (y*y)%(Base-1)]
x,y = divmod(Start, Base-1)
while True:
for n in ran:
k = (Base-1)*x + n
if k < Start:
continue
if k > End:
return
yield k
x += 1
for V in CastOut(Base=1... |
fun castOut(base: Int, start: Int, end: Int): List<Int> {
val b = base - 1
val ran = (0 until b).filter { it % b == (it * it) % b }
var x = start / b
val result = mutableListOf<Int>()
while (true) {
for (n in ran) {
val k = b * x + n
if (k < start) continue
... |
Port the following code from Python to Scala with equivalent syntax and logic. |
def CastOut(Base=10, Start=1, End=999999):
ran = [y for y in range(Base-1) if y%(Base-1) == (y*y)%(Base-1)]
x,y = divmod(Start, Base-1)
while True:
for n in ran:
k = (Base-1)*x + n
if k < Start:
continue
if k > End:
return
yield k
x += 1
for V in CastOut(Base=1... |
fun castOut(base: Int, start: Int, end: Int): List<Int> {
val b = base - 1
val ran = (0 until b).filter { it % b == (it * it) % b }
var x = start / b
val result = mutableListOf<Int>()
while (true) {
for (n in ran) {
val k = b * x + n
if (k < start) continue
... |
Transform the following Python implementation into Scala, maintaining the same output and logic. |
import argparse
from argparse import Namespace
import datetime
import shlex
def parse_args():
'Set up, parse, and return arguments'
parser = argparse.ArgumentParser(epilog=globals()['__doc__'])
parser.add_argument('command', choices='add pl plc pa'.split(),
help=)
par... |
import java.text.SimpleDateFormat
import java.util.Date
import java.io.File
import java.io.IOException
val file = File("simdb.csv")
class Item(
val name: String,
val date: String,
val category: String
) : Comparable<Item> {
override fun compareTo(other: Item) = date.compareTo(other.date)
over... |
Translate the given Python code snippet into Scala without altering its behavior. |
import curses
def print_message():
stdscr.addstr('This is the message.\n')
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
stdscr.addstr('CTRL+P for message or q to quit.\n')
while True:
c = stdscr.getch()
if c == 16: print_message()
elif c == ord('q'): break
curses.nocbr... |
import javax.swing.JFrame
import javax.swing.JLabel
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
fun main(args: Array<String>) {
val directions = "<html><b>Ctrl-S</b> to show frame title<br>" +
"<b>Ctrl-H</b> to hide it</html>"
with (JFrame()) {
add(JLabel(dire... |
Preserve the algorithm and functionality while converting the code from Python to Scala. |
def isPrime(n) :
if (n < 2) :
return False
for i in range(2, n + 1) :
if (i * i <= n and n % i == 0) :
return False
return True
def mobius(N) :
if (N == 1) :
return 1
p = 0
for i in range(1, N + 1) :
if... | import kotlin.math.sqrt
fun main() {
println("First 199 terms of the möbius function are as follows:")
print(" ")
for (n in 1..199) {
print("%2d ".format(mobiusFunction(n)))
if ((n + 1) % 20 == 0) {
println()
}
}
}
private const val MU_MAX = 1000000
private var ... |
Convert the following code from Python to Scala, ensuring the logic remains intact. | def product_of_divisors(n):
assert(isinstance(n, int) and 0 < n)
ans = i = j = 1
while i*i <= n:
if 0 == n%i:
ans *= i
j = n//i
if j != i:
ans *= j
i += 1
return ans
if __name__ == "__main__":
print([product_of_divisors(n) for ... | import kotlin.math.pow
private fun divisorCount(n: Long): Long {
var nn = n
var total: Long = 1
while (nn and 1 == 0L) {
++total
nn = nn shr 1
}
var p: Long = 3
while (p * p <= nn) {
var count = 1L
while (nn % p == 0L) {
++count
... |
Translate the given Python code snippet into Scala without altering its behavior. | def product_of_divisors(n):
assert(isinstance(n, int) and 0 < n)
ans = i = j = 1
while i*i <= n:
if 0 == n%i:
ans *= i
j = n//i
if j != i:
ans *= j
i += 1
return ans
if __name__ == "__main__":
print([product_of_divisors(n) for ... | import kotlin.math.pow
private fun divisorCount(n: Long): Long {
var nn = n
var total: Long = 1
while (nn and 1 == 0L) {
++total
nn = nn shr 1
}
var p: Long = 3
while (p * p <= nn) {
var count = 1L
while (nn % p == 0L) {
++count
... |
Generate a Scala translation of this Python snippet without changing its computational steps. | import random
class Card(object):
suits = ("Clubs","Hearts","Spades","Diamonds")
pips = ("2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace")
def __init__(self, pip,suit):
self.pip=pip
self.suit=suit
def __str__(self):
return "%s %s"%(self.pip,self.suit)
class De... | const val FACES = "23456789TJQKA"
const val SUITS = "shdc"
fun createDeck(): List<String> {
val cards = mutableListOf<String>()
FACES.forEach { face -> SUITS.forEach { suit -> cards.add("$face$suit") } }
return cards
}
fun dealTopDeck(deck: List<String>, n: Int) = deck.take(n)
fun dealBottomDeck(deck: Li... |
Ensure the translated Scala code behaves exactly like the original Python snippet. | from math import gcd
from functools import lru_cache
from itertools import islice, count
@lru_cache(maxsize=None)
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
def perfect_totient():
for n0 in count(1):
parts, n = 0, n0
while n != 1:
n = φ(n)
parts... |
fun totient(n: Int): Int {
var tot = n
var nn = n
var i = 2
while (i * i <= nn) {
if (nn % i == 0) {
while (nn % i == 0) nn /= i
tot -= tot / i
}
if (i == 2) i = 1
i += 2
}
if (nn > 1) tot -= tot / nn
return tot
}
fun main() {
va... |
Port the following code from Python to Scala with equivalent syntax and logic. | from math import gcd
from functools import lru_cache
from itertools import islice, count
@lru_cache(maxsize=None)
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
def perfect_totient():
for n0 in count(1):
parts, n = 0, n0
while n != 1:
n = φ(n)
parts... |
fun totient(n: Int): Int {
var tot = n
var nn = n
var i = 2
while (i * i <= nn) {
if (nn % i == 0) {
while (nn % i == 0) nn /= i
tot -= tot / i
}
if (i == 2) i = 1
i += 2
}
if (nn > 1) tot -= tot / nn
return tot
}
fun main() {
va... |
Generate a Scala translation of this Python snippet without changing its computational steps. | from math import (comb,
factorial)
def lah(n, k):
if k == 1:
return factorial(n)
if k == n:
return 1
if k > n:
return 0
if k < 1 or n < 1:
return 0
return comb(n, k) * factorial(n - 1) // factorial(k - 1)
def main():
print("Unsigned Lah numbe... | import java.math.BigInteger
fun factorial(n: BigInteger): BigInteger {
if (n == BigInteger.ZERO) return BigInteger.ONE
if (n == BigInteger.ONE) return BigInteger.ONE
var prod = BigInteger.ONE
var num = n
while (num > BigInteger.ONE) {
prod *= num
num--
}
return prod
}
fun l... |
Produce a functionally identical Scala code for the snippet given in Python. | from math import (comb,
factorial)
def lah(n, k):
if k == 1:
return factorial(n)
if k == n:
return 1
if k > n:
return 0
if k < 1 or n < 1:
return 0
return comb(n, k) * factorial(n - 1) // factorial(k - 1)
def main():
print("Unsigned Lah numbe... | import java.math.BigInteger
fun factorial(n: BigInteger): BigInteger {
if (n == BigInteger.ZERO) return BigInteger.ONE
if (n == BigInteger.ONE) return BigInteger.ONE
var prod = BigInteger.ONE
var num = n
while (num > BigInteger.ONE) {
prod *= num
num--
}
return prod
}
fun l... |
Generate an equivalent Scala version of this Python code. | def two_sum(arr, num):
i = 0
j = len(arr) - 1
while i < j:
if arr[i] + arr[j] == num:
return (i, j)
if arr[i] + arr[j] < num:
i += 1
else:
j -= 1
return None
numbers = [0, 2, 11, 19, 90]
print(two_sum(numbers, 21))
print(two_sum(numbers, 25))... |
fun twoSum(a: IntArray, targetSum: Int): Pair<Int, Int>? {
if (a.size < 2) return null
var sum: Int
for (i in 0..a.size - 2) {
if (a[i] <= targetSum) {
for (j in i + 1..a.size - 1) {
sum = a[i] + a[j]
if (sum == targetSum) return Pair(i, j)
... |
Convert this Python snippet to Scala and keep its semantics consistent. | def two_sum(arr, num):
i = 0
j = len(arr) - 1
while i < j:
if arr[i] + arr[j] == num:
return (i, j)
if arr[i] + arr[j] < num:
i += 1
else:
j -= 1
return None
numbers = [0, 2, 11, 19, 90]
print(two_sum(numbers, 21))
print(two_sum(numbers, 25))... |
fun twoSum(a: IntArray, targetSum: Int): Pair<Int, Int>? {
if (a.size < 2) return null
var sum: Int
for (i in 0..a.size - 2) {
if (a[i] <= targetSum) {
for (j in i + 1..a.size - 1) {
sum = a[i] + a[j]
if (sum == targetSum) return Pair(i, j)
... |
Convert the following code from Python to Scala, ensuring the logic remains intact. |
def cocktailshiftingbounds(A):
beginIdx = 0
endIdx = len(A) - 1
while beginIdx <= endIdx:
newBeginIdx = endIdx
newEndIdx = beginIdx
for ii in range(beginIdx,endIdx):
if A[ii] > A[ii + 1]:
A[ii+1], A[ii] = A[ii], A[ii+1]
n... | fun <T> swap(array: Array<T>, i: Int, j: Int) {
val temp = array[i]
array[i] = array[j]
array[j] = temp
}
fun <T> cocktailSort(array: Array<T>) where T : Comparable<T> {
var begin = 0
var end = array.size
if (end == 0) {
return
}
--end
while (begin < end) {
var newBe... |
Port the following code from Python to Scala with equivalent syntax and logic. | import sys
if "UTF-8" in sys.stdout.encoding:
print("△")
else:
raise Exception("Terminal can't handle UTF-8")
|
fun main(args: Array<String>) {
val supportsUnicode = "UTF" in System.getenv("LANG").toUpperCase()
if (supportsUnicode)
println("This terminal supports unicode and U+25b3 is : \u25b3")
else
println("This terminal does not support unicode")
}
|
Generate a Scala translation of this Python snippet without changing its computational steps. | import sys
if "UTF-8" in sys.stdout.encoding:
print("△")
else:
raise Exception("Terminal can't handle UTF-8")
|
fun main(args: Array<String>) {
val supportsUnicode = "UTF" in System.getenv("LANG").toUpperCase()
if (supportsUnicode)
println("This terminal supports unicode and U+25b3 is : \u25b3")
else
println("This terminal does not support unicode")
}
|
Write a version of this Python function in Scala with identical behavior. | from itertools import count, islice
def primes(_cache=[2, 3]):
yield from _cache
for n in count(_cache[-1]+2, 2):
if isprime(n):
_cache.append(n)
yield n
def isprime(n, _seen={0: False, 1: False}):
def _isprime(n):
for p in primes():
if p*p > n:
... | private const val MAX = 10000000
private val primes = BooleanArray(MAX)
fun main() {
sieve()
println("First 35 unprimeable numbers:")
displayUnprimeableNumbers(35)
val n = 600
println()
println("The ${n}th unprimeable number = ${nthUnprimeableNumber(n)}")
println()
val lowest = genLowes... |
Convert this Python block to Scala, preserving its control flow and logic. |
from itertools import takewhile
def primesWithGivenDigitSum(below, n):
return list(
takewhile(
lambda x: below > x,
(
x for x in primes()
if n == sum(int(c) for c in str(x))
)
)
)
def main():
matches = pri... | import java.math.BigInteger
fun digitSum(bi: BigInteger): Int {
var bi2 = bi
var sum = 0
while (bi2 > BigInteger.ZERO) {
val dr = bi2.divideAndRemainder(BigInteger.TEN)
sum += dr[1].toInt()
bi2 = dr[0]
}
return sum
}
fun main() {
val fiveK = BigInteger.valueOf(5_000)
... |
Please provide an equivalent version of this Python code in Scala. |
from itertools import takewhile
def primesWithGivenDigitSum(below, n):
return list(
takewhile(
lambda x: below > x,
(
x for x in primes()
if n == sum(int(c) for c in str(x))
)
)
)
def main():
matches = pri... | import java.math.BigInteger
fun digitSum(bi: BigInteger): Int {
var bi2 = bi
var sum = 0
while (bi2 > BigInteger.ZERO) {
val dr = bi2.divideAndRemainder(BigInteger.TEN)
sum += dr[1].toInt()
bi2 = dr[0]
}
return sum
}
fun main() {
val fiveK = BigInteger.valueOf(5_000)
... |
Maintain the same structure and functionality when rewriting this code in Scala. | from collections import deque
def prime_digits_sum(r):
q = deque([(r, 0)])
while q:
r, n = q.popleft()
for d in 2, 3, 5, 7:
if d >= r:
if d == r: yield n + d
break
q.append((r - d, (n + d) * 10))
print(*prime_digits_sum(13))
| fun primeDigitsSum13(n: Int): Boolean {
var nn = n
var sum = 0
while (nn > 0) {
val r = nn % 10
if (r != 2 && r != 3 && r != 5 && r != 7) {
return false
}
nn /= 10
sum += r
}
return sum == 13
}
fun main() {
var c = 0
for (i in 1 until... |
Produce a functionally identical Scala code for the snippet given in Python. | from collections import deque
def prime_digits_sum(r):
q = deque([(r, 0)])
while q:
r, n = q.popleft()
for d in 2, 3, 5, 7:
if d >= r:
if d == r: yield n + d
break
q.append((r - d, (n + d) * 10))
print(*prime_digits_sum(13))
| fun primeDigitsSum13(n: Int): Boolean {
var nn = n
var sum = 0
while (nn > 0) {
val r = nn % 10
if (r != 2 && r != 3 && r != 5 && r != 7) {
return false
}
nn /= 10
sum += r
}
return sum == 13
}
fun main() {
var c = 0
for (i in 1 until... |
Change the following Python code into Scala without altering its purpose. | import copy
deepcopy_of_obj = copy.deepcopy(obj)
|
import java.io.Serializable
import java.io.ByteArrayOutputStream
import java.io.ByteArrayInputStream
import java.io.ObjectOutputStream
import java.io.ObjectInputStream
fun <T : Serializable> deepCopy(obj: T?): T? {
if (obj == null) return null
val baos = ByteArrayOutputStream()
val oos = ObjectOutputStr... |
Convert this Python snippet to Scala and keep its semantics consistent. | import copy
deepcopy_of_obj = copy.deepcopy(obj)
|
import java.io.Serializable
import java.io.ByteArrayOutputStream
import java.io.ByteArrayInputStream
import java.io.ObjectOutputStream
import java.io.ObjectInputStream
fun <T : Serializable> deepCopy(obj: T?): T? {
if (obj == null) return null
val baos = ByteArrayOutputStream()
val oos = ObjectOutputStr... |
Produce a functionally identical Scala code for the snippet given in Python. | import random
def is_Prime(n):
if n!=int(n):
return False
n=int(n)
if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:
return False
if n==2 or n==3 or n==5 or n==7:
return True
s = 0
d = n-1
while d%2==0:
d>>=1
s+=1
assert(2**s * d == n-1)... | import java.math.BigInteger
val SMALL_PRIMES = listOf(
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 2... |
Write the same algorithm in Scala as shown in this Python implementation. | from itertools import permutations
in_order = lambda s: all(x <= s[i+1] for i,x in enumerate(s[:-1]))
perm_sort = lambda s: (p for p in permutations(s) if in_order(p)).next()
|
fun <T : Comparable<T>> isSorted(list: List<T>): Boolean {
val size = list.size
if (size < 2) return true
for (i in 1 until size) {
if (list[i] < list[i - 1]) return false
}
return true
}
fun <T : Comparable<T>> permute(input: List<T>): List<List<T>> {
if (input.size == 1) return list... |
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. | def root(a, b):
if b < 2:
return b
a1 = a - 1
c = 1
d = (a1 * c + b // (c ** a1)) // a
e = (a1 * d + b // (d ** a1)) // a
while c not in (d, e):
c, d, e = d, e, (a1 * e + b // (e ** a1)) // a
return min(d, e)
print("First 2,001 digits of the square root of two:\n{}".format(... |
import java.math.BigInteger
val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE
val bigTwo = BigInteger.valueOf(2L)
fun BigInteger.iRoot(n: Int): BigInteger {
require(this >= bigZero && n > 0)
if (this < bigTwo) return this
val n1 = n - 1
val n2 = BigInteger.valueOf(n.toLong())
val n3 = ... |
Generate an equivalent Scala version of this Python code. | def root(a, b):
if b < 2:
return b
a1 = a - 1
c = 1
d = (a1 * c + b // (c ** a1)) // a
e = (a1 * d + b // (d ** a1)) // a
while c not in (d, e):
c, d, e = d, e, (a1 * e + b // (e ** a1)) // a
return min(d, e)
print("First 2,001 digits of the square root of two:\n{}".format(... |
import java.math.BigInteger
val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE
val bigTwo = BigInteger.valueOf(2L)
fun BigInteger.iRoot(n: Int): BigInteger {
require(this >= bigZero && n > 0)
if (this < bigTwo) return this
val n1 = n - 1
val n2 = BigInteger.valueOf(n.toLong())
val n3 = ... |
Translate this program into Scala but keep the logic exactly as in Python. | >>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute()
<sqlite3.Cursor object at 0x013263B0>
>>>
c.execute()
<sqlite3.Cursor object at 0x013263B0>
>>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
('2006-0... |
import slick.jdbc.H2Profile.api._
import scala.concurrent.ExecutionContext.Implicits.global
object Main extends App {
class Suppliers(tag: Tag) extends Table[(Int, String, String, String, String, String)](tag, "SUPPLIERS") {
def id = column[Int]("SUP_ID", O.PrimaryKey)
def name = column[String]("SUP_NAME")
d... |
Generate an equivalent Scala version of this Python code. | >>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute()
<sqlite3.Cursor object at 0x013263B0>
>>>
c.execute()
<sqlite3.Cursor object at 0x013263B0>
>>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
('2006-0... |
import slick.jdbc.H2Profile.api._
import scala.concurrent.ExecutionContext.Implicits.global
object Main extends App {
class Suppliers(tag: Tag) extends Table[(Int, String, String, String, String, String)](tag, "SUPPLIERS") {
def id = column[Int]("SUP_ID", O.PrimaryKey)
def name = column[String]("SUP_NAME")
d... |
Port the following code from Python to Scala with equivalent syntax and logic. | nicePrimes( s, e ) = { local( m );
forprime( p = s, e,
m = p; \\
while( m > 9, \\ m == p mod 9
m = sumdigits( m ) ); \\
if( isprime( m ),
print1( p, " " ) ) );
}
| fun isPrime(n: Long): Boolean {
if (n < 2) {
return false
}
if (n % 2 == 0L) {
return n == 2L
}
if (n % 3 == 0L) {
return n == 3L
}
var p = 5
while (p * p <= n) {
if (n % p == 0L) {
return false
}
p += 2
if (n % p == 0L... |
Rewrite the snippet below in Scala so it works the same as the original Python code. | nicePrimes( s, e ) = { local( m );
forprime( p = s, e,
m = p; \\
while( m > 9, \\ m == p mod 9
m = sumdigits( m ) ); \\
if( isprime( m ),
print1( p, " " ) ) );
}
| fun isPrime(n: Long): Boolean {
if (n < 2) {
return false
}
if (n % 2 == 0L) {
return n == 2L
}
if (n % 3 == 0L) {
return n == 3L
}
var p = 5
while (p * p <= n) {
if (n % p == 0L) {
return false
}
p += 2
if (n % p == 0L... |
Port the provided Python code into Scala while preserving the original functionality. | import sys
import calendar
year = 2013
if len(sys.argv) > 1:
try:
year = int(sys.argv[-1])
except ValueError:
pass
for month in range(1, 13):
last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month))
print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sun... |
import java.util.*
fun main(args: Array<String>) {
print("Enter a year : ")
val year = readLine()!!.toInt()
println("The last Sundays of each month in $year are as follows:")
val calendar = GregorianCalendar(year, 0, 31)
for (month in 1..12) {
val daysInMonth = calendar.getActualMaximum(... |
Produce a language-to-language conversion: from Python to Scala, same semantics. | import sys
import calendar
year = 2013
if len(sys.argv) > 1:
try:
year = int(sys.argv[-1])
except ValueError:
pass
for month in range(1, 13):
last_sunday = max(week[-1] for week in calendar.monthcalendar(year, month))
print('{}-{}-{:2}'.format(year, calendar.month_abbr[month], last_sun... |
import java.util.*
fun main(args: Array<String>) {
print("Enter a year : ")
val year = readLine()!!.toInt()
println("The last Sundays of each month in $year are as follows:")
val calendar = GregorianCalendar(year, 0, 31)
for (month in 1..12) {
val daysInMonth = calendar.getActualMaximum(... |
Write a version of this Python function in Scala with identical behavior. | from random import choice, shuffle
from copy import deepcopy
def rls(n):
if n <= 0:
return []
else:
symbols = list(range(n))
square = _rls(symbols)
return _shuffle_transpose_shuffle(square)
def _shuffle_transpose_shuffle(matrix):
square = deepcopy(matrix)
shuffle(squar... | typealias matrix = MutableList<MutableList<Int>>
fun printSquare(latin: matrix) {
for (row in latin) {
println(row)
}
println()
}
fun latinSquare(n: Int) {
if (n <= 0) {
println("[]")
return
}
val latin = MutableList(n) { MutableList(n) { it } }
latin[0].shuff... |
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. | from itertools import count, islice
def _basechange_int(num, b):
if num == 0:
return [0]
result = []
while num != 0:
num, d = divmod(num, b)
result.append(d)
return result[::-1]
def fairshare(b=2):
for i in count():
yield sum(_basechange_int(i, b)) % b
if __na... | fun turn(base: Int, n: Int): Int {
var sum = 0
var n2 = n
while (n2 != 0) {
val re = n2 % base
n2 /= base
sum += re
}
return sum % base
}
fun fairShare(base: Int, count: Int) {
print(String.format("Base %2d:", base))
for (i in 0 until count) {
val t = turn(ba... |
Please provide an equivalent version of this Python code in Scala. | from collections import deque
from itertools import dropwhile, islice, takewhile
from textwrap import wrap
from typing import Iterable, Iterator
Digits = str
def esthetic_nums(base: int) -> Iterator[int]:
queue: deque[tuple[int, int]] = deque()
queue.extendleft((d, d) for d in range(1, base))
whi... | import kotlin.math.abs
fun isEsthetic(n: Long, b: Long): Boolean {
if (n == 0L) {
return false
}
var i = n % b
var n2 = n / b
while (n2 > 0) {
val j = n2 % b
if (abs(i - j) != 1L) {
return false
}
n2 /= b
i = j
}
return true
}
fun... |
Translate this program into Scala but keep the logic exactly as in Python. |
u = 'abcdé'
print(ord(u[-1]))
|
fun main(args: Array<String>) {
val åäö = "as⃝df̅ ♥♦♣♠ 頰"
println(åäö)
}
|
Preserve the algorithm and functionality while converting the code from Python to Scala. | from operator import itemgetter
DEBUG = False
def spermutations(n):
sign = 1
p = [[i, 0 if i == 0 else -1]
for i in range(n)]
if DEBUG: print '
yield tuple(pp[0] for pp in p), sign
while any(pp[1] for pp in p):
i1, (n1, d1) = max(((i, pp) for i, pp in enumerate(p) i... |
fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> {
val p = IntArray(n) { it }
val q = IntArray(n) { it }
val d = IntArray(n) { -1 }
var sign = 1
val perms = mutableListOf<IntArray>()
val signs = mutableListOf<Int>()
fun permute(k: Int) {
if (k >= n) {
... |
Convert this Python snippet to Scala and keep its semantics consistent. | import random
random.seed()
attributes_total = 0
count = 0
while attributes_total < 75 or count < 2:
attributes = []
for attribute in range(0, 6):
rolls = []
for roll in range(0, 4):
result = random.randint(1, 6)
rolls.append(result)
sorted_rol... | import scala.util.Random
Random.setSeed(1)
def rollDice():Int = {
val v4 = Stream.continually(Random.nextInt(6)+1).take(4)
v4.sum - v4.min
}
def getAttributes():Seq[Int] = Stream.continually(rollDice()).take(6)
def getCharacter():Seq[Int] = {
val attrs = getAttributes()
println("generated => " + attrs.mkStri... |
Ensure the translated Scala code behaves exactly like the original Python snippet. | import itertools
def cycler(start_items):
return itertools.cycle(start_items).__next__
def _kolakoski_gen(start_items):
s, k = [], 0
c = cycler(start_items)
while True:
c_next = c()
s.append(c_next)
sk = s[k]
yield sk
if sk > 1:
s += [c_next] * (sk - 1)... |
fun IntArray.nextInCycle(index: Int) = this[index % this.size]
fun IntArray.kolakoski(len: Int): IntArray {
val s = IntArray(len)
var i = 0
var k = 0
while (true) {
s[i] = this.nextInCycle(k)
if (s[k] > 1) {
repeat(s[k] - 1) {
if (++i == len) return s
... |
Translate this program into Scala but keep the logic exactly as in Python. | def divisors(n):
divs = [1]
for ii in range(2, int(n ** 0.5) + 3):
if n % ii == 0:
divs.append(ii)
divs.append(int(n / ii))
divs.append(n)
return list(set(divs))
def sequence(max_n=None):
n = 0
while True:
n += 1
ii = 0
if max_n is not No... |
const val MAX = 15
fun countDivisors(n: Int): Int {
var count = 0
var i = 1
while (i * i <= n) {
if (n % i == 0) {
count += if (i == n / i) 1 else 2
}
i++
}
return count
}
fun main() {
var seq = IntArray(MAX)
println("The first $MAX terms of the sequen... |
Produce a functionally identical Scala code for the snippet given in Python. |
bar = '▁▂▃▄▅▆▇█'
barcount = len(bar)
def sparkline(numbers):
mn, mx = min(numbers), max(numbers)
extent = mx - mn
sparkline = ''.join(bar[min([barcount - 1,
int((n - mn) / extent * barcount)])]
for n in numbers)
return mn, mx, sparkline
if __... | internal const val bars = "▁▂▃▄▅▆▇█"
internal const val n = bars.length - 1
fun <T: Number> Iterable<T>.toSparkline(): String {
var min = Double.MAX_VALUE
var max = Double.MIN_VALUE
val doubles = map { it.toDouble() }
doubles.forEach { i -> when { i < min -> min = i; i > max -> max = i } }
val rang... |
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. | from difflib import ndiff
def levenshtein(str1, str2):
result = ""
pos, removed = 0, 0
for x in ndiff(str1, str2):
if pos<len(str1) and str1[pos] == x[2]:
pos += 1
result += x[2]
if x[0] == "-":
removed += 1
continue
else:
if r... |
fun levenshteinAlign(a: String, b: String): Array<String> {
val aa = a.toLowerCase()
val bb = b.toLowerCase()
val costs = Array(a.length + 1) { IntArray(b.length + 1) }
for (j in 0..b.length) costs[0][j] = j
for (i in 1..a.length) {
costs[i][0] = i
for (j in 1..b.length) {
... |
Rewrite the snippet below in Scala so it works the same as the original Python code. | def longest_increasing_subsequence(X):
N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
lo = 1
hi = L
while lo <= hi:
mid = (lo+hi)//2
if (X[M[mid]] < X[i]):
lo = mid+1
else:
hi = mid-1
... |
fun longestIncreasingSubsequence(x: IntArray): IntArray =
when (x.size) {
0 -> IntArray(0)
1 -> x
else -> {
val n = x.size
val p = IntArray(n)
val m = IntArray(n + 1)
var len = 0
for (i in 0 until n) {
var... |
Keep all operations the same but rewrite the snippet in Scala. | from macropy.core.macros import *
from macropy.core.quotes import macros, q, ast, u
macros = Macros()
@macros.expr
def expand(tree, **kw):
addition = 10
return q[lambda x: x * ast[tree] + u[addition]]
|
infix fun Double.pwr(exp: Double) = Math.pow(this, exp)
fun main(args: Array<String>) {
val d = 2.0 pwr 8.0
println(d)
}
|
Convert this Python snippet to Scala and keep its semantics consistent. | >>> name = raw_input("Enter a variable name: ")
Enter a variable name: X
>>> globals()[name] = 42
>>> X
42
|
fun main(args: Array<String>) {
var n: Int
do {
print("How many integer variables do you want to create (max 5) : ")
n = readLine()!!.toInt()
}
while (n < 1 || n > 5)
val map = mutableMapOf<String, Int>()
var name: String
var value: Int
var i = 1
println("OK, enter... |
Translate the given Python code snippet into Scala without altering its behavior. | from __future__ import print_function
def order_disjoint_list_items(data, items):
itemindices = []
for item in set(items):
itemcount = items.count(item)
lastindex = [-1]
for i in range(itemcount):
lastindex.append(data.index(item, lastindex[-1] + 1))
it... |
const val NULL = "\u0000"
fun orderDisjointList(m: String, n: String): String {
val nList = n.split(' ')
var p = m
for (item in nList) p = p.replaceFirst(item, NULL)
val mList = p.split(NULL)
val sb = StringBuilder()
for (i in 0 until nList.size) sb.append(mList[i], nList[i]) ... |
Convert this Python block to Scala, preserving its control flow and logic. | python
Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(string1, string2, separator):
return separator.join([string1, '', string2])
>>> f('Rosetta', 'Code', ':')
'Rosetta::Code'
>>>
| c:\kotlin-compiler-1.0.6>kotlinc
Welcome to Kotlin version 1.0.6-release-127 (JRE 1.8.0_31-b13)
Type :help for help, :quit for quit
>>> fun f(s1: String, s2: String, sep: String) = s1 + sep + sep + s2
>>> f("Rosetta", "Code", ":")
Rosetta::Code
>>> :quit
|
Please provide an equivalent version of this Python code in Scala. | >>> def eval_with_x(code, a, b):
return eval(code, {'x':b}) - eval(code, {'x':a})
>>> eval_with_x('2 ** x', 3, 5)
24
|
fun evalWithX(expr: String, a: Double, b: Double) {
var x = a
val atA = eval(expr)
x = b
val atB = eval(expr)
return atB - atA
}
fun main(args: Array<String>) {
println(evalWithX("Math.exp(x)", 0.0, 1.0))
}
|
Can you help me rewrite this code in Scala instead of Python, keeping it the same logically? | >>> def eval_with_x(code, a, b):
return eval(code, {'x':b}) - eval(code, {'x':a})
>>> eval_with_x('2 ** x', 3, 5)
24
|
fun evalWithX(expr: String, a: Double, b: Double) {
var x = a
val atA = eval(expr)
x = b
val atB = eval(expr)
return atB - atA
}
fun main(args: Array<String>) {
println(evalWithX("Math.exp(x)", 0.0, 1.0))
}
|
Please provide an equivalent version of this Python code in Scala. |
import re
male2female=u
re_nl=re.compile(r",[ \n]*")
m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ]
switch={}
words=[]
re_plural=re.compile("E*S$")
re_ES=re.compile("ES$")
def gen_pluralize(m,f):
yield re_plural.sub("",m),re_plural.sub("",f)
yield re_ES.sub("es",m),re_ES.sub("es",f)
yie... |
fun reverseGender(s: String): String {
var t = s
val words = listOf("She", "she", "Her", "her", "hers", "He", "he", "His", "his", "him")
val repls = listOf("He_", "he_", "His_", "his_" ,"his_", "She_", "she_", "Her_", "her_", "her_")
for (i in 0 until words.size) {
val r = Regex("""\b$... |
Convert the following code from Python to Scala, ensuring the logic remains intact. |
import re
male2female=u
re_nl=re.compile(r",[ \n]*")
m2f=[ tok.split(" ") for tok in re_nl.split(male2female) ]
switch={}
words=[]
re_plural=re.compile("E*S$")
re_ES=re.compile("ES$")
def gen_pluralize(m,f):
yield re_plural.sub("",m),re_plural.sub("",f)
yield re_ES.sub("es",m),re_ES.sub("es",f)
yie... |
fun reverseGender(s: String): String {
var t = s
val words = listOf("She", "she", "Her", "her", "hers", "He", "he", "His", "his", "him")
val repls = listOf("He_", "he_", "His_", "his_" ,"his_", "She_", "she_", "Her_", "her_", "her_")
for (i in 0 until words.size) {
val r = Regex("""\b$... |
Preserve the algorithm and functionality while converting the code from Python to Scala. | def rank(x): return int('a'.join(map(str, [1] + x)), 11)
def unrank(n):
s = ''
while n: s,n = "0123456789a"[n%11] + s, n//11
return map(int, s.split('a'))[1:]
l = [1, 2, 3, 10, 100, 987654321]
print l
n = rank(l)
print n
l = unrank(n)
print l
|
import java.math.BigInteger
fun rank(li: List<Int>) = when (li.size) {
0 -> -BigInteger.ONE
else -> BigInteger(li.joinToString("a"), 11)
}
fun unrank(r: BigInteger) = when (r) {
-BigInteger.ONE -> emptyList<Int>()
else -> r.toString(11).split('a').map { if (it != "") it.toInt() else ... |
Produce a language-to-language conversion: from Python to Scala, same semantics. | best = 0
best_out = ""
target = 952
nbrs = [100, 75, 50, 25, 6, 3]
def sol(target, nbrs, out=""):
global best, best_out
if abs(target - best) > abs(target - nbrs[0]):
best = nbrs[0]
best_out = out
if target == nbrs[0]:
print(out)
elif len(nbrs) > 1:
for i1 in range(... | var best = 0
var best_out = ""
val target = 952
val nbrs = List(100, 75, 50, 25, 6, 3)
def sol(target: Int, xs: List[Int], out: String): Unit = {
if ((target - best).abs > (target - xs.head).abs) {
best = xs.head
best_out = out
}
if (target == xs.head)
println(out)
else
0 until (xs.size-1) fore... |
Preserve the algorithm and functionality while converting the code from Python to Scala. | best = 0
best_out = ""
target = 952
nbrs = [100, 75, 50, 25, 6, 3]
def sol(target, nbrs, out=""):
global best, best_out
if abs(target - best) > abs(target - nbrs[0]):
best = nbrs[0]
best_out = out
if target == nbrs[0]:
print(out)
elif len(nbrs) > 1:
for i1 in range(... | var best = 0
var best_out = ""
val target = 952
val nbrs = List(100, 75, 50, 25, 6, 3)
def sol(target: Int, xs: List[Int], out: String): Unit = {
if ((target - best).abs > (target - xs.head).abs) {
best = xs.head
best_out = out
}
if (target == xs.head)
println(out)
else
0 until (xs.size-1) fore... |
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. |
var x = 0
var y = 0
There are also multi-line comments
Everything inside of
]
discard
|
like so
*/
const val CURRENT_VERSION = "1.0.5-2"
const val NEXT_MAJOR_VERSION = "1.1"
fun main(args: Array<String>) {
println("Current stable version is $CURRENT_VERSION")
println("Next major version is $NEXT_MAJOR_VERSION")
}
|
Translate the given Python code snippet into Scala without altering its behavior. | def get_next_character(f):
c = f.read(1)
while c:
while True:
try:
yield c.decode('utf-8')
except UnicodeDecodeError:
c += f.read(1)
else:
c = f.read(1)
break
with open("input.txt","rb") as f:
for c in get_next_character(f):
... |
import java.io.File
const val EOF = -1
fun main(args: Array<String>) {
val reader = File("input.txt").reader()
reader.use {
while (true) {
val c = reader.read()
if (c == EOF) break
print(c.toChar())
}
}
}
|
Can you help me rewrite this code in Scala instead of Python, keeping it the same logically? |
import sys, os
import random
import time
def print_there(x, y, text):
sys.stdout.write("\x1b7\x1b[%d;%df%s\x1b8" % (x, y, text))
sys.stdout.flush()
class Ball():
def __init__(self):
self.x = 0
self.y = 0
def update(self):
self.x += random.randint(0,1)
self... |
import java.util.Random
val boxW = 41
val boxH = 37
val pinsBaseW = 19
val nMaxBalls = 55
val centerH = pinsBaseW + (boxW - pinsBaseW * 2 + 1) / 2 - 1
val rand = Random()
enum class Cell(val c: Char) {
EMPTY(' '),
BALL('o'),
WALL('|'),
CORNER('+'),
FLOOR('-'),
PIN('.')
}
... |
Convert this Python snippet to Scala and keep its semantics consistent. | from __future__ import print_function
from itertools import takewhile
maxsum = 99
def get_primes(max):
if max < 2:
return []
lprimes = [2]
for x in range(3, max + 1, 2):
for p in lprimes:
if x % p == 0:
break
else:
lprimes.append(x)
retur... |
const val MAXSUM = 99
fun getPrimes(max: Int): List<Int> {
if (max < 2) return emptyList<Int>()
val lprimes = mutableListOf(2)
outer@ for (x in 3..max step 2) {
for (p in lprimes) if (x % p == 0) continue@outer
lprimes.add(x)
}
return lprimes
}
fun main(args: Array<String>) {
... |
Generate an equivalent Scala version of this Python code. |
def circle_sort_backend(A:list, L:int, R:int)->'sort A in place, returning the number of swaps':
n = R-L
if n < 2:
return 0
swaps = 0
m = n//2
for i in range(m):
if A[R-(i+1)] < A[L+i]:
(A[R-(i+1)], A[L+i],) = (A[L+i], A[R-(i+1)],)
swaps += 1
if ... |
fun<T: Comparable<T>> circleSort(array: Array<T>, lo: Int, hi: Int, nSwaps: Int): Int {
if (lo == hi) return nSwaps
fun swap(array: Array<T>, i: Int, j: Int) {
val temp = array[i]
array[i] = array[j]
array[j] = temp
}
var high = hi
var low = lo
val mid = (hi ... |
Transform the following Python implementation into Scala, maintaining the same output and logic. | def getitem(s, depth=0):
out = [""]
while s:
c = s[0]
if depth and (c == ',' or c == '}'):
return out,s
if c == '{':
x = getgroup(s[1:], depth+1)
if x:
out,s = [a+b for a in out for b in x[0]], x[1]
continue
if c... |
object BraceExpansion {
fun expand(s: String) = expandR("", s, "")
private val r = Regex("""([\\]{2}|[\\][,}{])""")
private fun expandR(pre: String, s: String, suf: String) {
val noEscape = s.replace(r, " ")
var sb = StringBuilder("")
var i1 = noEscape.indexOf('{')
var i... |
Can you help me rewrite this code in Scala instead of Python, keeping it the same logically? | from itertools import islice
class INW():
def __init__(self, **wheels):
self._wheels = wheels
self.isect = {name: self._wstate(name, wheel)
for name, wheel in wheels.items()}
def _wstate(self, name, wheel):
"Wheel state holder"
assert all(val in... | import java.util.Collections
import java.util.stream.IntStream
object WheelController {
private val IS_NUMBER = "[0-9]".toRegex()
private const val TWENTY = 20
private var wheelMap = mutableMapOf<String, WheelModel>()
private fun advance(wheel: String) {
val w = wheelMap[wheel]
if (w!!... |
Change the programming language of this snippet from Python to Scala without modifying what it does. | from itertools import islice
class INW():
def __init__(self, **wheels):
self._wheels = wheels
self.isect = {name: self._wstate(name, wheel)
for name, wheel in wheels.items()}
def _wstate(self, name, wheel):
"Wheel state holder"
assert all(val in... | import java.util.Collections
import java.util.stream.IntStream
object WheelController {
private val IS_NUMBER = "[0-9]".toRegex()
private const val TWENTY = 20
private var wheelMap = mutableMapOf<String, WheelModel>()
private fun advance(wheel: String) {
val w = wheelMap[wheel]
if (w!!... |
Produce a language-to-language conversion: from Python to Scala, same semantics. | def get_pixel_colour(i_x, i_y):
import win32gui
i_desktop_window_id = win32gui.GetDesktopWindow()
i_desktop_window_dc = win32gui.GetWindowDC(i_desktop_window_id)
long_colour = win32gui.GetPixel(i_desktop_window_dc, i_x, i_y)
i_colour = int(long_colour)
win32gui.ReleaseDC(i_desktop_window_id,i_desktop_window_dc)
... | import java.awt.*
fun getMouseColor(): Color {
val location = MouseInfo.getPointerInfo().location
return getColorAt(location.x, location.y)
}
fun getColorAt(x: Int, y: Int): Color {
return Robot().getPixelColor(x, y)
}
|
Please provide an equivalent version of this Python code in Scala. | import urllib
import re
def fix(x):
p = re.compile(r'<[^<]*?>')
return p.sub('', x).replace('&', '&')
class YahooSearch:
def __init__(self, query, page=1):
self.query = query
self.page = page
self.url = "http://search.yahoo.com/search?p=%s&b=%s" %(self.query, ((self.pag... |
import java.net.URL
val rx = Regex("""<div class=\"yst result\">.+?<a href=\"(.*?)\" class=\"\">(.*?)</a>.+?class="abstract ellipsis">(.*?)</p>""")
class YahooResult(var title: String, var link: String, var text: String) {
override fun toString() = "\nTitle: $title\nLink : $link\nText : $text"
}
class YahooSe... |
Generate a Scala translation of this Python snippet without changing its computational steps. | from collections import namedtuple
from math import sqrt
Pt = namedtuple('Pt', 'x, y')
Circle = Cir = namedtuple('Circle', 'x, y, r')
def circles_from_p1p2r(p1, p2, r):
'Following explanation at http://mathforum.org/library/drmath/view/53027.html'
if r == 0.0:
raise ValueError('radius of zero')
(x... |
typealias IAE = IllegalArgumentException
class Point(val x: Double, val y: Double) {
fun distanceFrom(other: Point): Double {
val dx = x - other.x
val dy = y - other.y
return Math.sqrt(dx * dx + dy * dy )
}
override fun equals(other: Any?): Boolean {
if (other == null || ... |
Convert this Python snippet to Scala and keep its semantics consistent. | from collections import namedtuple
from math import sqrt
Pt = namedtuple('Pt', 'x, y')
Circle = Cir = namedtuple('Circle', 'x, y, r')
def circles_from_p1p2r(p1, p2, r):
'Following explanation at http://mathforum.org/library/drmath/view/53027.html'
if r == 0.0:
raise ValueError('radius of zero')
(x... |
typealias IAE = IllegalArgumentException
class Point(val x: Double, val y: Double) {
fun distanceFrom(other: Point): Double {
val dx = x - other.x
val dy = y - other.y
return Math.sqrt(dx * dx + dy * dy )
}
override fun equals(other: Any?): Boolean {
if (other == null || ... |
Keep all operations the same but rewrite the snippet in Scala. | import pyaudio
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
p = pyaudio.PyAudio()
stream = p.open(format = FORMAT,
channels = CHANNELS,
rate = RATE,
input = True,
frames_per_buffer = chunk)
data = stream.read(chunk)
print [ord(i) for... |
import java.io.File
import javax.sound.sampled.*
const val RECORD_TIME = 20000L
fun main(args: Array<String>) {
val wavFile = File("RecordAudio.wav")
val fileType = AudioFileFormat.Type.WAVE
val format = AudioFormat(16000.0f, 16, 2, true, true)
val info = DataLine.Info(TargetDataLine::class.java, f... |
Can you help me rewrite this code in Scala instead of Python, keeping it the same logically? | from __future__ import division
import math
from operator import mul
from itertools import product
from functools import reduce
def fac(n):
step = lambda x: 1 + x*4 - (x//2)*2
maxq = int(math.floor(math.sqrt(n)))
d = 1
q = n % 2 == 0 and 2 or 3
while q <= maxq and n % q != 0:
q = st... |
data class Fangs(val fang1: Long = 0L, val fang2: Long = 0L)
fun pow10(n: Int): Long = when {
n < 0 -> throw IllegalArgumentException("Can't be negative")
else -> {
var pow = 1L
for (i in 1..n) pow *= 10L
pow
}
}
fun countDigits(n: Long): Int = when {
n < 0L -> throw IllegalA... |
Write the same code in Scala as shown below in Python. | import random
n = 52
Black, Red = 'Black', 'Red'
blacks = [Black] * (n // 2)
reds = [Red] * (n // 2)
pack = blacks + reds
random.shuffle(pack)
black_stack, red_stack, discard = [], [], []
while pack:
top = pack.pop()
if top == Black:
black_stack.append(pack.pop())
else:
red_stack.appen... |
import java.util.Random
fun main(args: Array<String>) {
val pack = MutableList(52) { if (it < 26) 'R' else 'B' }
pack.shuffle()
val red = mutableListOf<Char>()
val black = mutableListOf<Char>()
val discard = mutableListOf<Char>()
for (i in 0 until 52 step 2) {
when (pack[i]... |
Change the programming language of this snippet from Python to Scala without modifying what it does. | import random
n = 52
Black, Red = 'Black', 'Red'
blacks = [Black] * (n // 2)
reds = [Red] * (n // 2)
pack = blacks + reds
random.shuffle(pack)
black_stack, red_stack, discard = [], [], []
while pack:
top = pack.pop()
if top == Black:
black_stack.append(pack.pop())
else:
red_stack.appen... |
import java.util.Random
fun main(args: Array<String>) {
val pack = MutableList(52) { if (it < 26) 'R' else 'B' }
pack.shuffle()
val red = mutableListOf<Char>()
val black = mutableListOf<Char>()
val discard = mutableListOf<Char>()
for (i in 0 until 52 step 2) {
when (pack[i]... |
Generate an equivalent Scala version of this Python code. |
def _init():
"digit sections for forming numbers"
digi_bits = .strip()
lines = [[d.replace('.', ' ') for d in ln.strip().split()]
for ln in digi_bits.strip().split('\n')
if '
formats = '<2 >2 <2 >2'.split()
digits = [[f"{dig:{f}}" for dig in line]
for f,... | import java.io.StringWriter
class Cistercian() {
constructor(number: Int) : this() {
draw(number)
}
private val size = 15
private var canvas = Array(size) { Array(size) { ' ' } }
init {
initN()
}
private fun initN() {
for (row in canvas) {
row.fill(' '... |
Generate a Scala translation of this Python snippet without changing its computational steps. |
def _init():
"digit sections for forming numbers"
digi_bits = .strip()
lines = [[d.replace('.', ' ') for d in ln.strip().split()]
for ln in digi_bits.strip().split('\n')
if '
formats = '<2 >2 <2 >2'.split()
digits = [[f"{dig:{f}}" for dig in line]
for f,... | import java.io.StringWriter
class Cistercian() {
constructor(number: Int) : this() {
draw(number)
}
private val size = 15
private var canvas = Array(size) { Array(size) { ' ' } }
init {
initN()
}
private fun initN() {
for (row in canvas) {
row.fill(' '... |
Can you help me rewrite this code in Scala instead of Python, keeping it the same logically? | :- initialization(main).
faces([a,k,q,j,10,9,8,7,6,5,4,3,2]).
face(F) :- faces(Fs), member(F,Fs).
suit(S) :- member(S, ['♥','♦','♣','♠']).
best_hand(Cards,H) :-
straight_flush(Cards,C) -> H = straight-flush(C)
; many_kind(Cards,F,4) -> H = four-of-a-kind(F)
; full_house(Cards,F1,F2) -> H = full-house(F1... |
class Card(val face: Int, val suit: Char)
const val FACES = "23456789tjqka"
const val SUITS = "shdc"
fun isStraight(cards: List<Card>): Boolean {
val sorted = cards.sortedBy { it.face }
if (sorted[0].face + 4 == sorted[4].face) return true
if (sorted[4].face == 14 && sorted[0].face == 2 && sorted[3].fac... |
Keep all operations the same but rewrite the snippet in Scala. | :- initialization(main).
faces([a,k,q,j,10,9,8,7,6,5,4,3,2]).
face(F) :- faces(Fs), member(F,Fs).
suit(S) :- member(S, ['♥','♦','♣','♠']).
best_hand(Cards,H) :-
straight_flush(Cards,C) -> H = straight-flush(C)
; many_kind(Cards,F,4) -> H = four-of-a-kind(F)
; full_house(Cards,F1,F2) -> H = full-house(F1... |
class Card(val face: Int, val suit: Char)
const val FACES = "23456789tjqka"
const val SUITS = "shdc"
fun isStraight(cards: List<Card>): Boolean {
val sorted = cards.sortedBy { it.face }
if (sorted[0].face + 4 == sorted[4].face) return true
if (sorted[4].face == 14 && sorted[0].face == 2 && sorted[3].fac... |
Generate an equivalent Scala version of this Python code. | from functools import wraps
from turtle import *
def memoize(obj):
cache = obj.cache = {}
@wraps(obj)
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in cache:
cache[key] = obj(*args, **kwargs)
return cache[key]
return memoizer
@memoize
def f... |
import java.awt.*
import javax.swing.*
class FibonacciWordFractal(n: Int) : JPanel() {
private val wordFractal: String
init {
preferredSize = Dimension(450, 620)
background = Color.black
wordFractal = wordFractal(n)
}
fun wordFractal(i: Int): String {
if (i < 2) re... |
Transform the following Python implementation into Scala, maintaining the same output and logic. | from __future__ import print_function
import random
from time import sleep
first = random.choice([True, False])
you = ''
if first:
me = ''.join(random.sample('HT'*3, 3))
print('I choose first and will win on first seeing {} in the list of tosses'.format(me))
while len(you) != 3 or any(ch not in 'HT' for c... |
import java.util.Random
val rand = Random()
val optimum = mapOf(
"HHH" to "THH", "HHT" to "THH", "HTH" to "HHT", "HTT" to "HHT",
"THH" to "TTH", "THT" to "TTH", "TTH" to "HTT", "TTT" to "HTT"
)
fun getUserSequence(): String {
println("A sequence of three H or T should be entered")
var userSeq: Stri... |
Port the following code from Python to Scala with equivalent syntax and logic. |
import turtle as t
def sier(n,length):
if n == 0:
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
| import java.awt.*
import javax.swing.JFrame
import javax.swing.JPanel
fun main(args: Array<String>) {
var i = 8
if (args.any()) {
try {
i = args.first().toInt()
} catch (e: NumberFormatException) {
i = 8
println("Usage: 'java SierpinskyTriangle [level]'\... |
Generate an equivalent Scala version of this Python code. |
import turtle as t
def sier(n,length):
if n == 0:
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
| import java.awt.*
import javax.swing.JFrame
import javax.swing.JPanel
fun main(args: Array<String>) {
var i = 8
if (args.any()) {
try {
i = args.first().toInt()
} catch (e: NumberFormatException) {
i = 8
println("Usage: 'java SierpinskyTriangle [level]'\... |
Write the same algorithm in Scala as shown in this Python implementation. | def nonoblocks(blocks, cells):
if not blocks or blocks[0] == 0:
yield [(0, 0)]
else:
assert sum(blocks) + len(blocks)-1 <= cells, \
'Those blocks will not fit in those cells'
blength, brest = blocks[0], blocks[1:]
minspace4rest = sum(1+b for b in brest)
... |
fun printBlock(data: String, len: Int) {
val a = data.toCharArray()
val sumChars = a.map { it.toInt() - 48 }.sum()
println("\nblocks ${a.asList()}, cells $len")
if (len - sumChars <= 0) {
println("No solution")
return
}
val prep = a.map { "1".repeat(it.toInt() - 48) }
for (... |
Maintain the same structure and functionality when rewriting this code in Scala. | def nonoblocks(blocks, cells):
if not blocks or blocks[0] == 0:
yield [(0, 0)]
else:
assert sum(blocks) + len(blocks)-1 <= cells, \
'Those blocks will not fit in those cells'
blength, brest = blocks[0], blocks[1:]
minspace4rest = sum(1+b for b in brest)
... |
fun printBlock(data: String, len: Int) {
val a = data.toCharArray()
val sumChars = a.map { it.toInt() - 48 }.sum()
println("\nblocks ${a.asList()}, cells $len")
if (len - sumChars <= 0) {
println("No solution")
return
}
val prep = a.map { "1".repeat(it.toInt() - 48) }
for (... |
Convert this Python snippet to Scala and keep its semantics consistent. |
import inflect
import time
before = time.perf_counter()
p = inflect.engine()
print(' ')
print('eban numbers up to and including 1000:')
print(' ')
count = 0
for i in range(1,1001):
if not 'e' in p.number_to_words(i):
print(str(i)+' ',end='')
count += 1
print(' ')
print(' ')
print... |
typealias Range = Triple<Int, Int, Boolean>
fun main() {
val rgs = listOf<Range>(
Range(2, 1000, true),
Range(1000, 4000, true),
Range(2, 10_000, false),
Range(2, 100_000, false),
Range(2, 1_000_000, false),
Range(2, 10_000_000, false),
Range(2, 100_000_000... |
Ensure the translated Scala code behaves exactly like the original Python snippet. |
import inflect
import time
before = time.perf_counter()
p = inflect.engine()
print(' ')
print('eban numbers up to and including 1000:')
print(' ')
count = 0
for i in range(1,1001):
if not 'e' in p.number_to_words(i):
print(str(i)+' ',end='')
count += 1
print(' ')
print(' ')
print... |
typealias Range = Triple<Int, Int, Boolean>
fun main() {
val rgs = listOf<Range>(
Range(2, 1000, true),
Range(1000, 4000, true),
Range(2, 10_000, false),
Range(2, 100_000, false),
Range(2, 1_000_000, false),
Range(2, 10_000_000, false),
Range(2, 100_000_000... |
Please provide an equivalent version of this Python code in Scala. | def monkey_coconuts(sailors=5):
"Parameterised the number of sailors using an inner loop including the last mornings case"
nuts = sailors
while True:
n0, wakes = nuts, []
for sailor in range(sailors + 1):
portion, remainder = divmod(n0, sailors)
wakes.append((n0, ... |
fun main(args: Array<String>) {
var coconuts = 11
outer@ for (ns in 2..9) {
val hidden = IntArray(ns)
coconuts = (coconuts / ns) * ns + 1
while (true) {
var nc = coconuts
for (s in 1..ns) {
if (nc % ns == 1) {
hidd... |
Ensure the translated Scala code behaves exactly like the original Python snippet. | def monkey_coconuts(sailors=5):
"Parameterised the number of sailors using an inner loop including the last mornings case"
nuts = sailors
while True:
n0, wakes = nuts, []
for sailor in range(sailors + 1):
portion, remainder = divmod(n0, sailors)
wakes.append((n0, ... |
fun main(args: Array<String>) {
var coconuts = 11
outer@ for (ns in 2..9) {
val hidden = IntArray(ns)
coconuts = (coconuts / ns) * ns + 1
while (true) {
var nc = coconuts
for (s in 1..ns) {
if (nc % ns == 1) {
hidd... |
Preserve the algorithm and functionality while converting the code from Python to Scala. |
from PIL import Image
im = Image.open("boxes_1.jpg")
im.save("boxes_1v2.ppm")
|
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.io.PushbackInputStream
import java.io.File
import javax.imageio.ImageIO
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color)... |
Change the following Python code into Scala without altering its purpose. | import time, calendar, sched, winsound
duration = 750
freq = 1280
bellchar = "\u2407"
watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')
def gap(n=1):
time.sleep(n * duration / 1000)
off = gap
def on(n=1):
winsound.Beep(freq, n * duration)
def bong():
on(); of... |
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.TimeZone
class NauticalBell: Thread() {
override fun run() {
val sdf = SimpleDateFormat("HH:mm:ss")
sdf.timeZone = TimeZone.getTimeZone("UTC")
var numBells = 0
var time = System.currentTimeMillis()
... |
Keep all operations the same but rewrite the snippet in Scala. | import time, calendar, sched, winsound
duration = 750
freq = 1280
bellchar = "\u2407"
watches = 'Middle,Morning,Forenoon,Afternoon,First/Last dog,First'.split(',')
def gap(n=1):
time.sleep(n * duration / 1000)
off = gap
def on(n=1):
winsound.Beep(freq, n * duration)
def bong():
on(); of... |
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.TimeZone
class NauticalBell: Thread() {
override fun run() {
val sdf = SimpleDateFormat("HH:mm:ss")
sdf.timeZone = TimeZone.getTimeZone("UTC")
var numBells = 0
var time = System.currentTimeMillis()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.