Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. | >>> import winsound
>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:
winsound.Beep(int(note+.5), 500)
>>>
|
import kotlinx.cinterop.*
import win32.*
fun main(args: Array<String>) {
val freqs = intArrayOf(262, 294, 330, 349, 392, 440, 494, 523)
val dur = 500
repeat(5) { for (freq in freqs) Beep(freq, dur) }
}
|
Ensure the translated Scala code behaves exactly like the original Python snippet. | >>> import winsound
>>> for note in [261.63, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25]:
winsound.Beep(int(note+.5), 500)
>>>
|
import kotlinx.cinterop.*
import win32.*
fun main(args: Array<String>) {
val freqs = intArrayOf(262, 294, 330, 349, 392, 440, 494, 523)
val dur = 500
repeat(5) { for (freq in freqs) Beep(freq, dur) }
}
|
Maintain the same structure and functionality when rewriting this code in Scala. | import math
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((1024, 600))
pygame.display.set_caption("Polyspiral")
incr = 0
running = True
while running:
pygame.time.Clock().tick(60)
for event in pygame.event.get():
if event.type==QUIT:
running = False
break
inc... |
import java.awt.*
import java.awt.event.ActionEvent
import javax.swing.*
class PolySpiral() : JPanel() {
private var inc = 0.0
init {
preferredSize = Dimension(640, 640)
background = Color.white
Timer(40) {
inc = (inc + 0.05) % 360.0
repaint()
}.start(... |
Please provide an equivalent version of this Python code in Scala. | import math
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((1024, 600))
pygame.display.set_caption("Polyspiral")
incr = 0
running = True
while running:
pygame.time.Clock().tick(60)
for event in pygame.event.get():
if event.type==QUIT:
running = False
break
inc... |
import java.awt.*
import java.awt.event.ActionEvent
import javax.swing.*
class PolySpiral() : JPanel() {
private var inc = 0.0
init {
preferredSize = Dimension(640, 640)
background = Color.white
Timer(40) {
inc = (inc + 0.05) % 360.0
repaint()
}.start(... |
Convert this Python block to Scala, preserving its control flow and logic. | def setup():
size(500, 500)
generate_voronoi_diagram(width, height, 25)
saveFrame("VoronoiDiagram.png")
def generate_voronoi_diagram(w, h, num_cells):
nx, ny, nr, ng, nb = [], [], [], [], []
for i in range(num_cells):
nx.append(int(random(w)))
ny.append(int(random(h)))
nr.a... |
import java.awt.Color
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.geom.Ellipse2D
import java.awt.image.BufferedImage
import java.util.Random
import javax.swing.JFrame
fun distSq(x1: Int, x2: Int, y1: Int, y2: Int): Int {
val x = x1 - x2
val y = y1 - y2
return x * x + y * y
}
clas... |
Translate the given Python code snippet into Scala without altering its behavior. | def setup():
size(500, 500)
generate_voronoi_diagram(width, height, 25)
saveFrame("VoronoiDiagram.png")
def generate_voronoi_diagram(w, h, num_cells):
nx, ny, nr, ng, nb = [], [], [], [], []
for i in range(num_cells):
nx.append(int(random(w)))
ny.append(int(random(h)))
nr.a... |
import java.awt.Color
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.geom.Ellipse2D
import java.awt.image.BufferedImage
import java.util.Random
import javax.swing.JFrame
fun distSq(x1: Int, x2: Int, y1: Int, y2: Int): Int {
val x = x1 - x2
val y = y1 - y2
return x * x + y * y
}
clas... |
Change the programming language of this snippet from Python to Scala without modifying what it does. | import ldap
l = ldap.initialize("ldap://ldap.example.com")
try:
l.protocol_version = ldap.VERSION3
l.set_option(ldap.OPT_REFERRALS, 0)
bind = l.simple_bind_s("me@example.com", "password")
finally:
l.unbind()
| import org.apache.directory.api.ldap.model.exception.LdapException
import org.apache.directory.ldap.client.api.LdapNetworkConnection
import java.io.IOException
import java.util.logging.Level
import java.util.logging.Logger
class LDAP(map: Map<String, String>) {
fun run() {
var connection: LdapNetworkConnec... |
Rewrite the snippet below in Scala so it works the same as the original Python code. | import ctypes
def click():
ctypes.windll.user32.mouse_event(0x2, 0,0,0,0)
ctypes.windll.user32.mouse_event(0x4, 0,0,0,0)
click()
|
import java.awt.Robot
import java.awt.event.InputEvent
fun sendClick(buttons: Int) {
val r = Robot()
r.mousePress(buttons)
r.mouseRelease(buttons)
}
fun main(args: Array<String>) {
sendClick(InputEvent.BUTTON3_DOWN_MASK)
}
|
Convert this Python snippet to Scala and keep its semantics consistent. |
import strformat
import tables
type Item = tuple[name: string; weight, value, pieces: int]
const Items: seq[Item] = @[("map", 9, 150, 1),
("compass", 13, 35, 1),
("water", 153, 200, 2),
("sandwich", 50, 60, 2),
... |
data class Item(val name: String, val weight: Int, val value: Int, val count: Int)
val items = listOf(
Item("map", 9, 150, 1),
Item("compass", 13, 35, 1),
Item("water", 153, 200, 2),
Item("sandwich", 50, 60, 2),
Item("glucose", 15, 60, 2),
Item("tin", 68, 45, 3),
Item("banana", 27, 60, 3)... |
Maintain the same structure and functionality when rewriting this code in Scala. | from SOAPpy import WSDL
proxy = WSDL.Proxy("http://example.com/soap/wsdl")
result = proxy.soapFunc("hello")
result = proxy.anotherSoapFunc(34234)
|
import kotlinx.cinterop.*
import platform.posix.*
import libcurl.*
fun writeData(ptr: COpaquePointer?, size: size_t, nmeb: size_t, stream: COpaquePointer?)
= fwrite(ptr, size, nmeb, stream?.reinterpret<FILE>())
fun readData(ptr: COpaquePointer?, size: size_t, nmeb: size_t, stream: COpaquePointer?)
= fread(p... |
Transform the following Python implementation into Scala, maintaining the same output and logic. | from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print s... |
fun main(args: Array<String>) = println(args.asList())
|
Maintain the same structure and functionality when rewriting this code in Scala. | from optparse import OptionParser
[...]
parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print s... |
fun main(args: Array<String>) = println(args.asList())
|
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. | board = []
given = []
start = None
def setup(s):
global board, given, start
lines = s.splitlines()
ncols = len(lines[0].split())
nrows = len(lines)
board = [[-1] * (ncols + 2) for _ in xrange(nrows + 2)]
for r, row in enumerate(lines):
for c, cell in enumerate(row.split()):
... |
lateinit var board: List<IntArray>
lateinit var given: IntArray
lateinit var start: IntArray
fun setUp(input: List<String>) {
val nRows = input.size
val puzzle = List(nRows) { input[it].split(" ") }
val nCols = puzzle[0].size
val list = mutableListOf<Int>()
board = List(nRows + 2) { IntArray(nCol... |
Keep all operations the same but rewrite the snippet in Scala. | board = []
given = []
start = None
def setup(s):
global board, given, start
lines = s.splitlines()
ncols = len(lines[0].split())
nrows = len(lines)
board = [[-1] * (ncols + 2) for _ in xrange(nrows + 2)]
for r, row in enumerate(lines):
for c, cell in enumerate(row.split()):
... |
lateinit var board: List<IntArray>
lateinit var given: IntArray
lateinit var start: IntArray
fun setUp(input: List<String>) {
val nRows = input.size
val puzzle = List(nRows) { input[it].split(" ") }
val nCols = puzzle[0].size
val list = mutableListOf<Int>()
board = List(nRows + 2) { IntArray(nCol... |
Produce a language-to-language conversion: from Python to Scala, same semantics. | def merge_list(a, b):
out = []
while len(a) and len(b):
if a[0] < b[0]:
out.append(a.pop(0))
else:
out.append(b.pop(0))
out += a
out += b
return out
def strand(a):
i, s = 0, [a.pop(0)]
while i < len(a):
if a[i] > s[-1]:
s.append(a.pop(i))
else:
i += 1
return s
def strand_sort(a):
out = st... |
fun <T : Comparable<T>> strandSort(l: List<T>): List<T> {
fun merge(left: MutableList<T>, right: MutableList<T>): MutableList<T> {
val res = mutableListOf<T>()
while (!left.isEmpty() && !right.isEmpty()) {
if (left[0] <= right[0]) {
res.add(left[0])
left... |
Write the same algorithm in Scala as shown in this Python implementation. | PI = 3.141592653589793
TWO_PI = 6.283185307179586
def normalize2deg(a):
while a < 0: a += 360
while a >= 360: a -= 360
return a
def normalize2grad(a):
while a < 0: a += 400
while a >= 400: a -= 400
return a
def normalize2mil(a):
while a < 0: a += 6400
while a >= 6400: a -= 6400
return a
def normalize... | import java.text.DecimalFormat as DF
const val DEGREE = 360.0
const val GRADIAN = 400.0
const val MIL = 6400.0
const val RADIAN = 2 * Math.PI
fun d2d(a: Double) = a % DEGREE
fun d2g(a: Double) = a * (GRADIAN / DEGREE)
fun d2m(a: Double) = a * (MIL / DEGREE)
fun d2r(a: Double) = a * (RADIAN / 360)
fun g2d(a: Double) =... |
Preserve the algorithm and functionality while converting the code from Python to Scala. |
from xml.dom import minidom
xmlfile = file("test3.xml")
xmldoc = minidom.parse(xmlfile).documentElement
xmldoc = minidom.parseString("<inventory title="OmniCorp Store
i = xmldoc.getElementsByTagName("item")
firstItemElement = i[0]
for j in xmldoc.getElementsByTagName("price"):
print j.childNodes[0].data ... |
import javax.xml.parsers.DocumentBuilderFactory
import org.xml.sax.InputSource
import java.io.StringReader
import javax.xml.xpath.XPathFactory
import javax.xml.xpath.XPathConstants
import org.w3c.dom.Node
import org.w3c.dom.NodeList
val xml =
"""
<inventory title="OmniCorp Store #45x10^3">
<section name="health">... |
Write a version of this Python function in Scala with identical behavior. |
from mechanize import Browser
USER_AGENT = "Mozilla/5.0 (X11; U; Linux i686; tr-TR; rv:1.8.1.9) Gecko/20071102 Pardus/2007 Firefox/2.0.0.9"
br = Browser()
br.addheaders = [("User-agent", USER_AGENT)]
br.open("https://www.facebook.com")
br.select_form("loginform")
br['email'] = "xxxxxxx@xxxxx.com"
br['pass']... |
import java.net.Authenticator
import java.net.PasswordAuthentication
import javax.net.ssl.HttpsURLConnection
import java.net.URL
import java.io.InputStreamReader
import java.io.BufferedReader
object PasswordAuthenticator : Authenticator() {
override fun getPasswordAuthentication() =
PasswordAuthenticatio... |
Change the programming language of this snippet from Python to Scala without modifying what it does. | def mc_rank(iterable, start=1):
lastresult, fifo = None, []
for n, item in enumerate(iterable, start-1):
if item[0] == lastresult:
fifo += [item]
else:
while fifo:
yield n, fifo.pop(0)
lastresult, fifo = item[0], fifo + [item]
while fi... |
fun standardRanking(scores: Array<Pair<Int, String>>): IntArray {
val rankings = IntArray(scores.size)
rankings[0] = 1
for (i in 1 until scores.size) rankings[i] = if (scores[i].first == scores[i - 1].first) rankings[i - 1] else i + 1
return rankings
}
fun modifiedRanking(scores: Array<Pair<Int,... |
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. |
import re
import string
DISABLED_PREFIX = ';'
class Option(object):
def __init__(self, name, value=None, disabled=False,
disabled_prefix=DISABLED_PREFIX):
self.name = str(name)
self.value = value
self.disabled = bool(disabled)
self.... |
import java.io.File
class ConfigData(
val favouriteFruit: String,
val needsPeeling: Boolean,
val seedsRemoved: Boolean,
val numberOfBananas: Int,
val numberOfStrawberries: Int
)
fun updateConfigFile(fileName: String, cData: ConfigData) {
val inp = File(fileName)
val lines = inp.readLines... |
Produce a functionally identical Scala code for the snippet given in Python. | T = [["79", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
["", "H", "O", "L", "", "M", "E", "S", "", "R", "T"],
["3", "A", "B", "C", "D", "F", "G", "I", "J", "K", "N"],
["7", "P", "Q", "U", "V", "W", "X", "Y", "Z", ".", "/"]]
def straddle(s):
return "".join(L[0]+T[0][L.index(c)] for c in ... |
val board = "ET AON RISBCDFGHJKLMPQ/UVWXYZ."
val digits = "0123456789"
val rows = " 26"
val escape = "62"
val key = "0452"
fun encrypt(message: String): String {
val msg = message.toUpperCase()
.filter { (it in board || it in digits) && it !in " /" }
val sb = StringBuilder()
for (c i... |
Write the same algorithm in Scala as shown in this Python implementation. | import urllib.request
import re
PLAUSIBILITY_RATIO = 2
def plausibility_check(comment, x, y):
print('\n Checking plausibility of: %s' % comment)
if x > PLAUSIBILITY_RATIO * y:
print(' PLAUSIBLE. As we have counts of %i vs %i, a ratio of %4.1f times'
% (x, y, x / y))
else:
... |
import java.net.URL
import java.io.InputStreamReader
import java.io.BufferedReader
fun isPlausible(n1: Int, n2: Int) = n1 > 2 * n2
fun printResults(source: String, counts: IntArray) {
println("Results for $source")
println(" i before e except after c")
println(" for ${counts[0]}")
println(" ... |
Write the same algorithm in Scala as shown in this Python implementation. | import urllib.request
import re
PLAUSIBILITY_RATIO = 2
def plausibility_check(comment, x, y):
print('\n Checking plausibility of: %s' % comment)
if x > PLAUSIBILITY_RATIO * y:
print(' PLAUSIBLE. As we have counts of %i vs %i, a ratio of %4.1f times'
% (x, y, x / y))
else:
... |
import java.net.URL
import java.io.InputStreamReader
import java.io.BufferedReader
fun isPlausible(n1: Int, n2: Int) = n1 > 2 * n2
fun printResults(source: String, counts: IntArray) {
println("Results for $source")
println(" i before e except after c")
println(" for ${counts[0]}")
println(" ... |
Port the provided Python code into Scala while preserving the original functionality. |
from __future__ import division
import sys
from PIL import Image
def _fpart(x):
return x - int(x)
def _rfpart(x):
return 1 - _fpart(x)
def putpixel(img, xy, color, alpha=1):
compose_color = lambda bg, fg: int(round(alpha * fg + (1-alpha) * bg))
c = compose_color(img.getpixel(xy), color)
i... |
import java.awt.*
import javax.swing.*
class XiaolinWu: JPanel() {
init {
preferredSize = Dimension(640, 640)
background = Color.white
}
private fun plot(g: Graphics2D, x: Double, y: Double, c: Double) {
g.color = Color(0f, 0f, 0f, c.toFloat())
g.fillOval(x.toInt(), y.toI... |
Port the following code from Python to Scala with equivalent syntax and logic. | def closest_more_than(n, lst):
"(index of) closest int from lst, to n that is also > n"
large = max(lst) + 1
return lst.index(min(lst, key=lambda x: (large if x <= n else x)))
def nexthigh(n):
"Return nxt highest number from n's digits using scan & re-order"
assert n == int(abs(n)), "n >= 0"
th... | import java.math.BigInteger
import java.text.NumberFormat
fun main() {
for (s in arrayOf(
"0",
"9",
"12",
"21",
"12453",
"738440",
"45072010",
"95322020",
"9589776899767587796600",
"3345333"
)) {
println("${format(s)} -> ${... |
Transform the following Python implementation into Scala, maintaining the same output and logic. | def closest_more_than(n, lst):
"(index of) closest int from lst, to n that is also > n"
large = max(lst) + 1
return lst.index(min(lst, key=lambda x: (large if x <= n else x)))
def nexthigh(n):
"Return nxt highest number from n's digits using scan & re-order"
assert n == int(abs(n)), "n >= 0"
th... | import java.math.BigInteger
import java.text.NumberFormat
fun main() {
for (s in arrayOf(
"0",
"9",
"12",
"21",
"12453",
"738440",
"45072010",
"95322020",
"9589776899767587796600",
"3345333"
)) {
println("${format(s)} -> ${... |
Port the following code from Python to Scala with equivalent syntax and logic. | import autopy
autopy.key.type_string("Hello, world!")
autopy.key.type_string("Hello, world!", wpm=60)
autopy.key.tap(autopy.key.Code.RETURN)
autopy.key.tap(autopy.key.Code.F1)
autopy.key.tap(autopy.key.Code.LEFT_ARROW)
|
import java.awt.Robot
import java.awt.event.KeyEvent
fun sendChars(s: String, pressReturn: Boolean = true) {
val r = Robot()
for (c in s) {
val ci = c.toUpperCase().toInt()
r.keyPress(ci)
r.keyRelease(ci)
}
if (pressReturn) {
r.keyPress(KeyEvent.VK_ENTER)
r.key... |
Change the programming language of this snippet from Python to Scala without modifying what it does. | import random
from collections import OrderedDict
numbers = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 's... |
val names = mapOf(
1 to "one",
2 to "two",
3 to "three",
4 to "four",
5 to "five",
6 to "six",
7 to "seven",
8 to "eight",
9 to "nine",
10 to "ten",
11 to "eleven",
12 to "twelve",
13 to "thirteen",
14 to "fourteen",
15 to "fifteen",
16 to "sixteen",
... |
Change the programming language of this snippet from Python to Scala without modifying what it does. |
import numpy as np
class Revolver:
def __init__(self):
self.cylinder = np.array([False] * 6)
def unload(self):
self.cylinder[:] = False
def load(self):
while self.cylinder[1]:
self.cylinder[:] = np.roll(self.cylinder, 1)
self.c... | import kotlin.random.Random
val cylinder = Array(6) { false }
fun rShift() {
val t = cylinder[cylinder.size - 1]
for (i in (0 until cylinder.size - 1).reversed()) {
cylinder[i + 1] = cylinder[i]
}
cylinder[0] = t
}
fun unload() {
for (i in cylinder.indices) {
cylinder[i] = false
... |
Please provide an equivalent version of this Python code in Scala. | from turtle import *
import math
speed(0)
hideturtle()
part_ratio = 2 * math.cos(math.radians(72))
side_ratio = 1 / (part_ratio + 2)
hide_turtles = True
path_color = "black"
fill_color = "black"
def pentagon(t, s):
t.color(path_color, fill_color)
t.pendown()
t.right(36)
t.begin_fill()
for i... |
import java.awt.*
import java.awt.geom.Path2D
import java.util.Random
import javax.swing.*
class SierpinskiPentagon : JPanel() {
private val degrees072 = Math.toRadians(72.0)
private val scaleFactor = 1.0 / (2.0 + Math.cos(degrees072) * 2.0)
private val margin = 20
private var limit = 0
... |
Change the programming language of this snippet from Python to Scala without modifying what it does. |
beforeTxt =
smallrc01 =
rc01 =
def intarray(binstring):
return [[1 if ch == '1' else 0 for ch in line]
for line in binstring.strip().split()]
def chararray(intmatrix):
return '\n'.join(''.join(str(p) for p in row) for row in intmatrix)
def toTxt(intmatrix):
Return 8-neighb... |
class Point(val x: Int, val y: Int)
val image = arrayOf(
" ",
" ################# ############# ",
" ################## ################ ",
" ################### ################## ... |
Rewrite the snippet below in Scala so it works the same as the original Python code. | >>> from itertools import permutations
>>> pieces = 'KQRrBbNN'
>>> starts = {''.join(p).upper() for p in permutations(pieces)
if p.index('B') % 2 != p.index('b') % 2
and ( p.index('r') < p.index('K') < p.index('R')
or p.index('R') < p.index('K') <... | object Chess960 : Iterable<String> {
override fun iterator() = patterns.iterator()
private operator fun invoke(b: String, e: String) {
if (e.length <= 1) {
val s = b + e
if (s.is_valid()) patterns += s
} else {
for (i in 0 until e.length) {
in... |
Ensure the translated Scala code behaves exactly like the original Python snippet. |
import itertools
import re
RE_BARCODE = re.compile(
r"^(?P<s_quiet> +)"
r"(?P<s_guard>
r"(?P<left>[
r"(?P<m_guard>
r"(?P<right>[
r"(?P<e_guard>
r"(?P<e_quiet> +)$"
)
LEFT_DIGITS = {
(0, 0, 0, 1, 1, 0, 1): 0,
(0, 0, 1, 1, 0, 0, 1): 1,
(0, 0, 1, 0, 0, 1, 1): 2,
(0, 1,... | val LEFT_DIGITS = mapOf(
" ## #" to 0,
" ## #" to 1,
" # ##" to 2,
" #### #" to 3,
" # ##" to 4,
" ## #" to 5,
" # ####" to 6,
" ### ##" to 7,
" ## ###" to 8,
" # ##" to 9
)
val RIGHT_DIGITS = LEFT_DIGITS.mapKeys {
it.key.replace(' ', 's').replace('#', ' ').replac... |
Preserve the algorithm and functionality while converting the code from Python to Scala. | import win32api
import win32con
import win32evtlog
import win32security
import win32evtlogutil
ph = win32api.GetCurrentProcess()
th = win32security.OpenProcessToken(ph, win32con.TOKEN_READ)
my_sid = win32security.GetTokenInformation(th, win32security.TokenUser)[0]
applicationName = "My Application"
eventID = 1
catego... |
fun main(args: Array<String>) {
val command = "EventCreate" +
" /t INFORMATION" +
" /id 123" +
" /l APPLICATION" +
" /so Kotlin" +
" /d \"Rosetta Code Example\""
Runtime.getRuntime().exec(command)
}
|
Generate an equivalent Scala version of this Python code. | irregularOrdinals = {
"one": "first",
"two": "second",
"three": "third",
"five": "fifth",
"eight": "eighth",
"nine": "ninth",
"twelve": "twelfth",
}
def num2ordinal(n):
conversion = int(float(n))
num = spell_integer(conversion)
hyphen = num.rsplit("-", 1)
num = num.rsplit(" ", 1)
... |
typealias IAE = IllegalArgumentException
val names = mapOf(
1 to "one",
2 to "two",
3 to "three",
4 to "four",
5 to "five",
6 to "six",
7 to "seven",
8 to "eight",
9 to "nine",
10 to "ten",
11 to "eleven",
12 to "twelve",
13 to "thirteen",
14 to "fourteen",
... |
Translate this program into Scala but keep the logic exactly as in Python. | import ctypes
import os
from ctypes import c_ubyte, c_int
code = bytes([0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3])
code_size = len(code)
if (os.name == 'posix'):
import mmap
executable_map = mmap.mmap(-1, code_size, mmap.MAP_PRIVATE | mmap.MAP_ANON, mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EX... |
import kotlinx.cinterop.*
import string.*
import mman.*
import mcode.*
fun main(args: Array<String>) {
memScoped {
val bytes = byteArrayOf(
144 - 256,
144 - 256,
106, 12,
184 - 256, 7, 0, 0, ... |
Change the following Python code into Scala without altering its purpose. | from ipaddress import ip_address
from urllib.parse import urlparse
tests = [
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:80",
"::192.168.0.1",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80" ]
def parse_ip_port(netloc):
try:
ip = ip_address(netloc)
port = Non... |
import java.math.BigInteger
enum class AddressSpace { IPv4, IPv6, Invalid }
data class IPAddressComponents(
val address: BigInteger,
val addressSpace: AddressSpace,
val port: Int
)
val INVALID = IPAddressComponents(BigInteger.ZERO, AddressSpace.Invalid, 0)
fun ipAddressParse(ipAddress: String): IP... |
Rewrite the snippet below in Scala so it works the same as the original Python code. | In [6]: def dec(n):
...: return len(n.rsplit('.')[-1]) if '.' in n else 0
In [7]: dec('12.345')
Out[7]: 3
In [8]: dec('12.3450')
Out[8]: 4
In [9]:
| fun findNumOfDec(x: Double): Int {
val str = x.toString()
if (str.endsWith(".0")) {
return 0
}
return str.substring(str.indexOf('.')).length - 1
}
fun main() {
for (n in listOf(12.0, 12.345, 12.345555555555, 12.3450, 12.34555555555555555555, 1.2345e+54)) {
println("%f has %d decimal... |
Please provide an equivalent version of this Python code in Scala. | from sys import stdout
neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]
cnt = 0
pWid = 0
pHei = 0
def is_valid(a, b):
return -1 < a < pWid and -1 < b < pHei
def iterate(pa, x, y, v):
if v > cnt:
return 1
for i in range(len(neighbours)):
a = x + neighb... |
val board = listOf(
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0..."
)
val moves = listOf(
-3 to 0, 0 to 3, 3 to 0, 0 to -3,
2 to 2, 2 to -2, -2 to 2, -2 to -2
)
lateinit var grid: List<IntArray>
var totalToFill = 0
fun solve(r: Int, c: Int, count: Int): Boolean ... |
Generate a Scala translation of this Python snippet without changing its computational steps. | from sys import stdout
neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]]
cnt = 0
pWid = 0
pHei = 0
def is_valid(a, b):
return -1 < a < pWid and -1 < b < pHei
def iterate(pa, x, y, v):
if v > cnt:
return 1
for i in range(len(neighbours)):
a = x + neighb... |
val board = listOf(
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0..."
)
val moves = listOf(
-3 to 0, 0 to 3, 3 to 0, 0 to -3,
2 to 2, 2 to -2, -2 to 2, -2 to -2
)
lateinit var grid: List<IntArray>
var totalToFill = 0
fun solve(r: Int, c: Int, count: Int): Boolean ... |
Produce a language-to-language conversion: from Python to Scala, same semantics. | from sys import stdout
neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]
exists = []
lastNumber = 0
wid = 0
hei = 0
def find_next(pa, x, y, z):
for i in range(4):
a = x + neighbours[i][0]
b = y + neighbours[i][1]
if wid > a > -1 and hei > b > -1:
if pa[a][b] == z:
... |
val example1 = listOf(
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,... |
Write the same code in Scala as shown below in Python. | from sys import stdout
neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]]
exists = []
lastNumber = 0
wid = 0
hei = 0
def find_next(pa, x, y, z):
for i in range(4):
a = x + neighbours[i][0]
b = y + neighbours[i][1]
if wid > a > -1 and hei > b > -1:
if pa[a][b] == z:
... |
val example1 = listOf(
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,... |
Generate an equivalent Scala version of this Python code. | class Example(object):
def foo(self):
print("this is foo")
def bar(self):
print("this is bar")
def __getattr__(self, name):
def method(*args):
print("tried to handle unknown method " + name)
if args:
print("it had arguments: " + str(args))
... |
class C {
fun __noSuchMethod__(id: String, args: Array<Any>) {
println("Class C does not have a method called $id")
if (args.size > 0) println("which takes arguments: ${args.asList()}")
}
}
fun main(args: Array<String>) {
val c: dynamic = C()
c.foo()
}
|
Convert this Python block to Scala, preserving its control flow and logic. | assert 1.008 == molar_mass('H')
assert 2.016 == molar_mass('H2')
assert 18.015 == molar_mass('H2O')
assert 34.014 == molar_mass('H2O2')
assert 34.014 == molar_mass('(HO)2')
assert 142.036 == molar_mass('Na2SO4')
assert ... | var atomicMass = mutableMapOf(
"H" to 1.008,
"He" to 4.002602,
"Li" to 6.94,
"Be" to 9.0121831,
"B" to 10.81,
"C" to 12.011,
"N" to 14.007,
"O" to 15.999,
"F" to 18.998403163,
"Ne" to 20.1797,
"Na" to 22.98976928,
"Mg" to 24.305,
"Al" to 26.9815385,
"Si" to 28.085... |
Transform the following Python implementation into Scala, maintaining the same output and logic. | import operator
class AstNode(object):
def __init__( self, opr, left, right ):
self.opr = opr
self.l = left
self.r = right
def eval(self):
return self.opr(self.l.eval(), self.r.eval())
class LeafNode(object):
def __init__( self, valStrg ):
self.v = int(valStrg)
def eval(sel... |
fun String.toDoubleOrZero() = this.toDoubleOrNull() ?: 0.0
fun multiply(s: String): String {
val b = s.split('*').map { it.toDoubleOrZero() }
return (b[0] * b[1]).toString()
}
fun divide(s: String): String {
val b = s.split('/').map { it.toDoubleOrZero() }
return (b[0] / b[1]).toString()
}
fun add... |
Port the provided Python code into Scala while preserving the original functionality. | import operator
class AstNode(object):
def __init__( self, opr, left, right ):
self.opr = opr
self.l = left
self.r = right
def eval(self):
return self.opr(self.l.eval(), self.r.eval())
class LeafNode(object):
def __init__( self, valStrg ):
self.v = int(valStrg)
def eval(sel... |
fun String.toDoubleOrZero() = this.toDoubleOrNull() ?: 0.0
fun multiply(s: String): String {
val b = s.split('*').map { it.toDoubleOrZero() }
return (b[0] * b[1]).toString()
}
fun divide(s: String): String {
val b = s.split('/').map { it.toDoubleOrZero() }
return (b[0] / b[1]).toString()
}
fun add... |
Write the same algorithm in Scala as shown in this Python implementation. | import os
targetfile = "pycon-china"
os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak")
f = open(os.path.realpath(targetfile), "w")
f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011")
f.close()
|
import java.io.File
fun saveWithBackup(fileName: String, vararg data: String) {
val orig = File(fileName)
val backup = File(orig.canonicalPath + ".backup")
orig.renameTo(backup)
val pw = orig.printWriter()
for (i in data.indices) {
pw.print(data[i])
if (i < data.lastIndex) pw... |
Please provide an equivalent version of this Python code in Scala. | import os
targetfile = "pycon-china"
os.rename(os.path.realpath(targetfile), os.path.realpath(targetfile)+".bak")
f = open(os.path.realpath(targetfile), "w")
f.write("this task was solved during a talk about rosettacode at the PyCon China in 2011")
f.close()
|
import java.io.File
fun saveWithBackup(fileName: String, vararg data: String) {
val orig = File(fileName)
val backup = File(orig.canonicalPath + ".backup")
orig.renameTo(backup)
val pw = orig.printWriter()
for (i in data.indices) {
pw.print(data[i])
if (i < data.lastIndex) pw... |
Maintain the same structure and functionality when rewriting this code in Scala. |
from re import sub
testtexts = [
,
,
]
for txt in testtexts:
text2 = sub(r'<lang\s+\"?([\w\d\s]+)\"?\s?>', r'<syntaxhighlight lang=\1>', txt)
text2 = sub(r'<lang\s*>', r'<syntaxhighlight lang=text>', text2)
text2 = sub(r'</lang\s*>', r'
| object FixCodeTags extends App {
val rx =
s"(?is)<(?:(?:code\\s+)?(${langs.mkString("|")}))>(.+?|)<\\/(?:code|\\1)>".r
def langs =
Seq("bar", "baz", "foo", "Scala", "உயிர்/Uyir", "Müller")
def markDown =
"""Lorem ipsum <Code foo>saepe audire</code> elaboraret ne quo, id equidem
|... |
Generate a Scala translation of this Python snippet without changing its computational steps. | def expr(p)
if tok is "("
x = paren_expr()
elif tok in ["-", "+", "!"]
gettok()
y = expr(precedence of operator)
if operator was "+"
x = y
else
x = make_node(operator, y)
elif tok is an Identifier
x = make_leaf(Identifier, variable name... | package xyz.hyperreal.rosettacodeCompiler
import scala.io.Source
object SyntaxAnalyzer {
val symbols =
Map[String, (PrefixOperator, InfixOperator)](
"Op_or" -> (null, InfixOperator(10, LeftAssoc, BranchNode("Or", _, _))),
"Op_and" -> (null, InfixOperator(20, LeftAssoc, BranchNode... |
Maintain the same structure and functionality when rewriting this code in Scala. | def expr(p)
if tok is "("
x = paren_expr()
elif tok in ["-", "+", "!"]
gettok()
y = expr(precedence of operator)
if operator was "+"
x = y
else
x = make_node(operator, y)
elif tok is an Identifier
x = make_leaf(Identifier, variable name... | package xyz.hyperreal.rosettacodeCompiler
import scala.io.Source
object SyntaxAnalyzer {
val symbols =
Map[String, (PrefixOperator, InfixOperator)](
"Op_or" -> (null, InfixOperator(10, LeftAssoc, BranchNode("Or", _, _))),
"Op_and" -> (null, InfixOperator(20, LeftAssoc, BranchNode... |
Change the programming language of this snippet from Python to Scala without modifying what it does. | import random
import sys
snl = {
4: 14,
9: 31,
17: 7,
20: 38,
28: 84,
40: 59,
51: 67,
54: 34,
62: 19,
63: 81,
64: 60,
71: 91,
87: 24,
93: 73,
95: 75,
99: 78
}
sixesRollAgain = True
def turn(player, square):
while True:
roll = random.randint(1... |
import java.util.Random
val rand = Random()
val snl = mapOf(
4 to 14, 9 to 31, 17 to 7, 20 to 38, 28 to 84, 40 to 59, 51 to 67, 54 to 34,
62 to 19, 63 to 81, 64 to 60, 71 to 91, 87 to 24, 93 to 73, 95 to 75, 99 to 78
)
val sixThrowsAgain = true
fun turn(player: Int, square: Int): Int {
var square2 ... |
Port the provided Python code into Scala while preserving the original functionality. | import random
import sys
snl = {
4: 14,
9: 31,
17: 7,
20: 38,
28: 84,
40: 59,
51: 67,
54: 34,
62: 19,
63: 81,
64: 60,
71: 91,
87: 24,
93: 73,
95: 75,
99: 78
}
sixesRollAgain = True
def turn(player, square):
while True:
roll = random.randint(1... |
import java.util.Random
val rand = Random()
val snl = mapOf(
4 to 14, 9 to 31, 17 to 7, 20 to 38, 28 to 84, 40 to 59, 51 to 67, 54 to 34,
62 to 19, 63 to 81, 64 to 60, 71 to 91, 87 to 24, 93 to 73, 95 to 75, 99 to 78
)
val sixThrowsAgain = true
fun turn(player: Int, square: Int): Int {
var square2 ... |
Write a version of this Python function in Scala with identical behavior. | from fractions import Fraction
class Fr(Fraction):
def __repr__(self):
return '(%s/%s)' % (self.numerator, self.denominator)
def farey(n, length=False):
if not length:
return [Fr(0, 1)] + sorted({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)})
else:
return (n*(... |
fun farey(n: Int): List<String> {
var a = 0
var b = 1
var c = 1
var d = n
val f = mutableListOf("$a/$b")
while (c <= n) {
val k = (n + b) / d
val aa = a
val bb = b
a = c
b = d
c = k * c - aa
d = k * d - bb
f.add("$a/$b")
}
... |
Produce a language-to-language conversion: from Python to Scala, same semantics. | from fractions import Fraction
class Fr(Fraction):
def __repr__(self):
return '(%s/%s)' % (self.numerator, self.denominator)
def farey(n, length=False):
if not length:
return [Fr(0, 1)] + sorted({Fr(m, k) for k in range(1, n+1) for m in range(1, k+1)})
else:
return (n*(... |
fun farey(n: Int): List<String> {
var a = 0
var b = 1
var c = 1
var d = n
val f = mutableListOf("$a/$b")
while (c <= n) {
val k = (n + b) / d
val aa = a
val bb = b
a = c
b = d
c = k * c - aa
d = k * d - bb
f.add("$a/$b")
}
... |
Keep all operations the same but rewrite the snippet in Scala. | from proper_divisors import proper_divs
from functools import lru_cache
@lru_cache()
def pdsum(n):
return sum(proper_divs(n))
def aliquot(n, maxlen=16, maxterm=2**47):
if n == 0:
return 'terminating', [0]
s, slen, new = [n], 1, n
while slen <= maxlen and new < maxterm:
new =... |
data class Classification(val sequence: List<Long>, val aliquot: String)
const val THRESHOLD = 1L shl 47
fun sumProperDivisors(n: Long): Long {
if (n < 2L) return 0L
val sqrt = Math.sqrt(n.toDouble()).toLong()
var sum = 1L + (2L..sqrt)
.filter { n % it == 0L }
.map { it + n / it }
... |
Transform the following Python implementation into Scala, maintaining the same output and logic. | from proper_divisors import proper_divs
from functools import lru_cache
@lru_cache()
def pdsum(n):
return sum(proper_divs(n))
def aliquot(n, maxlen=16, maxterm=2**47):
if n == 0:
return 'terminating', [0]
s, slen, new = [n], 1, n
while slen <= maxlen and new < maxterm:
new =... |
data class Classification(val sequence: List<Long>, val aliquot: String)
const val THRESHOLD = 1L shl 47
fun sumProperDivisors(n: Long): Long {
if (n < 2L) return 0L
val sqrt = Math.sqrt(n.toDouble()).toLong()
var sum = 1L + (2L..sqrt)
.filter { n % it == 0L }
.map { it + n / it }
... |
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. | from fractions import Fraction
from decimal import Decimal, getcontext
getcontext().prec = 60
from itertools import product
casting_functions = [int, float, complex,
Fraction, Decimal,
hex, oct, bin,
bool,
... |
open class C(val x: Int)
class D(x: Int) : C(x)
fun main(args: Array<String>) {
val c: C = D(42)
println(c.x)
val b: Byte = 100
println(b)
val s: Short = 32000
println(s)
val l: Long = 1_000_000
println(l)
val n : Int? = c.x
println(n)
}
|
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. | from fractions import Fraction
from decimal import Decimal, getcontext
getcontext().prec = 60
from itertools import product
casting_functions = [int, float, complex,
Fraction, Decimal,
hex, oct, bin,
bool,
... |
open class C(val x: Int)
class D(x: Int) : C(x)
fun main(args: Array<String>) {
val c: C = D(42)
println(c.x)
val b: Byte = 100
println(b)
val s: Short = 32000
println(s)
val l: Long = 1_000_000
println(l)
val n : Int? = c.x
println(n)
}
|
Change the programming language of this snippet from Python to Scala without modifying what it does. | def load_ast()
line = readline()
line_list = tokenize the line, respecting double quotes
text = line_list[0]
if text == ";"
return None
node_type = text
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = lo... | package xyz.hyperreal.rosettacodeCompiler
import scala.collection.mutable.{ArrayBuffer, HashMap}
import scala.io.Source
object CodeGenerator {
def fromStdin = fromSource(Source.stdin)
def fromString(src: String) = fromSource(Source.fromString(src))
def fromSource(ast: Source) = {
val vars = ... |
Port the following code from Python to Scala with equivalent syntax and logic. | def load_ast()
line = readline()
line_list = tokenize the line, respecting double quotes
text = line_list[0]
if text == ";"
return None
node_type = text
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right = lo... | package xyz.hyperreal.rosettacodeCompiler
import scala.collection.mutable.{ArrayBuffer, HashMap}
import scala.io.Source
object CodeGenerator {
def fromStdin = fromSource(Source.stdin)
def fromString(src: String) = fromSource(Source.fromString(src))
def fromSource(ast: Source) = {
val vars = ... |
Preserve the algorithm and functionality while converting the code from Python to Scala. | import random
def MillerRabinPrimalityTest(number):
if number == 2:
return True
elif number == 1 or number % 2 == 0:
return False
oddPartOfNumber = number - 1
timesTwoDividNumber = 0
while oddPartOfNumber % 2 == 0:
oddPartOfNumbe... |
import java.math.BigInteger
const val MAX = 20
val bigOne = BigInteger.ONE
val bigTwo = 2.toBigInteger()
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
... |
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. | import random
def MillerRabinPrimalityTest(number):
if number == 2:
return True
elif number == 1 or number % 2 == 0:
return False
oddPartOfNumber = number - 1
timesTwoDividNumber = 0
while oddPartOfNumber % 2 == 0:
oddPartOfNumbe... |
import java.math.BigInteger
const val MAX = 20
val bigOne = BigInteger.ONE
val bigTwo = 2.toBigInteger()
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
... |
Translate this program into Scala but keep the logic exactly as in Python. | LIMIT = 1_000_035
def primes2(limit=LIMIT):
if limit < 2: return []
if limit < 3: return [2]
lmtbf = (limit - 3) // 2
buf = [True] * (lmtbf + 1)
for i in range((int(limit ** 0.5) - 3) // 2 + 1):
if buf[i]:
p = i + i + 3
s = p * (i + 1) + i
buf[s::p] = [Fal... |
fun sieve(lim: Int): BooleanArray {
var limit = lim + 1
val c = BooleanArray(limit)
c[0] = true
c[1] = true
var p = 3
while (true) {
val p2 = p * p
if (p2 >= limit) break
for (i in p2 until limit step 2 * p) c[i] = true
while (true) {
p... |
Write the same code in Scala as shown below in Python. | from collections import defaultdict
from itertools import product
from pprint import pprint as pp
cube2n = {x**3:x for x in range(1, 1201)}
sum2cubes = defaultdict(set)
for c1, c2 in product(cube2n, cube2n):
if c1 >= c2: sum2cubes[c1 + c2].add((cube2n[c1], cube2n[c2]))
taxied = sorted((k, v) for k,v in sum2cubes.it... |
import java.util.PriorityQueue
class CubeSum(val x: Long, val y: Long) : Comparable<CubeSum> {
val value: Long = x * x * x + y * y * y
override fun toString() = String.format("%4d^3 + %3d^3", x, y)
override fun compareTo(other: CubeSum) = value.compareTo(other.value)
}
class SumIterator : Iterator<Cu... |
Keep all operations the same but rewrite the snippet in Scala. | import numpy as np
def primesfrom2to(n):
sieve = np.ones(n//3 + (n%6==2), dtype=np.bool)
sieve[0] = False
for i in range(int(n**0.5)//3+1):
if sieve[i]:
k=3*i+1|1
sieve[ ((k*k)//3) ::2*k] = False
sieve[(k*k+4*k-2*k*(i&1))//3::2*k] = False
... | private const val MAX = 10000000 + 1000
private val primes = BooleanArray(MAX)
fun main() {
sieve()
println("First 36 strong primes:")
displayStrongPrimes(36)
for (n in intArrayOf(1000000, 10000000)) {
System.out.printf("Number of strong primes below %,d = %,d%n", n, strongPrimesBelow(n))
... |
Change the programming language of this snippet from Python to Scala without modifying what it does. | from itertools import islice
def lfact():
yield 0
fact, summ, n = 1, 0, 1
while 1:
fact, summ, n = fact*n, summ + fact, n + 1
yield summ
print('first 11:\n %r' % [lf for i, lf in zip(range(11), lfact())])
print('20 through 110 (inclusive) by tens:')
for lf in islice(lfact(), 20, 111, 10)... |
import java.math.BigInteger
fun leftFactorial(n: Int): BigInteger {
if (n == 0) return BigInteger.ZERO
var fact = BigInteger.ONE
var sum = fact
for (i in 1 until n) {
fact *= BigInteger.valueOf(i.toLong())
sum += fact
}
return sum
}
fun main(args: Array<String... |
Generate a Scala translation of this Python snippet without changing its computational steps. | from itertools import islice
def lfact():
yield 0
fact, summ, n = 1, 0, 1
while 1:
fact, summ, n = fact*n, summ + fact, n + 1
yield summ
print('first 11:\n %r' % [lf for i, lf in zip(range(11), lfact())])
print('20 through 110 (inclusive) by tens:')
for lf in islice(lfact(), 20, 111, 10)... |
import java.math.BigInteger
fun leftFactorial(n: Int): BigInteger {
if (n == 0) return BigInteger.ZERO
var fact = BigInteger.ONE
var sum = fact
for (i in 1 until n) {
fact *= BigInteger.valueOf(i.toLong())
sum += fact
}
return sum
}
fun main(args: Array<String... |
Keep all operations the same but rewrite the snippet in Scala. | from sympy import primerange
def strange_triplets(mx: int = 30) -> None:
primes = list(primerange(0, mx))
primes3 = set(primerange(0, 3 * mx))
for i, n in enumerate(primes):
for j, m in enumerate(primes[i + 1:], i + 1):
for p in primes[j + 1:]:
if n + m + p in primes3:
... | val primeStream5 = LazyList.from(5, 6)
.flatMap(n => Seq(n, n + 2))
.filter(p => (5 to math.sqrt(p).floor.toInt by 6).forall(a => p % a > 0 && p % (a + 2) > 0))
val primes = LazyList(2, 3) ++ primeStream5
def isPrime(n: Int): Boolean =
if (n < 5) (n | 1) == 3
else primes.takeWhile(_ <= math.sqrt(n)).... |
Port the provided Python code into Scala while preserving the original functionality. | from sympy import primerange
def strange_triplets(mx: int = 30) -> None:
primes = list(primerange(0, mx))
primes3 = set(primerange(0, 3 * mx))
for i, n in enumerate(primes):
for j, m in enumerate(primes[i + 1:], i + 1):
for p in primes[j + 1:]:
if n + m + p in primes3:
... | val primeStream5 = LazyList.from(5, 6)
.flatMap(n => Seq(n, n + 2))
.filter(p => (5 to math.sqrt(p).floor.toInt by 6).forall(a => p % a > 0 && p % (a + 2) > 0))
val primes = LazyList(2, 3) ++ primeStream5
def isPrime(n: Int): Boolean =
if (n < 5) (n | 1) == 3
else primes.takeWhile(_ <= math.sqrt(n)).... |
Write a version of this Python function in Scala with identical behavior. | Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> from sympy import isprime
>>> [x for x in range(101,500)
if isprime(sum(int(c) for c in str(x)[:2])) and
isprime(sum(int(c) for c in str(x)[1:]))]
[111, ... | val p = arrayOf(
false, false, true, true, false,
true, false, true, false, false,
false, true, false, true, false,
false, false, true, false
)
fun isStrange(n: Long): Boolean {
if (n < 10) {
return false
}
var nn = n
while (nn >= 10) {
if (!p[(nn % 10 + (nn / 10) % 10)... |
Can you help me rewrite this code in Scala instead of Python, keeping it the same logically? | Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> from sympy import isprime
>>> [x for x in range(101,500)
if isprime(sum(int(c) for c in str(x)[:2])) and
isprime(sum(int(c) for c in str(x)[1:]))]
[111, ... | val p = arrayOf(
false, false, true, true, false,
true, false, true, false, false,
false, true, false, true, false,
false, false, true, false
)
fun isStrange(n: Long): Boolean {
if (n < 10) {
return false
}
var nn = n
while (nn >= 10) {
if (!p[(nn % 10 + (nn / 10) % 10)... |
Produce a language-to-language conversion: from Python to Scala, same semantics. | def MagicSquareDoublyEven(order):
sq = [range(1+n*order,order + (n*order)+1) for n in range(order) ]
n1 = order/4
for r in range(n1):
r1 = sq[r][n1:-n1]
r2 = sq[order -r - 1][n1:-n1]
r1.reverse()
r2.reverse()
sq[r][n1:-n1] = r2
sq[order -r - 1][n1:-n1] = r1
... |
fun magicSquareDoublyEven(n: Int): Array<IntArray> {
if ( n < 4 || n % 4 != 0)
throw IllegalArgumentException("Base must be a positive multiple of 4")
val bits = 0b1001_0110_0110_1001
val size = n * n
val mult = n / 4
val result = Array(n) { IntArray(n) }
var i = 0
for (r ... |
Generate an equivalent Scala version of this Python code. |
pal = [0] * 128
r = 42
g = 84
b = 126
rd = gd = bd = False
def setup():
global buffer
size(600, 600)
frameRate(25)
buffer = [None] * width * height
for x in range(width):
for y in range(width):
value = int(((128 + (128 * sin(x / 32.0)))
+ (128 + (128 *... |
import java.awt.*
import java.awt.image.BufferedImage
import javax.swing.*
class PlasmaEffect : JPanel() {
private val plasma: Array<FloatArray>
private var hueShift = 0.0f
private val img: BufferedImage
init {
val dim = Dimension(640, 640)
preferredSize = dim
background = Co... |
Write a version of this Python function in Scala with identical behavior. | import math
def SquareFree ( _number ) :
max = (int) (math.sqrt ( _number ))
for root in range ( 2, max+1 ):
if 0 == _number % ( root * root ):
return False
return True
def ListSquareFrees( _start, _end ):
count = 0
for i in range ( _start, _end+1 ):
if True == SquareFree( i ):
print ( "{}\t".fo... |
import kotlin.math.sqrt
fun sieve(limit: Long): List<Long> {
val primes = mutableListOf(2L)
val c = BooleanArray(limit.toInt() + 1)
var p = 3
while (true) {
val p2 = p * p
if (p2 > limit) break
for (i in p2..limit step 2L * p) c[i.toInt()] = true
do { p += 2 } wh... |
Maintain the same structure and functionality when rewriting this code in Scala. | class DigitSumer :
def __init__(self):
sumdigit = lambda n : sum( map( int,str( n )))
self.t = [sumdigit( i ) for i in xrange( 10000 )]
def __call__ ( self,n ):
r = 0
while n >= 10000 :
n,q = divmod( n,10000 )
r += self.t[q]
return r + self.t[n]
... | private const val MC = 103 * 1000 * 10000 + 11 * 9 + 1
private val SV = BooleanArray(MC + 1)
private fun sieve() {
val dS = IntArray(10000)
run {
var a = 9
var i = 9999
while (a >= 0) {
for (b in 9 downTo 0) {
var c = 9
val s = a + b
... |
Maintain the same structure and functionality when rewriting this code in Scala. | from sys import argv
unit2mult = {"arshin": 0.7112, "centimeter": 0.01, "diuym": 0.0254,
"fut": 0.3048, "kilometer": 1000.0, "liniya": 0.00254,
"meter": 1.0, "milia": 7467.6, "piad": 0.1778,
"sazhen": 2.1336, "tochka": 0.000254, "vershok": 0.04445,... |
fun cls() = ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor()
fun main(args: Array<String>) {
val units = listOf("tochka", "liniya", "dyuim", "vershok", "piad", "fut",
"arshin", "sazhen", "versta", "milia",
"centimeter", "meter", "kilometer")
val ... |
Convert this Python snippet to Scala and keep its semantics consistent. | def quad(top=2200):
r = [False] * top
ab = [False] * (top * 2)**2
for a in range(1, top):
for b in range(a, top):
ab[a * a + b * b] = True
s = 3
for c in range(1, top):
s1, s, s2 = s, s + 2, s + 2
for d in range(c + 1, top):
if ab[s1]:
... |
const val MAX = 2200
const val MAX2 = MAX * MAX - 1
fun main(args: Array<String>) {
val found = BooleanArray(MAX + 1)
val p2 = IntArray(MAX + 1) { it * it }
val dc = mutableMapOf<Int, MutableList<Int>>()
for (d in 1..MAX) {
for (c in 1 until d) {
val diff = p2[d] - ... |
Convert this Python snippet to Scala and keep its semantics consistent. |
from collections import Counter
def decompose_sum(s):
return [(a,s-a) for a in range(2,int(s/2+1))]
all_pairs = set((a,b) for a in range(2,100) for b in range(a+1,100) if a+b<100)
product_counts = Counter(c*d for c,d in all_pairs)
unique_products = set((a,b) for a,b in all_pairs if product_counts[a*b]==1)
s_... |
data class P(val x: Int, val y: Int, val sum: Int, val prod: Int)
fun main(args: Array<String>) {
val candidates = mutableListOf<P>()
for (x in 2..49) {
for (y in x + 1..100 - x) {
candidates.add(P(x, y, x + y, x * y))
}
}
val sums = candidates.groupBy { it.sum }
... |
Produce a functionally identical Scala code for the snippet given in Python. | "Generate a short Superpermutation of n characters A... as a string using various algorithms."
from __future__ import print_function, division
from itertools import permutations
from math import factorial
import string
import datetime
import gc
MAXN = 7
def s_perm0(n):
allchars = string.ascii_uppercase... |
const val MAX = 12
var sp = CharArray(0)
val count = IntArray(MAX)
var pos = 0
fun factSum(n: Int): Int {
var s = 0
var x = 0
var f = 1
while (x < n) {
f *= ++x
s += f
}
return s
}
fun r(n: Int): Boolean {
if (n == 0) return false
val c = sp[pos - n]
if (--co... |
Write the same code in Scala as shown below in Python. | >>> def isint(f):
return complex(f).imag == 0 and complex(f).real.is_integer()
>>> [isint(f) for f in (1.0, 2, (3.0+0.0j), 4.1, (3+4j), (5.6+0j))]
[True, True, True, False, False, False]
>>>
...
>>> isint(25.000000)
True
>>> isint(24.999999)
False
>>> isint(25.000100)
False
>>> isint(-2.1e120)
True
>>> isint(-5... |
import java.math.BigInteger
import java.math.BigDecimal
fun Double.isLong(tolerance: Double = 0.0) =
(this - Math.floor(this)) <= tolerance || (Math.ceil(this) - this) <= tolerance
fun BigDecimal.isBigInteger() =
try {
this.toBigIntegerExact()
true
}
catch (ex: ArithmeticException) ... |
Maintain the same structure and functionality when rewriting this code in Scala. | from __future__ import print_function
from time import sleep
last_idle = last_total = 0
while True:
with open('/proc/stat') as f:
fields = [float(column) for column in f.readline().strip().split()[1:]]
idle, total = fields[3], sum(fields)
idle_delta, total_delta = idle - last_idle, total - last_to... |
import java.io.FileReader
import java.io.BufferedReader
fun main(args: Array<String>) {
println("CPU usage % at 1 second intervals:\n")
var prevIdleTime = 0L
var prevTotalTime = 0L
repeat(10) {
val br = BufferedReader(FileReader("/proc/stat"))
val firstLine = br.readLine().drop(5)
... |
Convert the following code from Python to Scala, ensuring the logic remains intact. | range17 = range(17)
a = [['0'] * 17 for i in range17]
idx = [0] * 4
def find_group(mark, min_n, max_n, depth=1):
if (depth == 4):
prefix = "" if (mark == '1') else "un"
print("Fail, found totally {}connected group:".format(prefix))
for i in range(4):
print(idx[i])
retur... |
val a = Array(17) { IntArray(17) }
val idx = IntArray(4)
fun findGroup(type: Int, minN: Int, maxN: Int, depth: Int): Boolean {
if (depth == 4) {
print("\nTotally ${if (type != 0) "" else "un"}connected group:")
for (i in 0 until 4) print(" ${idx[i]}")
println()
return true
}
... |
Produce a language-to-language conversion: from Python to Scala, same semantics. | primes =[]
sp =[]
usp=[]
n = 10000000
if 2<n:
primes.append(2)
for i in range(3,n+1,2):
for j in primes:
if(j>i/2) or (j==primes[-1]):
primes.append(i)
if((i-1)/2) in primes:
sp.append(i)
break
else:
usp.append(i)
... |
fun sieve(limit: Int): BooleanArray {
val c = BooleanArray(limit + 1)
c[0] = true
c[1] = true
for (i in 4..limit step 2) c[i] = true
var p = 3
while (true) {
val p2 = p * p
if (p2 > limit) break
for (i in p2..limit step 2 * p) c[i] = true
while (true... |
Generate a Scala translation of this Python snippet without changing its computational steps. | from collections import defaultdict
def hashJoin(table1, index1, table2, index2):
h = defaultdict(list)
for s in table1:
h[s[index1]].append(s)
return [(s, r) for r in table2 for s in h[r[index2]]]
table1 = [(27, "Jonah"),
(18, "Alan"),
(28, "Glory"),
(18, "... | data class A(val age: Int, val name: String)
data class B(val character: String, val nemesis: String)
data class C(val rowA: A, val rowB: B)
fun hashJoin(tableA: List<A>, tableB: List<B>): List<C> {
val mm = tableB.groupBy { it.character }
val tableC = mutableListOf<C>()
for (a in tableA) {
val v... |
Transform the following Python implementation into Scala, maintaining the same output and logic. |
from itertools import product
def replicateM(n):
def rep(m):
def go(x):
return [[]] if 1 > x else (
liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))
)
return go(n)
return lambda m: rep(m)
def main():
print(
fTable(main.__doc__ ... |
fun main(args: Array<String>) {
val n = 3
val values = charArrayOf('A', 'B', 'C', 'D')
val k = values.size
val decide = fun(pc: CharArray) = pc[0] == 'B' && pc[1] == 'C'
val pn = IntArray(n)
val pc = CharArray(n)
while (true) {
for ((i, x) in pn.withIndex()) pc[i] = ... |
Can you help me rewrite this code in Scala instead of Python, keeping it the same logically? |
from itertools import product
def replicateM(n):
def rep(m):
def go(x):
return [[]] if 1 > x else (
liftA2List(lambda a, b: [a] + b)(m)(go(x - 1))
)
return go(n)
return lambda m: rep(m)
def main():
print(
fTable(main.__doc__ ... |
fun main(args: Array<String>) {
val n = 3
val values = charArrayOf('A', 'B', 'C', 'D')
val k = values.size
val decide = fun(pc: CharArray) = pc[0] == 'B' && pc[1] == 'C'
val pn = IntArray(n)
val pc = CharArray(n)
while (true) {
for ((i, x) in pn.withIndex()) pc[i] = ... |
Port the provided Python code into Scala while preserving the original functionality. | import time
import os
seconds = input("Enter a number of seconds: ")
sound = input("Enter an mp3 filename: ")
time.sleep(float(seconds))
os.startfile(sound + ".mp3")
|
import javafx.application.Application
import javafx.scene.media.Media
import javafx.scene.media.MediaPlayer
import javafx.stage.Stage
import java.io.File
import java.util.concurrent.TimeUnit
class AudioAlarm : Application() {
override fun start(primaryStage: Stage) {
with (primaryStage) {
ti... |
Preserve the algorithm and functionality while converting the code from Python to Scala. | def run_vm(data_size)
int stack[data_size + 1000]
set stack[0..data_size - 1] to 0
int pc = 0
while True:
op = code[pc]
pc += 1
if op == FETCH:
stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);
pc += word_size
elif op == STORE:
... | package xyz.hyperreal.rosettacodeCompiler
import java.io.{BufferedReader, FileReader, Reader, StringReader}
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
object VirtualMachine {
private object Opcodes {
val FETCH: Byte = 0
val STORE: Byte = 1
val PUSH: Byte = 2
val J... |
Convert this Python snippet to Scala and keep its semantics consistent. | def run_vm(data_size)
int stack[data_size + 1000]
set stack[0..data_size - 1] to 0
int pc = 0
while True:
op = code[pc]
pc += 1
if op == FETCH:
stack.append(stack[bytes_to_int(code[pc:pc+word_size])[0]]);
pc += word_size
elif op == STORE:
... | package xyz.hyperreal.rosettacodeCompiler
import java.io.{BufferedReader, FileReader, Reader, StringReader}
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
object VirtualMachine {
private object Opcodes {
val FETCH: Byte = 0
val STORE: Byte = 1
val PUSH: Byte = 2
val J... |
Convert the following code from Python to Scala, ensuring the logic remains intact. |
import time
print "\033[?1049h\033[H"
print "Alternate buffer!"
for i in xrange(5, 0, -1):
print "Going back in:", i
time.sleep(1)
print "\033[?1049l"
|
const val ESC = "\u001B"
fun main(args: Array<String>) {
print("$ESC[?1049h$ESC[H")
println("Alternate screen buffer")
for(i in 5 downTo 1) {
print("\rGoing back in $i second${if (i != 1) "s" else ""}...")
Thread.sleep(1000)
}
print("$ESC[?1049l")
}
|
Translate the given Python code snippet into Scala without altering its behavior. | import random
def is_probable_prime(n,k):
if n==0 or n==1:
return False
if n==2:
return True
if n % 2 == 0:
return False
s = 0
d = n-1
while True:
quotient, remainder = divmod(d, 2)
if remainder == 1:
break
s += 1
d = quo... |
import java.math.BigInteger
fun nextLeftTruncatablePrimes(n: BigInteger, radix: Int, certainty: Int): List<BigInteger> {
val probablePrimes = mutableListOf<BigInteger>()
val baseString = if (n == BigInteger.ZERO) "" else n.toString(radix)
for (i in 1 until radix) {
val p = BigInteger(i.toString(r... |
Port the provided Python code into Scala while preserving the original functionality. | import pyttsx
engine = pyttsx.init()
engine.say("It was all a dream.")
engine.runAndWait()
|
import kotlinx.cinterop.*
import platform.posix.*
fun talk(s: String) {
val pid = fork()
if (pid < 0) {
perror("fork")
exit(1)
}
if (pid == 0) {
execlp("espeak", "espeak", s, null)
perror("espeak")
_exit(1)
}
memScoped {
val status = alloc<IntVar>()
... |
Convert this Python block to Scala, preserving its control flow and logic. | def builtinsort(x):
x.sort()
def partition(seq, pivot):
low, middle, up = [], [], []
for x in seq:
if x < pivot:
low.append(x)
elif x == pivot:
middle.append(x)
else:
up.append(x)
return low, middle, up
import random
def qsortranpart(seq):
size = le... |
import java.util.Random
import kotlin.system.measureNanoTime
typealias Sorter = (IntArray) -> Unit
val rand = Random()
fun onesSeq(n: Int) = IntArray(n) { 1 }
fun ascendingSeq(n: Int) = shuffledSeq(n).sorted().toIntArray()
fun shuffledSeq(n: Int) = IntArray(n) { 1 + rand.nextInt(10 * n) }
fun bubbleSort(a: IntA... |
Translate the given Python code snippet into Scala without altering its behavior. |
from __future__ import division, print_function
from itertools import permutations, combinations, product, \
chain
from pprint import pprint as pp
from fractions import Fraction as F
import random, ast, re
import sys
if sys.version_info[0] < 3:
input = raw_input
from ... |
import java.util.Random
const val N_CARDS = 4
const val SOLVE_GOAL = 24
const val MAX_DIGIT = 9
class Frac(val num: Int, val den: Int)
enum class OpType { NUM, ADD, SUB, MUL, DIV }
class Expr(
var op: OpType = OpType.NUM,
var left: Expr? = null,
var right: Expr? = null,
var value: Int = 0... |
Transform the following Python implementation into Scala, maintaining the same output and logic. |
from __future__ import division, print_function
from itertools import permutations, combinations, product, \
chain
from pprint import pprint as pp
from fractions import Fraction as F
import random, ast, re
import sys
if sys.version_info[0] < 3:
input = raw_input
from ... |
import java.util.Random
const val N_CARDS = 4
const val SOLVE_GOAL = 24
const val MAX_DIGIT = 9
class Frac(val num: Int, val den: Int)
enum class OpType { NUM, ADD, SUB, MUL, DIV }
class Expr(
var op: OpType = OpType.NUM,
var left: Expr? = null,
var right: Expr? = null,
var value: Int = 0... |
Change the following Python code into Scala without altering its purpose. | k8 = [ 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 ]
k7 = [ 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 ]
k6 = [ 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 ]
k5 = [ 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 ]
k4 = [ 2, 12, 4, 1, 7, 10, ... |
fun Byte.toUInt() = java.lang.Byte.toUnsignedInt(this)
fun Byte.toULong() = java.lang.Byte.toUnsignedLong(this)
fun Int.toULong() = java.lang.Integer.toUnsignedLong(this)
val s = arrayOf(
byteArrayOf( 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3),
byteArrayOf(14, 11, 4, 12, 6, 13, 15, ... |
Rewrite the snippet below in Scala so it works the same as the original Python code. | from math import hypot, pi, cos, sin
from PIL import Image
def hough(im, ntx=460, mry=360):
"Calculate Hough transform."
pim = im.load()
nimx, mimy = im.size
mry = int(mry/2)*2
him = Image.new("L", (ntx, mry), 255)
phim = him.load()
rmax = hypot(nimx, mimy)
dr = rmax / (mry/... | import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
internal class ArrayData(val dataArray: IntArray, val width: Int, val height: Int) {
constructor(width: Int, height: Int) : this(IntArray(width * height), width, height)
operator fun get(x: Int, y: Int) = dataArray[y * width... |
Change the programming language of this snippet from Python to Scala without modifying what it does. | environments = [{'cnt':0, 'seq':i+1} for i in range(12)]
code =
while any(env['seq'] > 1 for env in environments):
for env in environments:
exec(code, globals(), env)
print()
print('Counts')
for env in environments:
print('% 4d' % env['cnt'], end='')
print()
|
class Environment(var seq: Int, var count: Int)
const val JOBS = 12
val envs = List(JOBS) { Environment(it + 1, 0) }
var seq = 0
var count = 0
var currId = 0
fun switchTo(id: Int) {
if (id != currId) {
envs[currId].seq = seq
envs[currId].count = count
currId = id
}
seq... |
Can you help me rewrite this code in Scala instead of Python, keeping it the same logically? | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.