Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Port the following code from Python to Scala with equivalent syntax and logic. | import win32api
import win32con
import pywintypes
devmode=pywintypes.DEVMODEType()
devmode.PelsWidth=640
devmode.PelsHeight=480
devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT
win32api.ChangeDisplaySettings(devmode,0)
|
import java.util.Scanner
fun runSystemCommand(command: String) {
val proc = Runtime.getRuntime().exec(command)
Scanner(proc.inputStream).use {
while (it.hasNextLine()) println(it.nextLine())
}
proc.waitFor()
println()
}
fun main(args: Array<String>) {
runSystemCommand("xrandr -q... |
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. | import curses
from random import randint
stdscr = curses.initscr()
for rows in range(10):
line = ''.join([chr(randint(41, 90)) for i in range(10)])
stdscr.addstr(line + '\n')
icol = 3 - 1
irow = 6 - 1
ch = stdscr.instr(irow, icol, 1).decode(encoding="utf-8")
stdscr.move(irow, icol + 10)
stdscr.addstr('Ch... |
import kotlinx.cinterop.*
import win32.*
fun main(args: Array<String>) {
for (i in 0 until (80 * 25)) print("A")
println()
memScoped {
val conOut = GetStdHandle(-11)
val info = alloc<CONSOLE_SCREEN_BUFFER_INFO>()
val pos = alloc<COORD>()
GetConsoleScreenBufferInfo... |
Can you help me rewrite this code in Scala instead of Python, keeping it the same logically? | def legendre(a, p):
return pow(a, (p - 1) // 2, p)
def tonelli(n, p):
assert legendre(n, p) == 1, "not a square (mod p)"
q = p - 1
s = 0
while q % 2 == 0:
q //= 2
s += 1
if s == 1:
return pow(n, (p + 1) // 4, p)
for z in range(2, p):
if p - 1 == legendre(z, p... |
import java.math.BigInteger
data class Solution(val root1: BigInteger, val root2: BigInteger, val exists: Boolean)
val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE
val bigTwo = BigInteger.valueOf(2L)
val bigFour = BigInteger.valueOf(4L)
val bigTen = BigInteger.TEN
fun ts(n: Long, p: Long) = ts(BigInte... |
Write a version of this Python function in Scala with identical behavior. | def legendre(a, p):
return pow(a, (p - 1) // 2, p)
def tonelli(n, p):
assert legendre(n, p) == 1, "not a square (mod p)"
q = p - 1
s = 0
while q % 2 == 0:
q //= 2
s += 1
if s == 1:
return pow(n, (p + 1) // 4, p)
for z in range(2, p):
if p - 1 == legendre(z, p... |
import java.math.BigInteger
data class Solution(val root1: BigInteger, val root2: BigInteger, val exists: Boolean)
val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE
val bigTwo = BigInteger.valueOf(2L)
val bigFour = BigInteger.valueOf(4L)
val bigTen = BigInteger.TEN
fun ts(n: Long, p: Long) = ts(BigInte... |
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. | from collections import deque
some_list = deque(["a", "b", "c"])
print(some_list)
some_list.appendleft("Z")
print(some_list)
for value in reversed(some_list):
print(value)
|
class LinkedList<E> {
class Node<E>(var data: E, var prev: Node<E>? = null, var next: Node<E>? = null) {
override fun toString(): String {
val sb = StringBuilder(this.data.toString())
var node = this.next
while (node != null) {
sb.append(" -> ", node.dat... |
Write the same code in Scala as shown below in Python. | from itertools import product
while True:
bexp = input('\nBoolean expression: ')
bexp = bexp.strip()
if not bexp:
print("\nThank you")
break
code = compile(bexp, '<string>', 'eval')
names = code.co_names
print('\n' + ' '.join(names), ':', bexp)
for values in product(range(2)... |
import java.util.Stack
class Variable(val name: Char, var value: Boolean = false)
lateinit var expr: String
var variables = mutableListOf<Variable>()
fun Char.isOperator() = this in "&|!^"
fun Char.isVariable() = this in variables.map { it.name }
fun evalExpression(): Boolean {
val stack = Stack<Boolean>()
... |
Generate a Scala translation of this Python snippet without changing its computational steps. | from itertools import product
while True:
bexp = input('\nBoolean expression: ')
bexp = bexp.strip()
if not bexp:
print("\nThank you")
break
code = compile(bexp, '<string>', 'eval')
names = code.co_names
print('\n' + ' '.join(names), ':', bexp)
for values in product(range(2)... |
import java.util.Stack
class Variable(val name: Char, var value: Boolean = false)
lateinit var expr: String
var variables = mutableListOf<Variable>()
fun Char.isOperator() = this in "&|!^"
fun Char.isVariable() = this in variables.map { it.name }
fun evalExpression(): Boolean {
val stack = Stack<Boolean>()
... |
Keep all operations the same but rewrite the snippet in Scala. | class Setr():
def __init__(self, lo, hi, includelo=True, includehi=False):
self.eqn = "(%i<%sX<%s%i)" % (lo,
'=' if includelo else '',
'=' if includehi else '',
hi)
def __contains__(self, X... |
typealias RealPredicate = (Double) -> Boolean
enum class RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN }
class RealSet(val low: Double, val high: Double, val predicate: RealPredicate) {
constructor (start: Double, end: Double, rangeType: RangeType): this(start, end,
when (rangeType) {
... |
Transform the following Python implementation into Scala, maintaining the same output and logic. | class Setr():
def __init__(self, lo, hi, includelo=True, includehi=False):
self.eqn = "(%i<%sX<%s%i)" % (lo,
'=' if includelo else '',
'=' if includehi else '',
hi)
def __contains__(self, X... |
typealias RealPredicate = (Double) -> Boolean
enum class RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN }
class RealSet(val low: Double, val high: Double, val predicate: RealPredicate) {
constructor (start: Double, end: Double, rangeType: RangeType): this(start, end,
when (rangeType) {
... |
Translate the given Python code snippet into Scala without altering its behavior. | from collections import defaultdict
states = ["Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut", "Delaware", "Florida",
"Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas",
"Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts",
"Michigan", "Minnesota", "Missi... |
fun solve(states: List<String>) {
val dict = mutableMapOf<String, String>()
for (state in states) {
val key = state.toLowerCase().replace(" ", "")
if (dict[key] == null) dict.put(key, state)
}
val keys = dict.keys.toList()
val solutions = mutableListOf<String>()
val duplicates ... |
Rewrite the snippet below in Scala so it works the same as the original Python code. | from itertools import islice, count
def superd(d):
if d != int(d) or not 2 <= d <= 9:
raise ValueError("argument must be integer from 2 to 9 inclusive")
tofind = str(d) * d
for n in count(2):
if tofind in str(d * n ** d):
yield n
if __name__ == '__main__':
for d in range(2,... | import java.math.BigInteger
fun superD(d: Int, max: Int) {
val start = System.currentTimeMillis()
var test = ""
for (i in 0 until d) {
test += d
}
var n = 0
var i = 0
println("First $max super-$d numbers:")
while (n < max) {
i++
val value: Any = BigInteger.value... |
Produce a language-to-language conversion: from Python to Scala, same semantics. | from itertools import islice, count
def superd(d):
if d != int(d) or not 2 <= d <= 9:
raise ValueError("argument must be integer from 2 to 9 inclusive")
tofind = str(d) * d
for n in count(2):
if tofind in str(d * n ** d):
yield n
if __name__ == '__main__':
for d in range(2,... | import java.math.BigInteger
fun superD(d: Int, max: Int) {
val start = System.currentTimeMillis()
var test = ""
for (i in 0 until d) {
test += d
}
var n = 0
var i = 0
println("First $max super-$d numbers:")
while (n < max) {
i++
val value: Any = BigInteger.value... |
Rewrite the snippet below in Scala so it works the same as the original Python code. |
from __future__ import annotations
from typing import Any
from typing import Callable
from typing import Generic
from typing import Optional
from typing import TypeVar
from typing import Union
T = TypeVar("T")
class Maybe(Generic[T]):
def __init__(self, value: Union[Optional[T], Maybe[T]] = None):
if ... |
import java.util.Optional
fun getOptionalInt(i: Int) = Optional.of(2 * i)
fun getOptionalString(i: Int) = Optional.of("A".repeat(i))
fun getOptionalString2(i: Int) =
Optional.ofNullable(if (i > 0) "A".repeat(i) else null)
fun main(args: Array<String>) {
println(getOptionalInt(5).flatMap(::getOption... |
Translate this program into Scala but keep the logic exactly as in Python. |
from __future__ import annotations
from itertools import chain
from typing import Any
from typing import Callable
from typing import Iterable
from typing import List
from typing import TypeVar
T = TypeVar("T")
class MList(List[T]):
@classmethod
def unit(cls, value: Iterable[T]) -> MList[T]:
return... |
class MList<T : Any> private constructor(val value: List<T>) {
fun <U : Any> bind(f: (List<T>) -> MList<U>) = f(this.value)
companion object {
fun <T : Any> unit(lt: List<T>) = MList<T>(lt)
}
}
fun doubler(li: List<Int>) = MList.unit(li.map { 2 * it } )
fun letters(li: List<Int>) = MList.unit(l... |
Write the same code in Scala as shown below in Python. | from collections import defaultdict
import urllib.request
CH2NUM = {ch: str(num) for num, chars in enumerate('abc def ghi jkl mno pqrs tuv wxyz'.split(), 2) for ch in chars}
URL = 'http://www.puzzlers.org/pub/wordlists/unixdict.txt'
def getwords(url):
return urllib.request.urlopen(url).read().decode("utf-8").lower(... |
import java.io.File
val wordList = "unixdict.txt"
val url = "http:
const val DIGITS = "22233344455566677778889999"
val map = mutableMapOf<String, MutableList<String>>()
fun processList() {
var countValid = 0
val f = File(wordList)
val sb = StringBuilder()
f.forEachLine { word->
var valid ... |
Port the provided Python code into Scala while preserving the original functionality. | import inspect
class Super(object):
def __init__(self, name):
self.name = name
def __str__(self):
return "Super(%s)" % (self.name,)
def doSup(self):
return 'did super stuff'
@classmethod
def cls(cls):
return 'cls method (in sup)'
@classmethod
def supCls(cls):
return 'Supe... |
import kotlin.reflect.full.functions
open class MySuperClass {
fun mySuperClassMethod(){}
}
open class MyClass : MySuperClass() {
fun myPublicMethod(){}
internal fun myInternalMethod(){}
protected fun myProtectedMethod(){}
private fun myPrivateMethod(){}
}
fun main(args: Array<String>) {
... |
Change the following Python code into Scala without altering its purpose. | class Example(object):
def foo(self, x):
return 42 + x
name = "foo"
getattr(Example(), name)(5)
|
class C {
fun foo() {
println("foo called")
}
}
fun main(args: Array<String>) {
val c = C()
val f = "c.foo"
js(f)()
}
|
Keep all operations the same but rewrite the snippet in Scala. | names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split()))
print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )
|
class President(val name: String) {
var age: Int = 0
set(value) {
if (value in 0..125) field = value
else throw IllegalArgumentException("$name's age must be between 0 and 125")
}
}
fun main(args: Array<String>) {
val pres = President("Donald")
pres.age = 69
... |
Please provide an equivalent version of this Python code in Scala. | >>> 3
3
>>> _*_, _**0.5
(9, 1.7320508075688772)
>>>
|
fun main(args: Array<String>) {
3.let {
println(it)
println(it * it)
println(Math.sqrt(it.toDouble()))
}
}
|
Port the provided Python code into Scala while preserving the original functionality. | >>> 3
3
>>> _*_, _**0.5
(9, 1.7320508075688772)
>>>
|
fun main(args: Array<String>) {
3.let {
println(it)
println(it * it)
println(Math.sqrt(it.toDouble()))
}
}
|
Write a version of this Python function in Scala with identical behavior. | import pyprimes
def primorial_prime(_pmax=500):
isprime = pyprimes.isprime
n, primo = 0, 1
for prime in pyprimes.nprimes(_pmax):
n, primo = n+1, primo * prime
if isprime(primo-1) or isprime(primo+1):
yield n
if __name__ == '__main__':
pyprimes.warn_probably = F... |
import java.math.BigInteger
const val LIMIT = 20
fun isPrime(n: Int): Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d : Int = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
... |
Write a version of this Python function in Scala with identical behavior. | from __future__ import print_function
from scipy.misc import factorial as fact
from scipy.misc import comb
def perm(N, k, exact=0):
return comb(N, k, exact) * fact(k, exact)
exact=True
print('Sample Perms 1..12')
for N in range(1, 13):
k = max(N-2, 1)
print('%iP%i =' % (N, k), perm(N, k, exact), end=', '... |
import java.math.BigInteger
fun perm(n: Int, k: Int): BigInteger {
require(n > 0 && k >= 0)
return (n - k + 1 .. n).fold(BigInteger.ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) }
}
fun comb(n: Int, k: Int): BigInteger {
require(n > 0 && k >= 0)
val fact = (2..k).fold(BigInteger.ONE) { acc, ... |
Please provide an equivalent version of this Python code in Scala. | from decimal import *
D = Decimal
getcontext().prec = 100
a = n = D(1)
g, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5)
for i in range(18):
x = [(a + g) * half, (a * g).sqrt()]
var = x[0] - a
z -= var * var * n
n += n
a, g = x
print(a * a / z)
| import java.math.BigDecimal
import java.math.MathContext
val con1024 = MathContext(1024)
val bigTwo = BigDecimal(2)
val bigFour = bigTwo * bigTwo
fun bigSqrt(bd: BigDecimal, con: MathContext): BigDecimal {
var x0 = BigDecimal.ZERO
var x1 = BigDecimal.valueOf(Math.sqrt(bd.toDouble()))
while (x0 != x1) {
... |
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. | from decimal import *
D = Decimal
getcontext().prec = 100
a = n = D(1)
g, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5)
for i in range(18):
x = [(a + g) * half, (a * g).sqrt()]
var = x[0] - a
z -= var * var * n
n += n
a, g = x
print(a * a / z)
| import java.math.BigDecimal
import java.math.MathContext
val con1024 = MathContext(1024)
val bigTwo = BigDecimal(2)
val bigFour = bigTwo * bigTwo
fun bigSqrt(bd: BigDecimal, con: MathContext): BigDecimal {
var x0 = BigDecimal.ZERO
var x1 = BigDecimal.valueOf(Math.sqrt(bd.toDouble()))
while (x0 != x1) {
... |
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. | from Xlib import X, display
class Window:
def __init__(self, display, msg):
self.display = display
self.msg = msg
self.screen = self.display.screen()
self.window = self.screen.root.create_window(
10, 10, 100, 100, 1,
self.screen.root_depth,
... |
import kotlinx.cinterop.*
import Xlib.*
fun main(args: Array<String>) {
val msg = "Hello, World!"
val d = XOpenDisplay(null)
if (d == null) {
println("Cannot open display")
return
}
val s = XDefaultScreen(d)
val w = XCreateSimpleWindow(d, XRootWindow(d, s), 10, 10, 160, 160, ... |
Produce a language-to-language conversion: from Python to Scala, same semantics. | def sieve(limit):
primes = []
c = [False] * (limit + 1)
p = 3
while True:
p2 = p * p
if p2 > limit: break
for i in range(p2, limit, 2 * p): c[i] = True
while True:
p += 2
if not c[p]: break
for i in range(3, limit, 2):
if not c[i... |
fun sieve(limit: Int): List<Int> {
val primes = mutableListOf<Int>()
val c = BooleanArray(limit + 1)
var p = 3
var p2 = p * p
while (p2 <= limit) {
for (i in p2..limit step 2 * p) c[i] = true
do {
p += 2
} while (c[p])
p2 = p * p
}
for (i... |
Please provide an equivalent version of this Python code in Scala. | from pyprimes import nprimes
from functools import reduce
primelist = list(nprimes(1000001))
def primorial(n):
return reduce(int.__mul__, primelist[:n], 1)
if __name__ == '__main__':
print('First ten primorals:', [primorial(n) for n in range(10)])
for e in range(7):
n = 10**e
print('... |
import java.math.BigInteger
const val LIMIT = 1000000
fun isPrime(n: Int): Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d : Int = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return fals... |
Write the same code in Scala as shown below in Python. | from fractions import Fraction
from math import ceil
class Fr(Fraction):
def __repr__(self):
return '%s/%s' % (self.numerator, self.denominator)
def ef(fr):
ans = []
if fr >= 1:
if fr.denominator == 1:
return [[int(fr)], Fr(0, 1)]
intfr = int(fr)
ans, fr = [[int... |
import java.math.BigInteger
import java.math.BigDecimal
import java.math.MathContext
val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE
val bdZero = BigDecimal.ZERO
val context = MathContext.UNLIMITED
fun gcd(a: BigInteger, b: BigInteger): BigInteger
= if (b == bigZero) a else gcd(b, a % b)
class Frac... |
Maintain the same structure and functionality when rewriting this code in Scala. | from fractions import Fraction
from math import ceil
class Fr(Fraction):
def __repr__(self):
return '%s/%s' % (self.numerator, self.denominator)
def ef(fr):
ans = []
if fr >= 1:
if fr.denominator == 1:
return [[int(fr)], Fr(0, 1)]
intfr = int(fr)
ans, fr = [[int... |
import java.math.BigInteger
import java.math.BigDecimal
import java.math.MathContext
val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE
val bdZero = BigDecimal.ZERO
val context = MathContext.UNLIMITED
fun gcd(a: BigInteger, b: BigInteger): BigInteger
= if (b == bigZero) a else gcd(b, a % b)
class Frac... |
Port the provided Python code into Scala while preserving the original functionality. | from numpy import *
def Legendre(n,x):
x=array(x)
if (n==0):
return x*0+1.0
elif (n==1):
return x
else:
return ((2.0*n-1.0)*x*Legendre(n-1,x)-(n-1)*Legendre(n-2,x))/n
def DLegendre(n,x):
x=array(x)
if (n==0):
return x*0
elif (n==1):
return x*0+1.0
else:
return (n/(x**2-1.0))*(x*Legendre(n,x)... | import java.lang.Math.*
class Legendre(val N: Int) {
fun evaluate(n: Int, x: Double) = (n downTo 1).fold(c[n][n]) { s, i -> s * x + c[n][i - 1] }
fun diff(n: Int, x: Double) = n * (x * evaluate(n, x) - evaluate(n - 1, x)) / (x * x - 1)
fun integrate(f: (Double) -> Double, a: Double, b: Double): Double {
... |
Produce a language-to-language conversion: from Python to Scala, same semantics. | from random import seed, random
from time import time
from operator import itemgetter
from collections import namedtuple
from math import sqrt
from copy import deepcopy
def sqd(p1, p2):
return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2))
class KdNode(object):
__slots__ = ("dom_elt", "split", "left", "right... |
import java.util.Random
typealias Point = DoubleArray
fun Point.sqd(p: Point) = this.zip(p) { a, b -> (a - b) * (a - b) }.sum()
class HyperRect (val min: Point, val max: Point) {
fun copy() = HyperRect(min.copyOf(), max.copyOf())
}
data class NearestNeighbor(val nearest: Point?, val distSqd: Double, val nodes... |
Translate the given Python code snippet into Scala without altering its behavior. | from random import seed, random
from time import time
from operator import itemgetter
from collections import namedtuple
from math import sqrt
from copy import deepcopy
def sqd(p1, p2):
return sum((c1 - c2) ** 2 for c1, c2 in zip(p1, p2))
class KdNode(object):
__slots__ = ("dom_elt", "split", "left", "right... |
import java.util.Random
typealias Point = DoubleArray
fun Point.sqd(p: Point) = this.zip(p) { a, b -> (a - b) * (a - b) }.sum()
class HyperRect (val min: Point, val max: Point) {
fun copy() = HyperRect(min.copyOf(), max.copyOf())
}
data class NearestNeighbor(val nearest: Point?, val distSqd: Double, val nodes... |
Can you help me rewrite this code in Scala instead of Python, keeping it the same logically? | from PIL import Image
if __name__=="__main__":
im = Image.open("frog.png")
im2 = im.quantize(16)
im2.show()
|
import java.io.BufferedReader
import java.io.InputStreamReader
fun main(args: Array<String>) {
val pb = ProcessBuilder(
"convert",
"Quantum_frog.png",
"-dither",
"None",
"-colors",
"16",
"Quantum_frog_16.png"
)
pb.directory(null)
val proc =... |
Write a version of this Python function in Scala with identical behavior. | def cut_it(h, w):
dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))
if h % 2: h, w = w, h
if h % 2: return 0
if w == 1: return 1
count = 0
next = [w + 1, -w - 1, -1, 1]
blen = (h + 1) * (w + 1) - 1
grid = [False] * (blen + 1)
def walk(y, x, count):
if not y or y == h or not x or x ... |
object RectangleCutter {
private var w: Int = 0
private var h: Int = 0
private var len: Int = 0
private var cnt: Long = 0
private lateinit var grid: ByteArray
private val next = IntArray(4)
private val dir = arrayOf(
intArrayOf(0, -1),
intArrayOf(-1, 0),
intArrayOf... |
Please provide an equivalent version of this Python code in Scala. | def cut_it(h, w):
dirs = ((1, 0), (-1, 0), (0, -1), (0, 1))
if h % 2: h, w = w, h
if h % 2: return 0
if w == 1: return 1
count = 0
next = [w + 1, -w - 1, -1, 1]
blen = (h + 1) * (w + 1) - 1
grid = [False] * (blen + 1)
def walk(y, x, count):
if not y or y == h or not x or x ... |
object RectangleCutter {
private var w: Int = 0
private var h: Int = 0
private var len: Int = 0
private var cnt: Long = 0
private lateinit var grid: ByteArray
private val next = IntArray(4)
private val dir = arrayOf(
intArrayOf(0, -1),
intArrayOf(-1, 0),
intArrayOf... |
Generate a Scala translation of this Python snippet without changing its computational steps. | import datetime
import math
primes = [ 3, 5 ]
cutOff = 200
bigUn = 100_000
chunks = 50
little = bigUn / chunks
tn = " cuban prime"
print ("The first {:,}{}s:".format(cutOff, tn))
c = 0
showEach = True
u = 0
v = 1
st = datetime.datetime.now()
for i in range(1, int(math.pow(2,20))):
found = False
u += 6
v += u
... | import kotlin.math.ceil
import kotlin.math.sqrt
fun main() {
val primes = mutableListOf(3L, 5L)
val cutOff = 200
val bigUn = 100_000
val chunks = 50
val little = bigUn / chunks
println("The first $cutOff cuban primes:")
var showEach = true
var c = 0
var u = 0L
var v = 1L
va... |
Maintain the same structure and functionality when rewriting this code in Scala. | from __future__ import division
size(300, 260)
background(255)
x = floor(random(width))
y = floor(random(height))
for _ in range(30000):
v = floor(random(3))
if v == 0:
x = x / 2
y = y / 2
colour = color(0, 255, 0)
elif v == 1:
x = width / 2 + (width / 2 - x) / 2
... |
import java.awt.*
import java.util.Stack
import java.util.Random
import javax.swing.JPanel
import javax.swing.JFrame
import javax.swing.Timer
import javax.swing.SwingUtilities
class ChaosGame : JPanel() {
class ColoredPoint(x: Int, y: Int, val colorIndex: Int) : Point(x, y)
val stack = Stack<ColoredPoint>(... |
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. | from __future__ import division
size(300, 260)
background(255)
x = floor(random(width))
y = floor(random(height))
for _ in range(30000):
v = floor(random(3))
if v == 0:
x = x / 2
y = y / 2
colour = color(0, 255, 0)
elif v == 1:
x = width / 2 + (width / 2 - x) / 2
... |
import java.awt.*
import java.util.Stack
import java.util.Random
import javax.swing.JPanel
import javax.swing.JFrame
import javax.swing.Timer
import javax.swing.SwingUtilities
class ChaosGame : JPanel() {
class ColoredPoint(x: Int, y: Int, val colorIndex: Int) : Point(x, y)
val stack = Stack<ColoredPoint>(... |
Translate this program into Scala but keep the logic exactly as in Python. | from itertools import product, combinations, izip
scoring = [0, 1, 3]
histo = [[0] * 10 for _ in xrange(4)]
for results in product(range(3), repeat=6):
s = [0] * 4
for r, g in izip(results, combinations(range(4), 2)):
s[g[0]] += scoring[r]
s[g[1]] += scoring[2 - r]
for h, v in izip(histo,... |
val games = arrayOf("12", "13", "14", "23", "24", "34")
var results = "000000"
fun nextResult(): Boolean {
if (results == "222222") return false
val res = results.toInt(3) + 1
results = res.toString(3).padStart(6, '0')
return true
}
fun main(args: Array<String>) {
val points = Array(4) { IntArra... |
Change the programming language of this snippet from Python to Scala without modifying what it does. | from collections import namedtuple
from pprint import pprint as pp
OpInfo = namedtuple('OpInfo', 'prec assoc')
L, R = 'Left Right'.split()
ops = {
'^': OpInfo(prec=4, assoc=R),
'*': OpInfo(prec=3, assoc=L),
'/': OpInfo(prec=3, assoc=L),
'+': OpInfo(prec=2, assoc=L),
'-': OpInfo(prec=2, assoc=L),
'(': OpInfo(pre... |
import java.util.Stack
const val OPS = "-+/*^"
fun infixToPostfix(infix: String): String {
val sb = StringBuilder()
val s = Stack<Int>()
val rx = Regex("""\s""")
for (token in infix.split(rx)) {
if (token.isEmpty()) continue
val c = token[0]
val idx = OPS.indexOf(c)
... |
Preserve the algorithm and functionality while converting the code from Python to Scala. | import math
def perlin_noise(x, y, z):
X = math.floor(x) & 255
Y = math.floor(y) & 255
Z = math.floor(z) & 255
x -= math.floor(x)
y -= math.floor(y)
z -= math.floor(z)
u = fade(x) ... |
object Perlin {
private val permutation = intArrayOf(
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,
140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,
247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, ... |
Convert this Python block to Scala, preserving its control flow and logic. |
import os
from math import pi, sin
au_header = bytearray(
[46, 115, 110, 100,
0, 0, 0, 24,
255, 255, 255, 255,
0, 0, 0, 3,
0, 0, 172, 68,
0, 0, 0, 1])
def f(x, freq):
"Compute sine wave as 16-bi... |
import javax.sound.sampled.AudioFormat
import javax.sound.sampled.AudioSystem
import kotlin.math.sin
import kotlin.math.PI
fun sineWave(frequency: Int, seconds: Int, sampleRate: Int): ByteArray {
val samples = seconds * sampleRate
val result = ByteArray(samples)
val interval = sampleRate.toDouble() / fre... |
Port the provided Python code into Scala while preserving the original functionality. | from itertools import izip
def gen_row(w, s):
def gen_seg(o, sp):
if not o:
return [[2] * sp]
return [[2] * x + o[0] + tail
for x in xrange(1, sp - len(o) + 2)
for tail in gen_seg(o[1:], sp - x)]
return [x[1:] for x in gen_seg([[1] * i for i in ... |
import java.util.BitSet
typealias BitSets = List<MutableList<BitSet>>
val rx = Regex("""\s""")
fun newPuzzle(data: List<String>) {
val rowData = data[0].split(rx)
val colData = data[1].split(rx)
val rows = getCandidates(rowData, colData.size)
val cols = getCandidates(colData, rowData.size)
do ... |
Produce a functionally identical Scala code for the snippet given in Python. | from itertools import izip
def gen_row(w, s):
def gen_seg(o, sp):
if not o:
return [[2] * sp]
return [[2] * x + o[0] + tail
for x in xrange(1, sp - len(o) + 2)
for tail in gen_seg(o[1:], sp - x)]
return [x[1:] for x in gen_seg([[1] * i for i in ... |
import java.util.BitSet
typealias BitSets = List<MutableList<BitSet>>
val rx = Regex("""\s""")
fun newPuzzle(data: List<String>) {
val rowData = data[0].split(rx)
val colData = data[1].split(rx)
val rows = getCandidates(rowData, colData.size)
val cols = getCandidates(colData, rowData.size)
do ... |
Generate an equivalent Scala version of this Python code. | from __future__ import print_function
def add_reverse(num, max_iter=1000):
i, nums = 0, {num}
while True:
i, num = i+1, num + reverse_int(num)
nums.add(num)
if reverse_int(num) == num or i >= max_iter:
break
return nums
def reverse_int(num):
return int(str(num)... |
import java.math.BigInteger
const val ITERATIONS = 500
const val LIMIT = 10000
val bigLimit = BigInteger.valueOf(LIMIT.toLong())
val lychrelSieve = IntArray(LIMIT + 1)
val seedLychrels = mutableListOf<Int>()
val relatedLychrels = mutableSetOf<BigInteger>()
fun isPalindrome(bi: BigInteger): Boolean {
... |
Convert this Python block to Scala, preserving its control flow and logic. | from __future__ import print_function
def add_reverse(num, max_iter=1000):
i, nums = 0, {num}
while True:
i, num = i+1, num + reverse_int(num)
nums.add(num)
if reverse_int(num) == num or i >= max_iter:
break
return nums
def reverse_int(num):
return int(str(num)... |
import java.math.BigInteger
const val ITERATIONS = 500
const val LIMIT = 10000
val bigLimit = BigInteger.valueOf(LIMIT.toLong())
val lychrelSieve = IntArray(LIMIT + 1)
val seedLychrels = mutableListOf<Int>()
val relatedLychrels = mutableSetOf<BigInteger>()
fun isPalindrome(bi: BigInteger): Boolean {
... |
Change the programming language of this snippet from Python to Scala without modifying what it does. | import re
from fractions import Fraction
from pprint import pprint as pp
equationtext =
def parse_eqn(equationtext=equationtext):
eqn_re = re.compile(r)
found = eqn_re.findall(equationtext)
machins, part = [], []
for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):
if lhs and ... |
import java.math.BigInteger
val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE
class BigRational : Comparable<BigRational> {
val num: BigInteger
val denom: BigInteger
constructor(n: BigInteger, d: BigInteger) {
require(d != bigZero)
var nn = n
var dd = d
if (nn ... |
Can you help me rewrite this code in Scala instead of Python, keeping it the same logically? | import re
from fractions import Fraction
from pprint import pprint as pp
equationtext =
def parse_eqn(equationtext=equationtext):
eqn_re = re.compile(r)
found = eqn_re.findall(equationtext)
machins, part = [], []
for lhs, sign, mult, numer, denom in eqn_re.findall(equationtext):
if lhs and ... |
import java.math.BigInteger
val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE
class BigRational : Comparable<BigRational> {
val num: BigInteger
val denom: BigInteger
constructor(n: BigInteger, d: BigInteger) {
require(d != bigZero)
var nn = n
var dd = d
if (nn ... |
Ensure the translated Scala code behaves exactly like the original Python snippet. | from spell_integer import spell_integer, SMALL, TENS, HUGE
def int_from_words(num):
words = num.replace(',','').replace(' and ', ' ').replace('-', ' ').split()
if words[0] == 'minus':
negmult = -1
words.pop(0)
else:
negmult = 1
small, total = 0, 0
for word in words:
... |
val names = mapOf<String, Long>(
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9,
"ten" to 10,
"eleven" to 11,
"twelve" to 12,
"thirteen" to 13,
"fourteen" to 14,
"fifteen" to 15,
"sixte... |
Ensure the translated Scala code behaves exactly like the original Python snippet. | import random
import collections
INT_MASK = 0xFFFFFFFF
class IsaacRandom(random.Random):
def seed(self, seed=None):
def mix():
init_state[0] ^= ((init_state[1]<<11)&INT_MASK); init_state[3] += init_state[0]; init_state[3] &= INT_MASK; init_state[1] += init_state[2]; init_... |
val randrsl = IntArray(256)
var randcnt = 0
val mm = IntArray(256)
var aa = 0
var bb = 0
var cc = 0
const val GOLDEN_RATIO = 0x9e3779b9.toInt()
fun isaac() {
cc++
bb += cc
for (i in 0..255) {
val x = mm[i]
when (i % 4) {
0 -> aa = aa xor (aa shl 13)
... |
Rewrite the snippet below in Scala so it works the same as the original Python code. | import random
import collections
INT_MASK = 0xFFFFFFFF
class IsaacRandom(random.Random):
def seed(self, seed=None):
def mix():
init_state[0] ^= ((init_state[1]<<11)&INT_MASK); init_state[3] += init_state[0]; init_state[3] &= INT_MASK; init_state[1] += init_state[2]; init_... |
val randrsl = IntArray(256)
var randcnt = 0
val mm = IntArray(256)
var aa = 0
var bb = 0
var cc = 0
const val GOLDEN_RATIO = 0x9e3779b9.toInt()
fun isaac() {
cc++
bb += cc
for (i in 0..255) {
val x = mm[i]
when (i % 4) {
0 -> aa = aa xor (aa shl 13)
... |
Write the same algorithm in Scala as shown in this Python implementation. | from math import factorial as fact
from random import randrange
from textwrap import wrap
def identity_perm(n):
return list(range(n))
def unranker1(n, r, pi):
while n > 0:
n1, (rdivn, rmodn) = n-1, divmod(r, n)
pi[n1], pi[rmodn] = pi[rmodn], pi[n1]
n = n1
r = rdivn
return ... |
import java.util.Random
fun IntArray.swap(i: Int, j: Int) {
val temp = this[i]
this[i] = this[j]
this[j] = temp
}
tailrec fun mrUnrank1(rank: Int, n: Int, vec: IntArray) {
if (n < 1) return
val q = rank / n
val r = rank % n
vec.swap(r, n - 1)
mrUnrank1(q, n - 1, vec)
}
fun mrRank1(... |
Please provide an equivalent version of this Python code in Scala. | from math import factorial as fact
from random import randrange
from textwrap import wrap
def identity_perm(n):
return list(range(n))
def unranker1(n, r, pi):
while n > 0:
n1, (rdivn, rmodn) = n-1, divmod(r, n)
pi[n1], pi[rmodn] = pi[rmodn], pi[n1]
n = n1
r = rdivn
return ... |
import java.util.Random
fun IntArray.swap(i: Int, j: Int) {
val temp = this[i]
this[i] = this[j]
this[j] = temp
}
tailrec fun mrUnrank1(rank: Int, n: Int, vec: IntArray) {
if (n < 1) return
val q = rank / n
val r = rank % n
vec.swap(r, n - 1)
mrUnrank1(q, n - 1, vec)
}
fun mrRank1(... |
Keep all operations the same but rewrite the snippet in Scala. | from math import log, modf, floor
def p(l, n, pwr=2):
l = int(abs(l))
digitcount = floor(log(l, 10))
log10pwr = log(pwr, 10)
raised, found = -1, 0
while found < n:
raised += 1
firstdigits = floor(10**(modf(log10pwr * raised)[0] + digitcount))
if firstdigits == l:
... | import kotlin.math.ln
import kotlin.math.pow
fun main() {
runTest(12, 1)
runTest(12, 2)
runTest(123, 45)
runTest(123, 12345)
runTest(123, 678910)
}
private fun runTest(l: Int, n: Int) {
println("p($l, $n) = %,d".format(p(l, n)))
}
fun p(l: Int, n: Int): Int {
var m = n
var test = 0
... |
Change the following Python code into Scala without altering its purpose. | from math import log, modf, floor
def p(l, n, pwr=2):
l = int(abs(l))
digitcount = floor(log(l, 10))
log10pwr = log(pwr, 10)
raised, found = -1, 0
while found < n:
raised += 1
firstdigits = floor(10**(modf(log10pwr * raised)[0] + digitcount))
if firstdigits == l:
... | import kotlin.math.ln
import kotlin.math.pow
fun main() {
runTest(12, 1)
runTest(12, 2)
runTest(123, 45)
runTest(123, 12345)
runTest(123, 678910)
}
private fun runTest(l: Int, n: Int) {
println("p($l, $n) = %,d".format(p(l, n)))
}
fun p(l: Int, n: Int): Int {
var m = n
var test = 0
... |
Rewrite the snippet below in Scala so it works the same as the original Python code. | computed = {}
def sterling2(n, k):
key = str(n) + "," + str(k)
if key in computed.keys():
return computed[key]
if n == k == 0:
return 1
if (n > 0 and k == 0) or (n == 0 and k > 0):
return 0
if n == k:
return 1
if k > n:
return 0
result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)
computed[key... | import java.math.BigInteger
fun main() {
println("Stirling numbers of the second kind:")
val max = 12
print("n/k")
for (n in 0..max) {
print("%10d".format(n))
}
println()
for (n in 0..max) {
print("%-3d".format(n))
for (k in 0..n) {
print("%10s".format(st... |
Convert this Python snippet to Scala and keep its semantics consistent. | computed = {}
def sterling2(n, k):
key = str(n) + "," + str(k)
if key in computed.keys():
return computed[key]
if n == k == 0:
return 1
if (n > 0 and k == 0) or (n == 0 and k > 0):
return 0
if n == k:
return 1
if k > n:
return 0
result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)
computed[key... | import java.math.BigInteger
fun main() {
println("Stirling numbers of the second kind:")
val max = 12
print("n/k")
for (n in 0..max) {
print("%10d".format(n))
}
println()
for (n in 0..max) {
print("%-3d".format(n))
for (k in 0..n) {
print("%10s".format(st... |
Generate an equivalent Scala version of this Python code. |
def convertToBase(n, b):
if(n < 2):
return [n];
temp = n;
ans = [];
while(temp != 0):
ans = [temp % b]+ ans;
temp /= b;
return ans;
def cipolla(n,p):
n %= p
if(n == 0 or n == 1):
return (n,-n%p)
phi = p - 1
if(pow(n, phi/2, p) != 1):
return ()
if(p%4 == 3):
ans = pow(n,(p+1)/4,p)
return (a... |
import java.math.BigInteger
class Point(val x: BigInteger, val y: BigInteger)
val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE
val bigTwo = BigInteger.valueOf(2L)
val bigBig = BigInteger.TEN.pow(50) + BigInteger.valueOf(151L)
fun c(ns: String, ps: String): Triple<BigInteger, BigInteger, Boolean> {
... |
Write a version of this Python function in Scala with identical behavior. |
def convertToBase(n, b):
if(n < 2):
return [n];
temp = n;
ans = [];
while(temp != 0):
ans = [temp % b]+ ans;
temp /= b;
return ans;
def cipolla(n,p):
n %= p
if(n == 0 or n == 1):
return (n,-n%p)
phi = p - 1
if(pow(n, phi/2, p) != 1):
return ()
if(p%4 == 3):
ans = pow(n,(p+1)/4,p)
return (a... |
import java.math.BigInteger
class Point(val x: BigInteger, val y: BigInteger)
val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE
val bigTwo = BigInteger.valueOf(2L)
val bigBig = BigInteger.TEN.pow(50) + BigInteger.valueOf(151L)
fun c(ns: String, ps: String): Triple<BigInteger, BigInteger, Boolean> {
... |
Write the same code in Scala as shown below 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
import kotlin.math.min
val one: BigInteger = BigInteger.ONE
val two: BigInteger = BigInteger.valueOf(2)
val three: BigInteger = BigInteger.valueOf(3)
fun pierpont(n: Int): List<List<BigInteger>> {
val p = List(2) { MutableList(n) { BigInteger.ZERO } }
p[0][0] = two
var count = ... |
Maintain the same structure and functionality when rewriting this code in Scala. | primes = [2, 3, 5, 7, 11, 13, 17, 19, 23]
def isPrime(n):
if n < 2:
return False
for i in primes:
if n == i:
return True
if n % i == 0:
return False
if i * i > n:
return True
print "Oops,", n, " is too large"
def init():
s = 24
w... | import java.math.BigInteger
var primes = mutableListOf<BigInteger>()
var smallPrimes = mutableListOf<Int>()
fun init() {
val two = BigInteger.valueOf(2)
val three = BigInteger.valueOf(3)
val p521 = BigInteger.valueOf(521)
val p29 = BigInteger.valueOf(29)
primes.add(two)
smallPrimes.add(2)
... |
Translate the given Python code snippet into Scala without altering its behavior. | from itertools import combinations as cmb
def isP(n):
if n == 2:
return True
if n % 2 == 0:
return False
return all(n % x > 0 for x in range(3, int(n ** 0.5) + 1, 2))
def genP(n):
p = [2]
p.extend([x for x in range(3, n + 1, 2) if isP(x)])
return p
data = [
(99809, 1), ... |
import kotlin.coroutines.experimental.*
val primes = generatePrimes().take(50_000).toList()
var foundCombo = false
fun isPrime(n: Int) : Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d : Int = 5
while (d * d <= n) {
if (n % d ==... |
Translate the given Python code snippet into Scala without altering its behavior. | import copy
class Zeckendorf:
def __init__(self, x='0'):
q = 1
i = len(x) - 1
self.dLen = int(i / 2)
self.dVal = 0
while i >= 0:
self.dVal = self.dVal + (ord(x[i]) - ord('0')) * q
q = q * 2
i = i -1
def a(self, n):
i = n
... |
class Zeckendorf(x: String = "0") : Comparable<Zeckendorf> {
var dVal = 0
var dLen = 0
private fun a(n: Int) {
var i = n
while (true) {
if (dLen < i) dLen = i
val j = (dVal shr (i * 2)) and 3
when (j) {
0, 1 -> return
2... |
Change the following Python code into Scala without altering its purpose. | computed = {}
def sterling1(n, k):
key = str(n) + "," + str(k)
if key in computed.keys():
return computed[key]
if n == k == 0:
return 1
if n > 0 and k == 0:
return 0
if k > n:
return 0
result = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k)
computed[key] = result
return result
print("Unsigne... | import java.math.BigInteger
fun main() {
println("Unsigned Stirling numbers of the first kind:")
val max = 12
print("n/k")
for (n in 0..max) {
print("%10d".format(n))
}
println()
for (n in 0..max) {
print("%-3d".format(n))
for (k in 0..n) {
print("%10s".f... |
Produce a language-to-language conversion: from Python to Scala, same semantics. | computed = {}
def sterling1(n, k):
key = str(n) + "," + str(k)
if key in computed.keys():
return computed[key]
if n == k == 0:
return 1
if n > 0 and k == 0:
return 0
if k > n:
return 0
result = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k)
computed[key] = result
return result
print("Unsigne... | import java.math.BigInteger
fun main() {
println("Unsigned Stirling numbers of the first kind:")
val max = 12
print("n/k")
for (n in 0..max) {
print("%10d".format(n))
}
println()
for (n in 0..max) {
print("%-3d".format(n))
for (k in 0..n) {
print("%10s".f... |
Preserve the algorithm and functionality while converting the code from Python to Scala. | from __future__ import print_function
from shapely.geometry import LineString
if __name__=="__main__":
line = LineString([(0,0),(1,0.1),(2,-0.1),(3,5),(4,6),(5,7),(6,8.1),(7,9),(8,9),(9,9)])
print (line.simplify(1.0, preserve_topology=False))
|
typealias Point = Pair<Double, Double>
fun perpendicularDistance(pt: Point, lineStart: Point, lineEnd: Point): Double {
var dx = lineEnd.first - lineStart.first
var dy = lineEnd.second - lineStart.second
val mag = Math.hypot(dx, dy)
if (mag > 0.0) { dx /= mag; dy /= mag }
val pvx = pt.first... |
Translate this program into Scala but keep the logic exactly as in Python. | from __future__ import print_function
from shapely.geometry import LineString
if __name__=="__main__":
line = LineString([(0,0),(1,0.1),(2,-0.1),(3,5),(4,6),(5,7),(6,8.1),(7,9),(8,9),(9,9)])
print (line.simplify(1.0, preserve_topology=False))
|
typealias Point = Pair<Double, Double>
fun perpendicularDistance(pt: Point, lineStart: Point, lineEnd: Point): Double {
var dx = lineEnd.first - lineStart.first
var dy = lineEnd.second - lineStart.second
val mag = Math.hypot(dx, dy)
if (mag > 0.0) { dx /= mag; dy /= mag }
val pvx = pt.first... |
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. |
import numpy as np
from scipy.misc import imread, imshow
from scipy import ndimage
def GetBilinearPixel(imArr, posX, posY):
out = []
modXi = int(posX)
modYi = int(posY)
modXf = posX - modXi
modYf = posY - modYi
modXiPlusOneLim = min(modXi+1,imArr.shape[1]-1)
modYiPlusOneLim = min(modYi+1,imArr.shape[0]-1)
... |
import java.io.File
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
operator fun Int.get(n: Int) = (this shr (n * 8)) and 0xFF
fun lerp(s: Float, e: Float, t: Float) = s + (e - s) * t
fun blerp(c00: Float, c10: Float, c01: Float, c11: Float, tx: Float, ty: Float) =
lerp(lerp(c00, c10, tx), l... |
Ensure the translated Scala code behaves exactly like the original Python snippet. |
import numpy as np
from scipy.misc import imread, imshow
from scipy import ndimage
def GetBilinearPixel(imArr, posX, posY):
out = []
modXi = int(posX)
modYi = int(posY)
modXf = posX - modXi
modYf = posY - modYi
modXiPlusOneLim = min(modXi+1,imArr.shape[1]-1)
modYiPlusOneLim = min(modYi+1,imArr.shape[0]-1)
... |
import java.io.File
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
operator fun Int.get(n: Int) = (this shr (n * 8)) and 0xFF
fun lerp(s: Float, e: Float, t: Float) = s + (e - s) * t
fun blerp(c00: Float, c10: Float, c01: Float, c11: Float, tx: Float, ty: Float) =
lerp(lerp(c00, c10, tx), l... |
Write a version of this Python function in Scala with identical behavior. | v1 = PVector(5, 7)
v2 = PVector(2, 3)
println('{} {} {} {}\n'.format( v1.x, v1.y, v1.mag(), v1.heading()))
println(v1 + v2)
println(v1 - v2)
println(v1 * 11)
println(v1 / 2)
println('')
println(v1.sub(v1))
println(v1.add(v2))
println(v1.mult(10))
println(v1.div(10))
|
class Vector2D(val x: Double, val y: Double) {
operator fun plus(v: Vector2D) = Vector2D(x + v.x, y + v.y)
operator fun minus(v: Vector2D) = Vector2D(x - v.x, y - v.y)
operator fun times(s: Double) = Vector2D(s * x, s * y)
operator fun div(s: Double) = Vector2D(x / s, y / s)
override fun toStr... |
Preserve the algorithm and functionality while converting the code from Python to Scala. |
class Point:
b = 7
def __init__(self, x=float('inf'), y=float('inf')):
self.x = x
self.y = y
def copy(self):
return Point(self.x, self.y)
def is_zero(self):
return self.x > 1e20 or self.x < -1e20
def neg(self):
return Point(self.x, -self.y)
def dbl(s... |
const val C = 7
class Pt(val x: Double, val y: Double) {
val zero get() = Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)
val isZero get() = x > 1e20 || x < -1e20
fun dbl(): Pt {
if (isZero) return this
val l = 3.0 * x * x / (2.0 * y)
val t = l * l - 2.0 * x
retur... |
Change the programming language of this snippet from Python to Scala without modifying what it does. |
class Point:
b = 7
def __init__(self, x=float('inf'), y=float('inf')):
self.x = x
self.y = y
def copy(self):
return Point(self.x, self.y)
def is_zero(self):
return self.x > 1e20 or self.x < -1e20
def neg(self):
return Point(self.x, -self.y)
def dbl(s... |
const val C = 7
class Pt(val x: Double, val y: Double) {
val zero get() = Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)
val isZero get() = x > 1e20 || x < -1e20
fun dbl(): Pt {
if (isZero) return this
val l = 3.0 * x * x / (2.0 * y)
val t = l * l - 2.0 * x
retur... |
Keep all operations the same but rewrite the snippet in Scala. | import math
def test_func(x):
return math.cos(x)
def mapper(x, min_x, max_x, min_to, max_to):
return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to
def cheb_coef(func, n, min, max):
coef = [0.0] * n
for i in xrange(n):
f = func(mapper(math.cos(math.pi * (i + 0.5) / n), -1, 1, min,... |
typealias DFunc = (Double) -> Double
fun mapRange(x: Double, min: Double, max: Double, minTo: Double, maxTo:Double): Double {
return (x - min) / (max - min) * (maxTo - minTo) + minTo
}
fun chebCoeffs(func: DFunc, n: Int, min: Double, max: Double): DoubleArray {
val coeffs = DoubleArray(n)
for (i in 0 un... |
Change the following Python code into Scala without altering its purpose. | import math
def test_func(x):
return math.cos(x)
def mapper(x, min_x, max_x, min_to, max_to):
return (x - min_x) / (max_x - min_x) * (max_to - min_to) + min_to
def cheb_coef(func, n, min, max):
coef = [0.0] * n
for i in xrange(n):
f = func(mapper(math.cos(math.pi * (i + 0.5) / n), -1, 1, min,... |
typealias DFunc = (Double) -> Double
fun mapRange(x: Double, min: Double, max: Double, minTo: Double, maxTo:Double): Double {
return (x - min) / (max - min) * (maxTo - minTo) + minTo
}
fun chebCoeffs(func: DFunc, n: Int, min: Double, max: Double): DoubleArray {
val coeffs = DoubleArray(n)
for (i in 0 un... |
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. | def bwt(s):
assert "\002" not in s and "\003" not in s, "Input string cannot contain STX and ETX characters"
s = "\002" + s + "\003"
table = sorted(s[i:] + s[:i] for i in range(len(s)))
last_column = [row[-1:] for row in table]
return "".join(last_column)
def ibwt(r):
table =... |
const val STX = "\u0002"
const val ETX = "\u0003"
fun bwt(s: String): String {
if (s.contains(STX) || s.contains(ETX)) {
throw RuntimeException("String can't contain STX or ETX")
}
val ss = STX + s + ETX
val table = Array<String>(ss.length) { ss.substring(it) + ss.substring(0, it) }
table... |
Write a version of this Python function in Scala with identical behavior. | def bwt(s):
assert "\002" not in s and "\003" not in s, "Input string cannot contain STX and ETX characters"
s = "\002" + s + "\003"
table = sorted(s[i:] + s[:i] for i in range(len(s)))
last_column = [row[-1:] for row in table]
return "".join(last_column)
def ibwt(r):
table =... |
const val STX = "\u0002"
const val ETX = "\u0003"
fun bwt(s: String): String {
if (s.contains(STX) || s.contains(ETX)) {
throw RuntimeException("String can't contain STX or ETX")
}
val ss = STX + s + ETX
val table = Array<String>(ss.length) { ss.substring(it) + ss.substring(0, it) }
table... |
Write the same algorithm in Scala as shown in this Python implementation. | import random
def riffleShuffle(va, flips):
nl = va
for n in range(flips):
cutPoint = len(nl)/2 + random.choice([-1, 1]) * random.randint(0, len(va)/10)
left = nl[0:cutPoint]
right = nl[cutPoint:]
del nl[:]
while (len(left) > 0 and len(right) > 0):
... |
import java.util.Random
import java.util.Collections.shuffle
val r = Random()
fun riffle(deck: List<Int>, iterations: Int): List<Int> {
val pile = deck.toMutableList()
repeat(iterations) {
val mid = deck.size / 2
val tenpc = mid / 10
val cut = mid - tenpc + r.nextInt(2 * te... |
Translate this program into Scala but keep the logic exactly as in Python. | import random
def riffleShuffle(va, flips):
nl = va
for n in range(flips):
cutPoint = len(nl)/2 + random.choice([-1, 1]) * random.randint(0, len(va)/10)
left = nl[0:cutPoint]
right = nl[cutPoint:]
del nl[:]
while (len(left) > 0 and len(right) > 0):
... |
import java.util.Random
import java.util.Collections.shuffle
val r = Random()
fun riffle(deck: List<Int>, iterations: Int): List<Int> {
val pile = deck.toMutableList()
repeat(iterations) {
val mid = deck.size / 2
val tenpc = mid / 10
val cut = mid - tenpc + r.nextInt(2 * te... |
Rewrite the snippet below in Scala so it works the same as the original Python code. |
from itertools import accumulate, chain, count, islice
from fractions import Fraction
def faulhaberTriangle(m):
def go(rs, n):
def f(x, y):
return Fraction(n, x) * y
xs = list(map(f, islice(count(2), m), rs))
return [Fraction(1 - sum(xs), 1)] + xs
return list(accum... |
import java.math.BigDecimal
import java.math.MathContext
val mc = MathContext(256)
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
class Frac : Comparable<Frac> {
val num: Long
val denom: Long
companion object {
val ZERO = Frac(0, 1)
val ONE = Frac(1, 1)
}
... |
Maintain the same structure and functionality when rewriting this code in Scala. | try:
import psyco
psyco.full()
except ImportError:
pass
MAX_N = 300
BRANCH = 4
ra = [0] * MAX_N
unrooted = [0] * MAX_N
def tree(br, n, l, sum = 1, cnt = 1):
global ra, unrooted, MAX_N, BRANCH
for b in xrange(br + 1, BRANCH + 1):
sum += n
if sum >= MAX_N:
return
... |
import java.math.BigInteger
const val MAX_N = 250
const val BRANCHES = 4
val rooted = Array(MAX_N + 1) { if (it < 2) BigInteger.ONE else BigInteger.ZERO }
val unrooted = Array(MAX_N + 1) { if (it < 2) BigInteger.ONE else BigInteger.ZERO }
val c = Array(BRANCHES) { BigInteger.ZERO }
fun tree(br: Int, n: Int, l: I... |
Produce a language-to-language conversion: from Python to Scala, same semantics. | try:
import psyco
psyco.full()
except ImportError:
pass
MAX_N = 300
BRANCH = 4
ra = [0] * MAX_N
unrooted = [0] * MAX_N
def tree(br, n, l, sum = 1, cnt = 1):
global ra, unrooted, MAX_N, BRANCH
for b in xrange(br + 1, BRANCH + 1):
sum += n
if sum >= MAX_N:
return
... |
import java.math.BigInteger
const val MAX_N = 250
const val BRANCHES = 4
val rooted = Array(MAX_N + 1) { if (it < 2) BigInteger.ONE else BigInteger.ZERO }
val unrooted = Array(MAX_N + 1) { if (it < 2) BigInteger.ONE else BigInteger.ZERO }
val c = Array(BRANCHES) { BigInteger.ZERO }
fun tree(br: Int, n: Int, l: I... |
Ensure the translated Scala code behaves exactly like the original Python snippet. | import re
_vowels = 'AEIOU'
def replace_at(text, position, fromlist, tolist):
for f, t in zip(fromlist, tolist):
if text[position:].startswith(f):
return ''.join([text[:position],
t,
text[position+len(f):]])
return text
def replace_e... |
val fStrs = listOf("MAC" to "MCC", "KN" to "N", "K" to "C", "PH" to "FF",
"PF" to "FF", "SCH" to "SSS")
val lStrs = listOf("EE" to "Y", "IE" to "Y", "DT" to "D", "RT" to "D",
"RD" to "D", "NT" to "D", "ND" to "D")
val mStrs = listOf("EV" to "AF", "KN" to "N", "SCH" to "SSS", "P... |
Write a version of this Python function in Scala with identical behavior. | import re
_vowels = 'AEIOU'
def replace_at(text, position, fromlist, tolist):
for f, t in zip(fromlist, tolist):
if text[position:].startswith(f):
return ''.join([text[:position],
t,
text[position+len(f):]])
return text
def replace_e... |
val fStrs = listOf("MAC" to "MCC", "KN" to "N", "K" to "C", "PH" to "FF",
"PF" to "FF", "SCH" to "SSS")
val lStrs = listOf("EE" to "Y", "IE" to "Y", "DT" to "D", "RT" to "D",
"RD" to "D", "NT" to "D", "ND" to "D")
val mStrs = listOf("EV" to "AF", "KN" to "N", "SCH" to "SSS", "P... |
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. | from fractions import Fraction
def nextu(a):
n = len(a)
a.append(1)
for i in range(n - 1, 0, -1):
a[i] = i * a[i] + a[i - 1]
return a
def nextv(a):
n = len(a) - 1
b = [(1 - n) * x for x in a]
b.append(1)
for i in range(n):
b[i + 1] += a[i]
return b
def sumpol(n):
... |
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
class Frac : Comparable<Frac> {
val num: Long
val denom: Long
companion object {
val ZERO = Frac(0, 1)
val ONE = Frac(1, 1)
}
constructor(n: Long, d: Long) {
require(d != 0L)
var nn = n
... |
Generate a Scala translation of this Python snippet without changing its computational steps. | Import-Module ActiveDirectory
$searchData = "user name"
$searchBase = "DC=example,DC=com"
get-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase
| import org.apache.directory.api.ldap.model.message.SearchScope
import org.apache.directory.ldap.client.api.{LdapConnection, LdapNetworkConnection}
object LdapSearchDemo extends App {
class LdapSearch {
def demonstrateSearch(): Unit = {
val conn = new LdapNetworkConnection("localhost", 11389)
try {... |
Write a version of this Python function in Scala with identical behavior. | def isPrime(n):
if n < 2:
return False
if n % 2 == 0:
return n == 2
if n % 3 == 0:
return n == 3
d = 5
while d * d <= n:
if n % d == 0:
return False
d += 2
if n % d == 0:
return False
d += 4
return True
def genera... |
import kotlin.coroutines.experimental.*
typealias Transition = Pair<Int, Int>
fun isPrime(n: Int) : Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d : Int = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (... |
Write the same algorithm in Scala as shown in this Python implementation. | def bags(n,cache={}):
if not n: return [(0, "")]
upto = sum([bags(x) for x in range(n-1, 0, -1)], [])
return [(c+1, '('+s+')') for c,s in bagchain((0, ""), n-1, upto)]
def bagchain(x, n, bb, start=0):
if not n: return [x]
out = []
for i in range(start, len(bb)):
c,s = bb[i]
if c <= n: out += bagchain((x[0]... |
typealias Tree = Long
val treeList = mutableListOf<Tree>()
val offset = IntArray(32) { if (it == 1) 1 else 0 }
fun append(t: Tree) {
treeList.add(1L or (t shl 1))
}
fun show(t: Tree, l: Int) {
var tt = t
var ll = l
while (ll-- > 0) {
print(if (tt % 2L == 1L) "(" else ")")
tt = tt u... |
Port the following code from Python to Scala with equivalent syntax and logic. | from elementary_cellular_automaton import eca, eca_wrap
def rule30bytes(lencells=100):
cells = '1' + '0' * (lencells - 1)
gen = eca(cells, 30)
while True:
yield int(''.join(next(gen)[0] for i in range(8)), 2)
if __name__ == '__main__':
print([b for i,b in zip(range(10), rule30bytes())])
|
const val N = 64
fun pow2(x: Int) = 1L shl x
fun evolve(state: Long, rule: Int) {
var state2 = state
for (p in 0..9) {
var b = 0
for (q in 7 downTo 0) {
val st = state2
b = (b.toLong() or ((st and 1L) shl q)).toInt()
state2 = 0L
for (i in 0 unt... |
Convert this Python block to Scala, preserving its control flow and logic. | from __future__ import print_function
def lgen(even=False, nmax=1000000):
start = 2 if even else 1
n, lst = 1, list(range(start, nmax + 1, 2))
lenlst = len(lst)
yield lst[0]
while n < lenlst and lst[n] < lenlst:
yield lst[n]
n, lst = n + 1, [j for i,j in enumerate(lst, 1) if i % lst... |
typealias IAE = IllegalArgumentException
val luckyOdd = MutableList(100000) { it * 2 + 1 }
val luckyEven = MutableList(100000) { it * 2 + 2 }
fun filterLuckyOdd() {
var n = 2
while (n < luckyOdd.size) {
val m = luckyOdd[n - 1]
val end = (luckyOdd.size / m) * m - 1
for (j in end down... |
Keep all operations the same but rewrite the snippet in Scala. | import math
import re
def inv(c):
denom = c.real * c.real + c.imag * c.imag
return complex(c.real / denom, -c.imag / denom)
class QuaterImaginary:
twoI = complex(0, 2)
invTwoI = inv(twoI)
def __init__(self, str):
if not re.match("^[0123.]+$", str) or str.count('.') > 1:
raise ... |
import kotlin.math.ceil
class Complex(val real: Double, val imag: Double) {
constructor(r: Int, i: Int) : this(r.toDouble(), i.toDouble())
operator fun plus(other: Complex) = Complex(real + other.real, imag + other.imag)
operator fun times(other: Complex) = Complex(
real * other.real - imag * ... |
Convert this Python block to Scala, preserving its control flow and logic. | from __future__ import division
import matplotlib.pyplot as plt
import random
mean, stddev, size = 50, 4, 100000
data = [random.gauss(mean, stddev) for c in range(size)]
mn = sum(data) / size
sd = (sum(x*x for x in data) / size
- (sum(data) / size) ** 2) ** 0.5
print("Sample mean = %g; Stddev = %g; max = %g;... |
val rand = java.util.Random()
fun normalStats(sampleSize: Int) {
if (sampleSize < 1) return
val r = DoubleArray(sampleSize)
val h = IntArray(12)
for (i in 0 until sampleSize) {
r[i] = 0.5 + rand.nextGaussian() / 4.0
when {
r[i] < 0.0 -> h[0]++
r[i] >= 1.... |
Maintain the same structure and functionality when rewriting this code in Scala. | from collections import defaultdict
costs = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},
'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},
'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},
'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}
demand = {'A': 30, 'B': 20, 'C': 70... |
val supply = intArrayOf(50, 60, 50, 50)
val demand = intArrayOf(30, 20, 70, 30, 60)
val costs = arrayOf(
intArrayOf(16, 16, 13, 22, 17),
intArrayOf(14, 14, 13, 19, 15),
intArrayOf(19, 19, 20, 23, 50),
intArrayOf(50, 12, 50, 15, 11)
)
val nRows = supply.size
val nCols = demand.size
val rowDone = Boo... |
Change the programming language of this snippet from Python to Scala without modifying what it does. | def getA004290(n):
if n < 2:
return 1
arr = [[0 for _ in range(n)] for _ in range(n)]
arr[0][0] = 1
arr[0][1] = 1
m = 0
while True:
m += 1
if arr[m - 1][-10 ** m % n] == 1:
break
arr[m][0] = 1
for k in range(1, n):
arr[m][k] = max([... | import java.math.BigInteger
fun main() {
for (n in testCases) {
val result = getA004290(n)
println("A004290($n) = $result = $n * ${result / n.toBigInteger()}")
}
}
private val testCases: List<Int>
get() {
val testCases: MutableList<Int> = ArrayList()
for (i in 1..10) {
... |
Please provide an equivalent version of this Python code in Scala. | import math
from sys import stdout
LOG_10 = 2.302585092994
def build_oms(s):
if s % 2 == 0:
s += 1
q = [[0 for j in range(s)] for i in range(s)]
p = 1
i = s // 2
j = 0
while p <= (s * s):
q[i][j] = p
ti = i + 1
if ti >= s: ti = 0
tj = j - 1
if ... |
fun magicSquareOdd(n: Int): Array<IntArray> {
if (n < 3 || n % 2 == 0)
throw IllegalArgumentException("Base must be odd and > 2")
var value = 0
val gridSize = n * n
var c = n / 2
var r = 0
val result = Array(n) { IntArray(n) }
while (++value <= gridSize) {
result[r][c] = ... |
Convert the following code from Python to Scala, ensuring the logic remains intact. |
from itertools import chain, count, islice, repeat
from functools import reduce
from math import sqrt
from time import time
def weirds():
def go(n):
ds = descPropDivs(n)
d = sum(ds) - n
return [n] if 0 < d and not hasSum(d, ds) else []
return concatMap(go)(count(1))
def hasS... |
fun divisors(n: Int): List<Int> {
val divs = mutableListOf(1)
val divs2 = mutableListOf<Int>()
var i = 2
while (i * i <= n) {
if (n % i == 0) {
val j = n / i
divs.add(i)
if (i != j) divs2.add(j)
}
i++
}
divs2.addAll(divs.asReversed())... |
Convert this Python block to Scala, preserving its control flow and logic. | from itertools import combinations, product, count
from functools import lru_cache, reduce
_bbullet, _wbullet = '\u2022\u25E6'
_or = set.__or__
def place(m, n):
"Place m black and white queens, peacefully, on an n-by-n board"
board = set(product(range(n), repeat=2))
placements = {frozenset(c) for c in ... | import kotlin.math.abs
enum class Piece {
Empty,
Black,
White,
}
typealias Position = Pair<Int, Int>
fun place(m: Int, n: Int, pBlackQueens: MutableList<Position>, pWhiteQueens: MutableList<Position>): Boolean {
if (m == 0) {
return true
}
var placingBlack = true
for (i in 0 until... |
Port the following code from Python to Scala with equivalent syntax and logic. | 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 is_prime(n):
return len(divisors(n)) == 2
def primes():
ii = 1
while True:
ii += 1... |
import java.math.BigInteger
import kotlin.math.sqrt
const val MAX = 33
fun isPrime(n: Int) = BigInteger.valueOf(n.toLong()).isProbablePrime(10)
fun generateSmallPrimes(n: Int): List<Int> {
val primes = mutableListOf<Int>()
primes.add(2)
var i = 3
while (primes.size < n) {
if (isPrime(i)) {
... |
Write a version of this Python function in Scala with identical behavior. |
import readline
while True:
try:
print(input('> '))
except:
break
|
var range = intArrayOf()
val history = mutableListOf<String>()
fun greeting() {
ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor()
println("** Welcome to the Ranger readline interface **")
println("** which performs operations on a range of integers **\n")
println("Command... |
Port the provided Python code into Scala while preserving the original functionality. | def prepend(n, seq):
return [n] + seq
def check_seq(pos, seq, n, min_len):
if pos > min_len or seq[0] > n:
return min_len, 0
if seq[0] == n:
return pos, 1
if pos < min_len:
return try_perm(0, pos, seq, n, min_len)
return min_len, 0
def try_perm(i, pos, seq, n, min_len):
... |
var example: List<Int>? = null
fun checkSeq(pos: Int, seq: List<Int>, n: Int, minLen: Int): Pair<Int, Int> =
if (pos > minLen || seq[0] > n) minLen to 0
else if (seq[0] == n) { example = seq; pos to 1 }
else if (pos < minLen) tryPerm(0, pos, seq, n, minLen)
else ... |
Write the same code in Scala as shown below in Python. | import sys
class UserInput:
def __init__(self,chunk):
self.formFeed = int(chunk[0])
self.lineFeed = int(chunk[1])
self.tab = int(chunk[2])
self.space = int(chunk[3])
def __str__(self):
return "(ff=%d; lf=%d; tb=%d; sp%d)" % (self.formFeed,self.lineFeed,self.tab,self.spa... |
import java.io.File
data class UserInput(val formFeed: Int, val lineFeed: Int, val tab: Int, val space: Int)
fun getUserInput(): List<UserInput> {
val h = "0 18 0 0 0 68 0 1 0 100 0 32 0 114 0 45 0 38 0 26 0 16 0 21 0 17 0 59 0 11 " +
"0 29 0 102 0 0 0 10 0 50 0 39 0 42 0 33 0 50 0 46 0 54 0 76 0 47... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.