Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Transform the following C++ implementation into Scala, maintaining the same output and logic.
#include <cmath> #include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ...
import kotlin.math.pow private fun divisorCount(n: Long): Long { var nn = n var total: Long = 1 while (nn and 1 == 0L) { ++total nn = nn shr 1 } var p: Long = 3 while (p * p <= nn) { var count = 1L while (nn % p == 0L) { ++count ...
Can you help me rewrite this code in Scala instead of C++, keeping it the same logically?
#include <cmath> #include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ...
import kotlin.math.pow private fun divisorCount(n: Long): Long { var nn = n var total: Long = 1 while (nn and 1 == 0L) { ++total nn = nn shr 1 } var p: Long = 3 while (p * p <= nn) { var count = 1L while (nn % p == 0L) { ++count ...
Convert the following code from C++ to Scala, ensuring the logic remains intact.
#include <deque> #include <algorithm> #include <ostream> #include <iterator> namespace cards { class card { public: enum pip_type { two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace, pip_count }; enum suite_type { hearts, spades, diamonds, clubs, suite_count }; ...
const val FACES = "23456789TJQKA" const val SUITS = "shdc" fun createDeck(): List<String> { val cards = mutableListOf<String>() FACES.forEach { face -> SUITS.forEach { suit -> cards.add("$face$suit") } } return cards } fun dealTopDeck(deck: List<String>, n: Int) = deck.take(n) fun dealBottomDeck(deck: Li...
Port the following code from C++ to Scala with equivalent syntax and logic.
#include <cassert> #include <iostream> #include <vector> class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) contin...
fun totient(n: Int): Int { var tot = n var nn = n var i = 2 while (i * i <= nn) { if (nn % i == 0) { while (nn % i == 0) nn /= i tot -= tot / i } if (i == 2) i = 1 i += 2 } if (nn > 1) tot -= tot / nn return tot } fun main() { va...
Preserve the algorithm and functionality while converting the code from C++ to Scala.
#include <cassert> #include <iostream> #include <vector> class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) contin...
fun totient(n: Int): Int { var tot = n var nn = n var i = 2 while (i * i <= nn) { if (nn % i == 0) { while (nn % i == 0) nn /= i tot -= tot / i } if (i == 2) i = 1 i += 2 } if (nn > 1) tot -= tot / nn return tot } fun main() { va...
Transform the following C++ implementation into Scala, maintaining the same output and logic.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class unsigned_lah_numbers { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer unsigned_lah_numbers::get(int n, int k) { if (k == ...
import java.math.BigInteger fun factorial(n: BigInteger): BigInteger { if (n == BigInteger.ZERO) return BigInteger.ONE if (n == BigInteger.ONE) return BigInteger.ONE var prod = BigInteger.ONE var num = n while (num > BigInteger.ONE) { prod *= num num-- } return prod } fun l...
Write the same code in Scala as shown below in C++.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class unsigned_lah_numbers { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer unsigned_lah_numbers::get(int n, int k) { if (k == ...
import java.math.BigInteger fun factorial(n: BigInteger): BigInteger { if (n == BigInteger.ZERO) return BigInteger.ONE if (n == BigInteger.ONE) return BigInteger.ONE var prod = BigInteger.ONE var num = n while (num > BigInteger.ONE) { prod *= num num-- } return prod } fun l...
Write the same code in Scala as shown below in C++.
#include <iostream> #include <map> #include <tuple> #include <vector> using namespace std; pair<int, int> twoSum(vector<int> numbers, int sum) { auto m = map<int, int>(); for (size_t i = 0; i < numbers.size(); ++i) { auto key = sum - numbers[i]; if (m.find(key) != m.end()) { return make_pair(m[key], i); ...
fun twoSum(a: IntArray, targetSum: Int): Pair<Int, Int>? { if (a.size < 2) return null var sum: Int for (i in 0..a.size - 2) { if (a[i] <= targetSum) { for (j in i + 1..a.size - 1) { sum = a[i] + a[j] if (sum == targetSum) return Pair(i, j) ...
Produce a functionally identical Scala code for the snippet given in C++.
#include <iostream> #include <map> #include <tuple> #include <vector> using namespace std; pair<int, int> twoSum(vector<int> numbers, int sum) { auto m = map<int, int>(); for (size_t i = 0; i < numbers.size(); ++i) { auto key = sum - numbers[i]; if (m.find(key) != m.end()) { return make_pair(m[key], i); ...
fun twoSum(a: IntArray, targetSum: Int): Pair<Int, Int>? { if (a.size < 2) return null var sum: Int for (i in 0..a.size - 2) { if (a[i] <= targetSum) { for (j in i + 1..a.size - 1) { sum = a[i] + a[j] if (sum == targetSum) return Pair(i, j) ...
Produce a language-to-language conversion: from C++ to Scala, same semantics.
#include <algorithm> #include <cassert> #include <iostream> #include <iterator> #include <vector> template <typename iterator> void cocktail_shaker_sort(iterator begin, iterator end) { if (begin == end) return; for (--end; begin < end; ) { iterator new_begin = end; iterator new_end = b...
fun <T> swap(array: Array<T>, i: Int, j: Int) { val temp = array[i] array[i] = array[j] array[j] = temp } fun <T> cocktailSort(array: Array<T>) where T : Comparable<T> { var begin = 0 var end = array.size if (end == 0) { return } --end while (begin < end) { var newBe...
Produce a language-to-language conversion: from C++ to Scala, same semantics.
#include <iostream> #include <cstdint> #include "prime_sieve.hpp" typedef uint32_t integer; int count_digits(integer n) { int digits = 0; for (; n > 0; ++digits) n /= 10; return digits; } integer change_digit(integer n, int index, int new_digit) { integer p = 1; integer changed = 0; ...
private const val MAX = 10000000 private val primes = BooleanArray(MAX) fun main() { sieve() println("First 35 unprimeable numbers:") displayUnprimeableNumbers(35) val n = 600 println() println("The ${n}th unprimeable number = ${nthUnprimeableNumber(n)}") println() val lowest = genLowes...
Change the following C++ code into Scala without altering its purpose.
#include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <string> #include <gmpxx.h> bool is_probably_prime(const mpz_class& n) { return mpz_probab_prime_p(n.get_mpz_t(), 3) != 0; } bool is_prime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2...
import java.math.BigInteger fun digitSum(bi: BigInteger): Int { var bi2 = bi var sum = 0 while (bi2 > BigInteger.ZERO) { val dr = bi2.divideAndRemainder(BigInteger.TEN) sum += dr[1].toInt() bi2 = dr[0] } return sum } fun main() { val fiveK = BigInteger.valueOf(5_000) ...
Write the same code in Scala as shown below in C++.
#include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <string> #include <gmpxx.h> bool is_probably_prime(const mpz_class& n) { return mpz_probab_prime_p(n.get_mpz_t(), 3) != 0; } bool is_prime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2...
import java.math.BigInteger fun digitSum(bi: BigInteger): Int { var bi2 = bi var sum = 0 while (bi2 > BigInteger.ZERO) { val dr = bi2.divideAndRemainder(BigInteger.TEN) sum += dr[1].toInt() bi2 = dr[0] } return sum } fun main() { val fiveK = BigInteger.valueOf(5_000) ...
Rewrite this program in Scala while keeping its functionality equivalent to the C++ version.
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) ...
fun primeDigitsSum13(n: Int): Boolean { var nn = n var sum = 0 while (nn > 0) { val r = nn % 10 if (r != 2 && r != 3 && r != 5 && r != 7) { return false } nn /= 10 sum += r } return sum == 13 } fun main() { var c = 0 for (i in 1 until...
Translate the given C++ code snippet into Scala without altering its behavior.
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) ...
fun primeDigitsSum13(n: Int): Boolean { var nn = n var sum = 0 while (nn > 0) { val r = nn % 10 if (r != 2 && r != 3 && r != 5 && r != 7) { return false } nn /= 10 sum += r } return sum == 13 } fun main() { var c = 0 for (i in 1 until...
Please provide an equivalent version of this C++ code in Scala.
#include <array> #include <iostream> #include <list> #include <map> #include <vector> int main() { auto myNumbers = std::vector<std::string>{"one", "two", "three", "four"}; auto myColors = std::vector<std::string>{"red", "green", "blue"}; auto myArray = std::array<std::vector<std::string>, 2>{myNumber...
import java.io.Serializable import java.io.ByteArrayOutputStream import java.io.ByteArrayInputStream import java.io.ObjectOutputStream import java.io.ObjectInputStream fun <T : Serializable> deepCopy(obj: T?): T? { if (obj == null) return null val baos = ByteArrayOutputStream() val oos = ObjectOutputStr...
Write a version of this C++ function in Scala with identical behavior.
#include <array> #include <iostream> #include <list> #include <map> #include <vector> int main() { auto myNumbers = std::vector<std::string>{"one", "two", "three", "four"}; auto myColors = std::vector<std::string>{"red", "green", "blue"}; auto myArray = std::array<std::vector<std::string>, 2>{myNumber...
import java.io.Serializable import java.io.ByteArrayOutputStream import java.io.ByteArrayInputStream import java.io.ObjectOutputStream import java.io.ObjectInputStream fun <T : Serializable> deepCopy(obj: T?): T? { if (obj == null) return null val baos = ByteArrayOutputStream() val oos = ObjectOutputStr...
Convert this C++ snippet to Scala and keep its semantics consistent.
#include <cstdint> #include <algorithm> #include <iostream> #include <sstream> #include <gmpxx.h> typedef mpz_class integer; bool is_prime(const integer& n, int reps = 50) { return mpz_probab_prime_p(n.get_mpz_t(), reps); } std::string to_string(const integer& n) { std::ostringstream out; out << n; r...
import java.math.BigInteger val SMALL_PRIMES = listOf( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 2...
Port the provided C++ code into Scala while preserving the original functionality.
#include <algorithm> template<typename ForwardIterator> void permutation_sort(ForwardIterator begin, ForwardIterator end) { while (std::next_permutation(begin, end)) { } }
fun <T : Comparable<T>> isSorted(list: List<T>): Boolean { val size = list.size if (size < 2) return true for (i in 1 until size) { if (list[i] < list[i - 1]) return false } return true } fun <T : Comparable<T>> permute(input: List<T>): List<List<T>> { if (input.size == 1) return list...
Keep all operations the same but rewrite the snippet in Scala.
#include <iostream> #include <math.h> unsigned long long root(unsigned long long base, unsigned int n) { if (base < 2) return base; if (n == 0) return 1; unsigned int n1 = n - 1; unsigned long long n2 = n; unsigned long long n3 = n1; unsigned long long c = 1; auto d = (n3 + base) / n2; auto e = (n3 * d + base...
import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigTwo = BigInteger.valueOf(2L) fun BigInteger.iRoot(n: Int): BigInteger { require(this >= bigZero && n > 0) if (this < bigTwo) return this val n1 = n - 1 val n2 = BigInteger.valueOf(n.toLong()) val n3 = ...
Rewrite this program in Scala while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <math.h> unsigned long long root(unsigned long long base, unsigned int n) { if (base < 2) return base; if (n == 0) return 1; unsigned int n1 = n - 1; unsigned long long n2 = n; unsigned long long n3 = n1; unsigned long long c = 1; auto d = (n3 + base) / n2; auto e = (n3 * d + base...
import java.math.BigInteger val bigZero = BigInteger.ZERO val bigOne = BigInteger.ONE val bigTwo = BigInteger.valueOf(2L) fun BigInteger.iRoot(n: Int): BigInteger { require(this >= bigZero && n > 0) if (this < bigTwo) return this val n1 = n - 1 val n2 = BigInteger.valueOf(n.toLong()) val n3 = ...
Keep all operations the same but rewrite the snippet in Scala.
#include <iostream> bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) ...
fun isPrime(n: Long): Boolean { if (n < 2) { return false } if (n % 2 == 0L) { return n == 2L } if (n % 3 == 0L) { return n == 3L } var p = 5 while (p * p <= n) { if (n % p == 0L) { return false } p += 2 if (n % p == 0L...
Please provide an equivalent version of this C++ code in Scala.
#include <iostream> bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) ...
fun isPrime(n: Long): Boolean { if (n < 2) { return false } if (n % 2 == 0L) { return n == 2L } if (n % 3 == 0L) { return n == 3L } var p = 5 while (p * p <= n) { if (n % p == 0L) { return false } p += 2 if (n % p == 0L...
Rewrite this program in Scala while keeping its functionality equivalent to the C++ version.
#include <windows.h> #include <iostream> #include <string> using namespace std; class lastSunday { public: lastSunday() { m[0] = "JANUARY: "; m[1] = "FEBRUARY: "; m[2] = "MARCH: "; m[3] = "APRIL: "; m[4] = "MAY: "; m[5] = "JUNE: "; m[6] = "JULY: "; m[7] = "AUGUST: ";...
import java.util.* fun main(args: Array<String>) { print("Enter a year : ") val year = readLine()!!.toInt() println("The last Sundays of each month in $year are as follows:") val calendar = GregorianCalendar(year, 0, 31) for (month in 1..12) { val daysInMonth = calendar.getActualMaximum(...
Change the programming language of this snippet from C++ to Scala without modifying what it does.
#include <windows.h> #include <iostream> #include <string> using namespace std; class lastSunday { public: lastSunday() { m[0] = "JANUARY: "; m[1] = "FEBRUARY: "; m[2] = "MARCH: "; m[3] = "APRIL: "; m[4] = "MAY: "; m[5] = "JUNE: "; m[6] = "JULY: "; m[7] = "AUGUST: ";...
import java.util.* fun main(args: Array<String>) { print("Enter a year : ") val year = readLine()!!.toInt() println("The last Sundays of each month in $year are as follows:") val calendar = GregorianCalendar(year, 0, 31) for (month in 1..12) { val daysInMonth = calendar.getActualMaximum(...
Translate this program into Scala but keep the logic exactly as in C++.
#include <algorithm> #include <chrono> #include <iostream> #include <random> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it...
typealias matrix = MutableList<MutableList<Int>> fun printSquare(latin: matrix) { for (row in latin) { println(row) } println() } fun latinSquare(n: Int) { if (n <= 0) { println("[]") return } val latin = MutableList(n) { MutableList(n) { it } } latin[0].shuff...
Write a version of this C++ function in Scala with identical behavior.
#include <iostream> #include <vector> int turn(int base, int n) { int sum = 0; while (n != 0) { int rem = n % base; n = n / base; sum += rem; } return sum % base; } void fairshare(int base, int count) { printf("Base %2d:", base); for (int i = 0; i < count; i++) { ...
fun turn(base: Int, n: Int): Int { var sum = 0 var n2 = n while (n2 != 0) { val re = n2 % base n2 /= base sum += re } return sum % base } fun fairShare(base: Int, count: Int) { print(String.format("Base %2d:", base)) for (i in 0 until count) { val t = turn(ba...
Generate a Scala translation of this C++ snippet without changing its computational steps.
#include <functional> #include <iostream> #include <sstream> #include <vector> std::string to(int n, int b) { static auto BASE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; std::stringstream ss; while (n > 0) { auto rem = n % b; n = n / b; ss << BASE[rem]; } auto fwd = ss.str(...
import kotlin.math.abs fun isEsthetic(n: Long, b: Long): Boolean { if (n == 0L) { return false } var i = n % b var n2 = n / b while (n2 > 0) { val j = n2 % b if (abs(i - j) != 1L) { return false } n2 /= b i = j } return true } fun...
Translate this program into Scala but keep the logic exactly as in C++.
#include <iostream> #include <vector> using namespace std; vector<int> UpTo(int n, int offset = 0) { vector<int> retval(n); for (int ii = 0; ii < n; ++ii) retval[ii] = ii + offset; return retval; } struct JohnsonTrotterState_ { vector<int> values_; vector<int> positions_; vector<bool> directions_; int sign...
fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> { val p = IntArray(n) { it } val q = IntArray(n) { it } val d = IntArray(n) { -1 } var sign = 1 val perms = mutableListOf<IntArray>() val signs = mutableListOf<Int>() fun permute(k: Int) { if (k >= n) { ...
Transform the following C++ implementation into Scala, maintaining the same output and logic.
#include <algorithm> #include <ctime> #include <iostream> #include <cstdlib> #include <string> using namespace std; int main() { srand(time(0)); unsigned int attributes_total = 0; unsigned int count = 0; int attributes[6] = {}; int rolls[4] = {}; while(attributes_total < 75 || count ...
import scala.util.Random Random.setSeed(1) def rollDice():Int = { val v4 = Stream.continually(Random.nextInt(6)+1).take(4) v4.sum - v4.min } def getAttributes():Seq[Int] = Stream.continually(rollDice()).take(6) def getCharacter():Seq[Int] = { val attrs = getAttributes() println("generated => " + attrs.mkStri...
Produce a functionally identical Scala code for the snippet given in C++.
#include <iostream> #include <vector> using Sequence = std::vector<int>; std::ostream& operator<<(std::ostream& os, const Sequence& v) { os << "[ "; for (const auto& e : v) { std::cout << e << ", "; } os << "]"; return os; } int next_in_cycle(const Sequence& s, size_t i) { return s[i % s.size()]; } ...
fun IntArray.nextInCycle(index: Int) = this[index % this.size] fun IntArray.kolakoski(len: Int): IntArray { val s = IntArray(len) var i = 0 var k = 0 while (true) { s[i] = this.nextInCycle(k) if (s[k] > 1) { repeat(s[k] - 1) { if (++i == len) return s ...
Maintain the same structure and functionality when rewriting this code in Scala.
#include <iostream> #define MAX 15 using namespace std; int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; } int main() { ...
const val MAX = 15 fun countDivisors(n: Int): Int { var count = 0 var i = 1 while (i * i <= n) { if (n % i == 0) { count += if (i == n / i) 1 else 2 } i++ } return count } fun main() { var seq = IntArray(MAX) println("The first $MAX terms of the sequen...
Ensure the translated Scala code behaves exactly like the original C++ snippet.
#include <iostream> #include <sstream> #include <vector> #include <cmath> #include <algorithm> #include <locale> class Sparkline { public: Sparkline(std::wstring &cs) : charset( cs ){ } virtual ~Sparkline(){ } void print(std::string spark){ const char *delim = "...
internal const val bars = "▁▂▃▄▅▆▇█" internal const val n = bars.length - 1 fun <T: Number> Iterable<T>.toSparkline(): String { var min = Double.MAX_VALUE var max = Double.MIN_VALUE val doubles = map { it.toDouble() } doubles.forEach { i -> when { i < min -> min = i; i > max -> max = i } } val rang...
Write the same algorithm in Scala as shown in this C++ implementation.
#include <vector> #include <list> #include <algorithm> #include <iostream> template <typename T> struct Node { T value; Node* prev_node; }; template <typename Container> Container lis(const Container& values) { using E = typename Container::value_type; using NodePtr = Node<E>*; using ConstNodePtr ...
fun longestIncreasingSubsequence(x: IntArray): IntArray = when (x.size) { 0 -> IntArray(0) 1 -> x else -> { val n = x.size val p = IntArray(n) val m = IntArray(n + 1) var len = 0 for (i in 0 until n) { var...
Keep all operations the same but rewrite the snippet in Scala.
#include <iostream> #include <vector> #include <algorithm> #include <string> template <typename T> void print(const std::vector<T> v) { std::cout << "{ "; for (const auto& e : v) { std::cout << e << " "; } std::cout << "}"; } template <typename T> auto orderDisjointArrayItems(std::vector<T> M, std::vector...
const val NULL = "\u0000" fun orderDisjointList(m: String, n: String): String { val nList = n.split(' ') var p = m for (item in nList) p = p.replaceFirst(item, NULL) val mList = p.split(NULL) val sb = StringBuilder() for (i in 0 until nList.size) sb.append(mList[i], nList[i]) ...
Write the same algorithm in Scala as shown in this C++ implementation.
#include <fstream> #include <iostream> #include <locale> using namespace std; int main(void) { std::locale::global(std::locale("")); std::cout.imbue(std::locale()); ifstream in("input.txt"); wchar_t c; while ((c = in.get()) != in.eof()) wcout<<c; in.close(); return EXIT_...
import java.io.File const val EOF = -1 fun main(args: Array<String>) { val reader = File("input.txt").reader() reader.use { while (true) { val c = reader.read() if (c == EOF) break print(c.toChar()) } } }
Can you help me rewrite this code in Scala instead of C++, keeping it the same logically?
#include "stdafx.h" #include <windows.h> #include <stdlib.h> const int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject(...
import java.util.Random val boxW = 41 val boxH = 37 val pinsBaseW = 19 val nMaxBalls = 55 val centerH = pinsBaseW + (boxW - pinsBaseW * 2 + 1) / 2 - 1 val rand = Random() enum class Cell(val c: Char) { EMPTY(' '), BALL('o'), WALL('|'), CORNER('+'), FLOOR('-'), PIN('.') } ...
Rewrite the snippet below in Scala so it works the same as the original C++ code.
#include <algorithm> #include <iostream> #include <vector> typedef unsigned long long integer; std::vector<integer> get_ancestors(const std::vector<integer>& ancestor, integer n) { std::vector<integer> result; for (integer a = ancestor[n]; a != 0 && a != n; ) { n = a; a = ancestor[n]; ...
const val MAXSUM = 99 fun getPrimes(max: Int): List<Int> { if (max < 2) return emptyList<Int>() val lprimes = mutableListOf(2) outer@ for (x in 3..max step 2) { for (p in lprimes) if (x % p == 0) continue@outer lprimes.add(x) } return lprimes } fun main(args: Array<String>) { ...
Port the provided C++ code into Scala while preserving the original functionality.
#include <iostream> int circlesort(int* arr, int lo, int hi, int swaps) { if(lo == hi) { return swaps; } int high = hi; int low = lo; int mid = (high - low) / 2; while(lo < hi) { if(arr[lo] > arr[hi]) { int temp = arr[lo]; arr[lo] = arr[hi]; a...
fun<T: Comparable<T>> circleSort(array: Array<T>, lo: Int, hi: Int, nSwaps: Int): Int { if (lo == hi) return nSwaps fun swap(array: Array<T>, i: Int, j: Int) { val temp = array[i] array[i] = array[j] array[j] = temp } var high = hi var low = lo val mid = (hi ...
Convert this C++ snippet to Scala and keep its semantics consistent.
#include <iostream> #include <iterator> #include <string> #include <utility> #include <vector> namespace detail { template <typename ForwardIterator> class tokenizer { ForwardIterator _tbegin, _tend, _end; public: tokenizer(ForwardIterator begin, ForwardIterator end) : _tbegin(begin), _tend(begin), _end(end...
object BraceExpansion { fun expand(s: String) = expandR("", s, "") private val r = Regex("""([\\]{2}|[\\][,}{])""") private fun expandR(pre: String, s: String, suf: String) { val noEscape = s.replace(r, " ") var sb = StringBuilder("") var i1 = noEscape.indexOf('{') var i...
Please provide an equivalent version of this C++ code in Scala.
#include <initializer_list> #include <iostream> #include <map> #include <vector> struct Wheel { private: std::vector<char> values; size_t index; public: Wheel() : index(0) { } Wheel(std::initializer_list<char> data) : values(data), index(0) { if (values.size() < 1) { ...
import java.util.Collections import java.util.stream.IntStream object WheelController { private val IS_NUMBER = "[0-9]".toRegex() private const val TWENTY = 20 private var wheelMap = mutableMapOf<String, WheelModel>() private fun advance(wheel: String) { val w = wheelMap[wheel] if (w!!...
Change the following C++ code into Scala without altering its purpose.
#include <initializer_list> #include <iostream> #include <map> #include <vector> struct Wheel { private: std::vector<char> values; size_t index; public: Wheel() : index(0) { } Wheel(std::initializer_list<char> data) : values(data), index(0) { if (values.size() < 1) { ...
import java.util.Collections import java.util.stream.IntStream object WheelController { private val IS_NUMBER = "[0-9]".toRegex() private const val TWENTY = 20 private var wheelMap = mutableMapOf<String, WheelModel>() private fun advance(wheel: String) { val w = wheelMap[wheel] if (w!!...
Preserve the algorithm and functionality while converting the code from C++ to Scala.
using namespace System; using namespace System::Drawing; using namespace System::Windows::Forms; [STAThreadAttribute] int main() { Point^ MousePoint = gcnew Point(); Control^ TempControl = gcnew Control(); MousePoint = TempControl->MousePosition; Bitmap^ TempBitmap = gcnew Bitmap(1,1); Graphics^ g = Graphics::Fro...
import java.awt.* fun getMouseColor(): Color { val location = MouseInfo.getPointerInfo().location return getColorAt(location.x, location.y) } fun getColorAt(x: Int, y: Int): Color { return Robot().getPixelColor(x, y) }
Convert the following code from C++ to Scala, ensuring the logic remains intact.
#include <iostream> #include <cmath> #include <tuple> struct point { double x, y; }; bool operator==(const point& lhs, const point& rhs) { return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); } enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE }; using result_t = std::tuple<result_categor...
typealias IAE = IllegalArgumentException class Point(val x: Double, val y: Double) { fun distanceFrom(other: Point): Double { val dx = x - other.x val dy = y - other.y return Math.sqrt(dx * dx + dy * dy ) } override fun equals(other: Any?): Boolean { if (other == null || ...
Produce a functionally identical Scala code for the snippet given in C++.
#include <iostream> #include <cmath> #include <tuple> struct point { double x, y; }; bool operator==(const point& lhs, const point& rhs) { return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); } enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE }; using result_t = std::tuple<result_categor...
typealias IAE = IllegalArgumentException class Point(val x: Double, val y: Double) { fun distanceFrom(other: Point): Double { val dx = x - other.x val dy = y - other.y return Math.sqrt(dx * dx + dy * dy ) } override fun equals(other: Any?): Boolean { if (other == null || ...
Write a version of this C++ function in Scala with identical behavior.
#include <iostream> #include <string> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) using namespace std; class recorder { public: void start() { paused = rec = false; action = "IDLE"; while( true ) { cout << endl << "==" << action << "==" << endl << endl; cout <<...
import java.io.File import javax.sound.sampled.* const val RECORD_TIME = 20000L fun main(args: Array<String>) { val wavFile = File("RecordAudio.wav") val fileType = AudioFileFormat.Type.WAVE val format = AudioFormat(16000.0f, 16, 2, true, true) val info = DataLine.Info(TargetDataLine::class.java, f...
Write the same code in Scala as shown below in C++.
#include <vector> #include <utility> #include <algorithm> #include <iostream> #include <sstream> #include <string> #include <cmath> bool isVampireNumber( long number, std::vector<std::pair<long, long> > & solution ) { std::ostringstream numberstream ; numberstream << number ; std::string numberstring( number...
data class Fangs(val fang1: Long = 0L, val fang2: Long = 0L) fun pow10(n: Int): Long = when { n < 0 -> throw IllegalArgumentException("Can't be negative") else -> { var pow = 1L for (i in 1..n) pow *= 10L pow } } fun countDigits(n: Long): Int = when { n < 0L -> throw IllegalA...
Convert this C++ snippet to Scala and keep its semantics consistent.
#include <array> #include <iostream> template<typename T, size_t S> using FixedSquareGrid = std::array<std::array<T, S>, S>; struct Cistercian { public: Cistercian() { initN(); } Cistercian(int v) { initN(); draw(v); } Cistercian &operator=(int v) { initN(); ...
import java.io.StringWriter class Cistercian() { constructor(number: Int) : this() { draw(number) } private val size = 15 private var canvas = Array(size) { Array(size) { ' ' } } init { initN() } private fun initN() { for (row in canvas) { row.fill(' '...
Convert the following code from C++ to Scala, ensuring the logic remains intact.
#include <array> #include <iostream> template<typename T, size_t S> using FixedSquareGrid = std::array<std::array<T, S>, S>; struct Cistercian { public: Cistercian() { initN(); } Cistercian(int v) { initN(); draw(v); } Cistercian &operator=(int v) { initN(); ...
import java.io.StringWriter class Cistercian() { constructor(number: Int) : this() { draw(number) } private val size = 15 private var canvas = Array(size) { Array(size) { ' ' } } init { initN() } private fun initN() { for (row in canvas) { row.fill(' '...
Transform the following C++ implementation into Scala, maintaining the same output and logic.
#include <iostream> #include <sstream> #include <algorithm> #include <vector> using namespace std; class poker { public: poker() { face = "A23456789TJQK"; suit = "SHCD"; } string analyze( string h ) { memset( faceCnt, 0, 13 ); memset( suitCnt, 0, 4 ); vector<string> hand; transform( h.begin(), h.end(), ...
class Card(val face: Int, val suit: Char) const val FACES = "23456789tjqka" const val SUITS = "shdc" fun isStraight(cards: List<Card>): Boolean { val sorted = cards.sortedBy { it.face } if (sorted[0].face + 4 == sorted[4].face) return true if (sorted[4].face == 14 && sorted[0].face == 2 && sorted[3].fac...
Port the following code from C++ to Scala with equivalent syntax and logic.
#include <iostream> #include <sstream> #include <algorithm> #include <vector> using namespace std; class poker { public: poker() { face = "A23456789TJQK"; suit = "SHCD"; } string analyze( string h ) { memset( faceCnt, 0, 13 ); memset( suitCnt, 0, 4 ); vector<string> hand; transform( h.begin(), h.end(), ...
class Card(val face: Int, val suit: Char) const val FACES = "23456789tjqka" const val SUITS = "shdc" fun isStraight(cards: List<Card>): Boolean { val sorted = cards.sortedBy { it.face } if (sorted[0].face + 4 == sorted[4].face) return true if (sorted[4].face == 14 && sorted[0].face == 2 && sorted[3].fac...
Produce a functionally identical Scala code for the snippet given in C++.
#include <windows.h> #include <string> using namespace std; class myBitmap { public: myBitmap() : pen( NULL ) {} ~myBitmap() { DeleteObject( pen ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( int w, int h ) { BITMAPINFO bi; ZeroMemory( &bi, siz...
import java.awt.* import javax.swing.* class FibonacciWordFractal(n: Int) : JPanel() { private val wordFractal: String init { preferredSize = Dimension(450, 620) background = Color.black wordFractal = wordFractal(n) } fun wordFractal(i: Int): String { if (i < 2) re...
Produce a language-to-language conversion: from C++ to Scala, same semantics.
#include <time.h> #include <iostream> #include <string> using namespace std; class penney { public: penney() { pW = cW = 0; } void gameLoop() { string a; while( true ) { playerChoice = computerChoice = ""; if( rand() % 2 ) { computer(); player(); } else { player(); comput...
import java.util.Random val rand = Random() val optimum = mapOf( "HHH" to "THH", "HHT" to "THH", "HTH" to "HHT", "HTT" to "HHT", "THH" to "TTH", "THT" to "TTH", "TTH" to "HTT", "TTT" to "HTT" ) fun getUserSequence(): String { println("A sequence of three H or T should be entered") var userSeq: Stri...
Translate the given C++ code snippet into Scala without altering its behavior.
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( ...
import java.awt.* import javax.swing.JFrame import javax.swing.JPanel fun main(args: Array<String>) { var i = 8 if (args.any()) { try { i = args.first().toInt() } catch (e: NumberFormatException) { i = 8 println("Usage: 'java SierpinskyTriangle [level]'\...
Write the same algorithm in Scala as shown in this C++ implementation.
#include <windows.h> #include <string> #include <iostream> const int BMP_SIZE = 612; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } bool create( ...
import java.awt.* import javax.swing.JFrame import javax.swing.JPanel fun main(args: Array<String>) { var i = 8 if (args.any()) { try { i = args.first().toInt() } catch (e: NumberFormatException) { i = 8 println("Usage: 'java SierpinskyTriangle [level]'\...
Maintain the same structure and functionality when rewriting this code in Scala.
#include <iomanip> #include <iostream> #include <algorithm> #include <numeric> #include <string> #include <vector> typedef std::pair<int, std::vector<int> > puzzle; class nonoblock { public: void solve( std::vector<puzzle>& p ) { for( std::vector<puzzle>::iterator i = p.begin(); i != p.end(); i++ ) { ...
fun printBlock(data: String, len: Int) { val a = data.toCharArray() val sumChars = a.map { it.toInt() - 48 }.sum() println("\nblocks ${a.asList()}, cells $len") if (len - sumChars <= 0) { println("No solution") return } val prep = a.map { "1".repeat(it.toInt() - 48) } for (...
Transform the following C++ implementation into Scala, maintaining the same output and logic.
#include <iomanip> #include <iostream> #include <algorithm> #include <numeric> #include <string> #include <vector> typedef std::pair<int, std::vector<int> > puzzle; class nonoblock { public: void solve( std::vector<puzzle>& p ) { for( std::vector<puzzle>::iterator i = p.begin(); i != p.end(); i++ ) { ...
fun printBlock(data: String, len: Int) { val a = data.toCharArray() val sumChars = a.map { it.toInt() - 48 }.sum() println("\nblocks ${a.asList()}, cells $len") if (len - sumChars <= 0) { println("No solution") return } val prep = a.map { "1".repeat(it.toInt() - 48) } for (...
Transform the following C++ implementation into Scala, maintaining the same output and logic.
#include <iostream> struct Interval { int start, end; bool print; }; int main() { Interval intervals[] = { {2, 1000, true}, {1000, 4000, true}, {2, 10000, false}, {2, 100000, false}, {2, 1000000, false}, {2, 10000000, false}, {2, 100000000, false}, ...
typealias Range = Triple<Int, Int, Boolean> fun main() { val rgs = listOf<Range>( Range(2, 1000, true), Range(1000, 4000, true), Range(2, 10_000, false), Range(2, 100_000, false), Range(2, 1_000_000, false), Range(2, 10_000_000, false), Range(2, 100_000_000...
Convert this C++ block to Scala, preserving its control flow and logic.
#include <iostream> struct Interval { int start, end; bool print; }; int main() { Interval intervals[] = { {2, 1000, true}, {1000, 4000, true}, {2, 10000, false}, {2, 100000, false}, {2, 1000000, false}, {2, 10000000, false}, {2, 100000000, false}, ...
typealias Range = Triple<Int, Int, Boolean> fun main() { val rgs = listOf<Range>( Range(2, 1000, true), Range(1000, 4000, true), Range(2, 10_000, false), Range(2, 100_000, false), Range(2, 1_000_000, false), Range(2, 10_000_000, false), Range(2, 100_000_000...
Convert this C++ block to Scala, preserving its control flow and logic.
#include <iostream> bool valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) { if (nuts % n != 1) { return false; } } return nuts != 0 && (nuts % n == 0); } int main() { int x = 0; for (int n = 2; n < 10; n++) { while (!valid(n, x)) { ...
fun main(args: Array<String>) { var coconuts = 11 outer@ for (ns in 2..9) { val hidden = IntArray(ns) coconuts = (coconuts / ns) * ns + 1 while (true) { var nc = coconuts for (s in 1..ns) { if (nc % ns == 1) { hidd...
Ensure the translated Scala code behaves exactly like the original C++ snippet.
#include <iostream> bool valid(int n, int nuts) { for (int k = n; k != 0; k--, nuts -= 1 + nuts / n) { if (nuts % n != 1) { return false; } } return nuts != 0 && (nuts % n == 0); } int main() { int x = 0; for (int n = 2; n < 10; n++) { while (!valid(n, x)) { ...
fun main(args: Array<String>) { var coconuts = 11 outer@ for (ns in 2..9) { val hidden = IntArray(ns) coconuts = (coconuts / ns) * ns + 1 while (true) { var nc = coconuts for (s in 1..ns) { if (nc % ns == 1) { hidd...
Maintain the same structure and functionality when rewriting this code in Scala.
#include <iostream> #include <string> #include <windows.h> using namespace std; class bells { public: void start() { watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First"; count[0] = "One"; count[1] = "Two"; count[2] = "Three"; cou...
import java.text.DateFormat import java.text.SimpleDateFormat import java.util.TimeZone class NauticalBell: Thread() { override fun run() { val sdf = SimpleDateFormat("HH:mm:ss") sdf.timeZone = TimeZone.getTimeZone("UTC") var numBells = 0 var time = System.currentTimeMillis() ...
Convert the following code from C++ to Scala, ensuring the logic remains intact.
#include <iostream> #include <string> #include <windows.h> using namespace std; class bells { public: void start() { watch[0] = "Middle"; watch[1] = "Morning"; watch[2] = "Forenoon"; watch[3] = "Afternoon"; watch[4] = "Dog"; watch[5] = "First"; count[0] = "One"; count[1] = "Two"; count[2] = "Three"; cou...
import java.text.DateFormat import java.text.SimpleDateFormat import java.util.TimeZone class NauticalBell: Thread() { override fun run() { val sdf = SimpleDateFormat("HH:mm:ss") sdf.timeZone = TimeZone.getTimeZone("UTC") var numBells = 0 var time = System.currentTimeMillis() ...
Convert this C++ block to Scala, preserving its control flow and logic.
#include <iostream> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) typedef unsigned char byte; typedef union { unsigned long word; unsigned char data[4]; } midi_msg; class midi { public: midi() { if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOER...
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) } }
Translate the given C++ code snippet into Scala without altering its behavior.
#include <iostream> #include <windows.h> #include <mmsystem.h> #pragma comment ( lib, "winmm.lib" ) typedef unsigned char byte; typedef union { unsigned long word; unsigned char data[4]; } midi_msg; class midi { public: midi() { if( midiOutOpen( &device, 0, 0, 0, CALLBACK_NULL) != MMSYSERR_NOER...
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) } }
Convert the following code from C++ to Scala, ensuring the logic remains intact.
#include <windows.h> #include <sstream> #include <ctime> const float PI = 3.1415926536f, TWO_PI = 2.f * PI; class vector2 { public: vector2( float a = 0, float b = 0 ) { set( a, b ); } void set( float a, float b ) { x = a; y = b; } void rotate( float r ) { float _x = x, _y = y, s = s...
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(...
Change the following C++ code into Scala without altering its purpose.
#include <windows.h> #include <sstream> #include <ctime> const float PI = 3.1415926536f, TWO_PI = 2.f * PI; class vector2 { public: vector2( float a = 0, float b = 0 ) { set( a, b ); } void set( float a, float b ) { x = a; y = b; } void rotate( float r ) { float _x = x, _y = y, s = s...
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(...
Translate the given C++ code snippet into Scala without altering its behavior.
#include <windows.h> #include <vector> #include <string> using namespace std; struct Point { int x, y; }; class MyBitmap { public: MyBitmap() : pen_(nullptr) {} ~MyBitmap() { DeleteObject(pen_); DeleteDC(hdc_); DeleteObject(bmp_); } bool Create(int w, int h) { BITMAPINFO bi; ZeroMem...
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...
Rewrite the snippet below in Scala so it works the same as the original C++ code.
#include <windows.h> #include <vector> #include <string> using namespace std; struct Point { int x, y; }; class MyBitmap { public: MyBitmap() : pen_(nullptr) {} ~MyBitmap() { DeleteObject(pen_); DeleteDC(hdc_); DeleteObject(bmp_); } bool Create(int w, int h) { BITMAPINFO bi; ZeroMem...
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...
Ensure the translated Scala code behaves exactly like the original C++ snippet.
#include <iostream> #include <vector> #include <algorithm> #include <stdexcept> #include <memory> #include <sys/time.h> using std::cout; using std::endl; class StopTimer { public: StopTimer(): begin_(getUsec()) {} unsigned long long getTime() const { return getUsec() - begin_; } private: static unsigned l...
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)...
Change the programming language of this snippet from C++ to Scala without modifying what it does.
#include <iostream> #include <sstream> #include <iterator> #include <vector> using namespace std; struct node { int val; unsigned char neighbors; }; class hSolver { public: hSolver() { dx[0] = -1; dx[1] = 0; dx[2] = 1; dx[3] = -1; dx[4] = 1; dx[5] = -1; dx[6] = 0; dx[7] = 1; dy[0] = -1; dy[1] = -...
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...
Rewrite this program in Scala while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <sstream> #include <iterator> #include <vector> using namespace std; struct node { int val; unsigned char neighbors; }; class hSolver { public: hSolver() { dx[0] = -1; dx[1] = 0; dx[2] = 1; dx[3] = -1; dx[4] = 1; dx[5] = -1; dx[6] = 0; dx[7] = 1; dy[0] = -1; dy[1] = -...
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...
Convert this C++ snippet to Scala and keep its semantics consistent.
#include <list> template <typename T> std::list<T> strandSort(std::list<T> lst) { if (lst.size() <= 1) return lst; std::list<T> result; std::list<T> sorted; while (!lst.empty()) { sorted.push_back(lst.front()); lst.pop_front(); for (typename std::list<T>::iterator it = lst.begin(); it != lst.en...
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...
Keep all operations the same but rewrite the snippet in Scala.
#include <functional> #include <iostream> #include <iomanip> #include <math.h> #include <sstream> #include <vector> #include <boost/algorithm/string.hpp> template<typename T> T normalize(T a, double b) { return std::fmod(a, b); } inline double d2d(double a) { return normalize<double>(a, 360); } inline double g2g(doub...
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) =...
Change the programming language of this snippet from C++ to Scala without modifying what it does.
#include <cassert> #include <cstdlib> #include <iostream> #include <stdexcept> #include <utility> #include <vector> #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/xmlerror.h> #include <libxml/xmlstring.h> #include <libxml/xmlversion.h> #include <libxml/xpath.h> #ifndef LIBXML_XPATH_ENABLED # e...
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">...
Can you help me rewrite this code in Scala instead of C++, keeping it the same logically?
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& print(std::ostream& os, const T& src) { auto it = src.cbegin(); auto end = src.cend(); os << "["; if (it != end) { os << *it; ...
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,...
Generate a Scala translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <string> #include <map> #include <algorithm> using namespace std; class StraddlingCheckerboard { map<char, string> table; char first[10], second[10], third[10]; int rowU, rowV; public: StraddlingCheckerboard(const string &alphabet, int u, int v) { rowU = min(u, v); rowV...
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...
Rewrite this program in Scala while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <fstream> #include <string> #include <tuple> #include <vector> #include <stdexcept> #include <boost/regex.hpp> struct Claim { Claim(const std::string& name) : name_(name), pro_(0), against_(0), propats_(), againstpats_() { } void add_pro(const std::string...
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(" ...
Change the following C++ code into Scala without altering its purpose.
#include <iostream> #include <fstream> #include <string> #include <tuple> #include <vector> #include <stdexcept> #include <boost/regex.hpp> struct Claim { Claim(const std::string& name) : name_(name), pro_(0), against_(0), propats_(), againstpats_() { } void add_pro(const std::string...
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(" ...
Translate this program into Scala but keep the logic exactly as in C++.
#include <algorithm> #include <iostream> #include <sstream> #include <gmpxx.h> using integer = mpz_class; std::string to_string(const integer& n) { std::ostringstream out; out << n; return out.str(); } integer next_highest(const integer& n) { std::string str(to_string(n)); if (!std::next_permuta...
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)} -> ${...
Change the programming language of this snippet from C++ to Scala without modifying what it does.
#include <algorithm> #include <iostream> #include <sstream> #include <gmpxx.h> using integer = mpz_class; std::string to_string(const integer& n) { std::ostringstream out; out << n; return out.str(); } integer next_highest(const integer& n) { std::string str(to_string(n)); if (!std::next_permuta...
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)} -> ${...
Change the programming language of this snippet from C++ to Scala without modifying what it does.
#include <iostream> #include <string> #include <cctype> #include <cstdint> typedef std::uint64_t integer; const char* small[] = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen"...
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 following C++ code into Scala without altering its purpose.
#include <array> #include <iomanip> #include <iostream> #include <random> #include <sstream> class Roulette { private: std::array<bool, 6> cylinder; std::mt19937 gen; std::uniform_int_distribution<> distrib; int next_int() { return distrib(gen); } void rshift() { std::rotate(...
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 ...
Produce a functionally identical Scala code for the snippet given in C++.
#include <iomanip> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> constexpr double degrees(double deg) { const double tau = 2.0 * M_PI; return deg * tau / 360.0; } const double part_ratio = 2.0 * cos(degrees(72)); const double side_ratio = 1.0 / (part_ratio + 2.0); struct Point { doubl...
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 ...
Write the same code in Scala as shown below in C++.
#include <iostream> #include <string> #include <sstream> #include <valarray> const std::string input { "................................" ".#########.......########......." ".###...####.....####..####......" ".###....###.....###....###......" ".###...####.....###............." ".#########......###............." ".###.#...
class Point(val x: Int, val y: Int) val image = arrayOf( " ", " ################# ############# ", " ################## ################ ", " ################### ################## ...
Write the same algorithm in Scala as shown in this C++ implementation.
#include <iostream> #include <string> #include <time.h> using namespace std; namespace { void placeRandomly(char* p, char c) { int loc = rand() % 8; if (!p[loc]) p[loc] = c; else placeRandomly(p, c); } int placeFirst(char* p, char c, int loc = 0) { while (p[loc]) ++loc; p[loc] = ...
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...
Port the provided C++ code into Scala while preserving the original functionality.
#include <iostream> #include <locale> #include <map> #include <vector> std::string trim(const std::string &str) { auto s = str; auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); }); s.erase(it1.base(), s.end()); auto it2 = st...
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...
Please provide an equivalent version of this C++ code in Scala.
#include <iostream> #include <sstream> int main(int argc, char *argv[]) { using namespace std; #if _WIN32 if (argc != 5) { cout << "Usage : " << argv[0] << " (type) (id) (source string) (description>)\n"; cout << " Valid types: SUCCESS, ERROR, WARNING, INFORMATION\n"; } else { ...
fun main(args: Array<String>) { val command = "EventCreate" + " /t INFORMATION" + " /id 123" + " /l APPLICATION" + " /so Kotlin" + " /d \"Rosetta Code Example\"" Runtime.getRuntime().exec(command) }
Convert this C++ block to Scala, preserving its control flow and logic.
#include <iostream> #include <string> #include <cstdint> typedef std::uint64_t integer; struct number_names { const char* cardinal; const char* ordinal; }; const number_names small[] = { { "zero", "zeroth" }, { "one", "first" }, { "two", "second" }, { "three", "third" }, { "four", "fourth" }, { "five...
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", ...
Generate an equivalent Scala version of this C++ code.
#include <boost/asio/ip/address.hpp> #include <cstdint> #include <iostream> #include <iomanip> #include <limits> #include <string> using boost::asio::ip::address; using boost::asio::ip::address_v4; using boost::asio::ip::address_v6; using boost::asio::ip::make_address; using boost::asio::ip::make_address_v4; using boo...
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 this program in Scala while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <utility> #include <vector> using Point = std::pair<double, double>; constexpr auto eps = 1e-14; std::ostream &operator<<(std::ostream &os, const Point &p) { auto x = p.first; if (x == 0.0) { x = 0.0; } auto y = p.second; if (y == 0.0) { y = 0.0; } ...
import kotlin.math.absoluteValue import kotlin.math.sqrt const val eps = 1e-14 class Point(val x: Double, val y: Double) { override fun toString(): String { var xv = x if (xv == 0.0) { xv = 0.0 } var yv = y if (yv == 0.0) { yv = 0.0 } ...
Generate an equivalent Scala version of this C++ code.
#include <iostream> #include <cstring> int findNumOfDec(const char *s) { int pos = 0; while (s[pos] && s[pos++] != '.') {} return strlen(s + pos); } void test(const char *s) { int num = findNumOfDec(s); const char *p = num != 1 ? "s" : ""; std::cout << s << " has " << num << " decimal" << p <...
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...
Write the same code in Scala as shown below in C++.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; dx[2] = 2; dy[2] = -2; dx...
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 ...
Please provide an equivalent version of this C++ code in Scala.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <stdlib.h> #include <string.h> using namespace std; struct node { int val; unsigned char neighbors; }; class nSolver { public: nSolver() { dx[0] = -2; dy[0] = -2; dx[1] = -2; dy[1] = 2; dx[2] = 2; dy[2] = -2; dx...
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 ...
Keep all operations the same but rewrite the snippet in Scala.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <cstdlib> #include <string> #include <bitset> using namespace std; typedef bitset<4> hood_t; struct node { int val; hood_t neighbors; }; class nSolver { public: void solve(vector<string>& puzz, int max_wid) { if (puzz.size()...
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,...
Keep all operations the same but rewrite the snippet in Scala.
#include <vector> #include <sstream> #include <iostream> #include <iterator> #include <cstdlib> #include <string> #include <bitset> using namespace std; typedef bitset<4> hood_t; struct node { int val; hood_t neighbors; }; class nSolver { public: void solve(vector<string>& puzz, int max_wid) { if (puzz.size()...
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,...
Change the programming language of this snippet from C++ to Scala without modifying what it does.
class animal { public: virtual void bark() { throw "implement me: do not know how to bark"; } }; class elephant : public animal { }; int main() { elephant e; e.bark(); }
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 the following code from C++ to Scala, ensuring the logic remains intact.
#include <iomanip> #include <iostream> #include <map> #include <string> #include <vector> std::map<std::string, double> atomicMass = { {"H", 1.008}, {"He", 4.002602}, {"Li", 6.94}, {"Be", 9.0121831}, {"B", 10.81}, {"C", 12.011}, {"N", 14.007}, {"O", 15.999}, {"F...
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...
Convert this C++ snippet to Scala and keep its semantics consistent.
#include <boost/spirit.hpp> #include <boost/spirit/tree/ast.hpp> #include <string> #include <cassert> #include <iostream> #include <istream> #include <ostream> using boost::spirit::rule; using boost::spirit::parser_tag; using boost::spirit::ch_p; using boost::spirit::real_p; using boost::spirit::tree_no...
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...
Produce a language-to-language conversion: from C++ to Scala, same semantics.
#include <boost/spirit.hpp> #include <boost/spirit/tree/ast.hpp> #include <string> #include <cassert> #include <iostream> #include <istream> #include <ostream> using boost::spirit::rule; using boost::spirit::parser_tag; using boost::spirit::ch_p; using boost::spirit::real_p; using boost::spirit::tree_no...
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...