Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Write a version of this C++ function in Scala with identical behavior. | #include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
const int luckySize = 60000;
std::vector<int> luckyEven(luckySize);
std::vector<int> luckyOdd(luckySize);
void init() {
for (int i = 0; i < luckySize; ++i) {
luckyEven[i] = i * 2 + 2;
luckyOdd[i] = i * 2 + 1;
}
}
v... |
typealias IAE = IllegalArgumentException
val luckyOdd = MutableList(100000) { it * 2 + 1 }
val luckyEven = MutableList(100000) { it * 2 + 2 }
fun filterLuckyOdd() {
var n = 2
while (n < luckyOdd.size) {
val m = luckyOdd[n - 1]
val end = (luckyOdd.size / m) * m - 1
for (j in end down... |
Translate this program into Scala but keep the logic exactly as in C++. | #include <algorithm>
#include <complex>
#include <iomanip>
#include <iostream>
std::complex<double> inv(const std::complex<double>& c) {
double denom = c.real() * c.real() + c.imag() * c.imag();
return std::complex<double>(c.real() / denom, -c.imag() / denom);
}
class QuaterImaginary {
public:
QuaterImagi... |
import kotlin.math.ceil
class Complex(val real: Double, val imag: Double) {
constructor(r: Int, i: Int) : this(r.toDouble(), i.toDouble())
operator fun plus(other: Complex) = Complex(real + other.real, imag + other.imag)
operator fun times(other: Complex) = Complex(
real * other.real - imag * ... |
Write the same code in Scala as shown below in C++. | #include <random>
#include <map>
#include <string>
#include <iostream>
#include <cmath>
#include <iomanip>
int main( ) {
std::random_device myseed ;
std::mt19937 engine ( myseed( ) ) ;
std::normal_distribution<> normDistri ( 2 , 3 ) ;
std::map<int , int> normalFreq ;
int sum = 0 ;
double mean = 0.0 ... |
val rand = java.util.Random()
fun normalStats(sampleSize: Int) {
if (sampleSize < 1) return
val r = DoubleArray(sampleSize)
val h = IntArray(12)
for (i in 0 until sampleSize) {
r[i] = 0.5 + rand.nextGaussian() / 4.0
when {
r[i] < 0.0 -> h[0]++
r[i] >= 1.... |
Translate this program into Scala but keep the logic exactly as in C++. | #include <iostream>
#include <numeric>
#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);
}
while (it != end) {
... |
val supply = intArrayOf(50, 60, 50, 50)
val demand = intArrayOf(30, 20, 70, 30, 60)
val costs = arrayOf(
intArrayOf(16, 16, 13, 22, 17),
intArrayOf(14, 14, 13, 19, 15),
intArrayOf(19, 19, 20, 23, 50),
intArrayOf(50, 12, 50, 15, 11)
)
val nRows = supply.size
val nCols = demand.size
val rowDone = Boo... |
Produce a functionally identical Scala code for the snippet given in C++. | #include <iostream>
#include <vector>
__int128 imax(__int128 a, __int128 b) {
if (a > b) {
return a;
}
return b;
}
__int128 ipow(__int128 b, __int128 n) {
if (n == 0) {
return 1;
}
if (n == 1) {
return b;
}
__int128 res = b;
while (n > 1) {
res *= b... | import java.math.BigInteger
fun main() {
for (n in testCases) {
val result = getA004290(n)
println("A004290($n) = $result = $n * ${result / n.toBigInteger()}")
}
}
private val testCases: List<Int>
get() {
val testCases: MutableList<Int> = ArrayList()
for (i in 1..10) {
... |
Ensure the translated Scala code behaves exactly like the original C++ snippet. | #include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
class magicSqr
{
public:
magicSqr() { sqr = 0; }
~magicSqr() { if( sqr ) delete [] sqr; }
void create( int d ) {
if( sqr ) delete [] sqr;
if( d & 1 ) d++;
while( d % 4 == 0 ) { d += 2; }
sz = ... |
fun magicSquareOdd(n: Int): Array<IntArray> {
if (n < 3 || n % 2 == 0)
throw IllegalArgumentException("Base must be odd and > 2")
var value = 0
val gridSize = n * n
var c = n / 2
var r = 0
val result = Array(n) { IntArray(n) }
while (++value <= gridSize) {
result[r][c] = ... |
Convert this C++ snippet to Scala and keep its semantics consistent. | #include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
std::vector<int> divisors(int n) {
std::vector<int> divs = { 1 };
std::vector<int> divs2;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
int j = n / i;
divs.push_back(i);
if (i !... |
fun divisors(n: Int): List<Int> {
val divs = mutableListOf(1)
val divs2 = mutableListOf<Int>()
var i = 2
while (i * i <= n) {
if (n % i == 0) {
val j = n / i
divs.add(i)
if (i != j) divs2.add(j)
}
i++
}
divs2.addAll(divs.asReversed())... |
Generate an equivalent Scala version of this C++ code. | #include <iostream>
#include <vector>
enum class Piece {
empty,
black,
white
};
typedef std::pair<int, int> position;
bool isAttacking(const position &queen, const position &pos) {
return queen.first == pos.first
|| queen.second == pos.second
|| abs(queen.first - pos.first) == abs(que... | import kotlin.math.abs
enum class Piece {
Empty,
Black,
White,
}
typealias Position = Pair<Int, Int>
fun place(m: Int, n: Int, pBlackQueens: MutableList<Position>, pWhiteQueens: MutableList<Position>): Boolean {
if (m == 0) {
return true
}
var placingBlack = true
for (i in 0 until... |
Produce a language-to-language conversion: from C++ to Scala, same semantics. | #include <iostream>
#include <vector>
std::vector<int> smallPrimes;
bool is_prime(size_t test) {
if (test < 2) {
return false;
}
if (test % 2 == 0) {
return test == 2;
}
for (size_t d = 3; d * d <= test; d += 2) {
if (test % d == 0) {
return false;
}
... |
import java.math.BigInteger
import kotlin.math.sqrt
const val MAX = 33
fun isPrime(n: Int) = BigInteger.valueOf(n.toLong()).isProbablePrime(10)
fun generateSmallPrimes(n: Int): List<Int> {
val primes = mutableListOf<Int>()
primes.add(2)
var i = 3
while (primes.size < n) {
if (isPrime(i)) {
... |
Produce a language-to-language conversion: from C++ to Scala, same semantics. | #include <algorithm>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
class Vector {
private:
double px, py, pz;
public:
Vector() : px(0.0), py(0.0), pz(0.0) {
}
Vector(double x, double y, double z) : px(x), py(y), pz(z) {
}
doub... |
import java.io.File
import kotlin.math.sqrt
import kotlin.math.pow
class Vector3D(val x: Double, val y: Double, val z: Double) {
operator fun plus(v: Vector3D) = Vector3D(x + v.x, y + v.y, z + v.z)
operator fun minus(v: Vector3D) = Vector3D(x - v.x, y - v.y, z - v.z)
operator fun times(s: Double) = Vect... |
Convert this C++ block to Scala, preserving its control flow and logic. | #include <iostream>
#include <string>
#include <vector>
std::vector<std::string> hist;
std::ostream& operator<<(std::ostream& os, const std::string& str) {
return os << str.c_str();
}
void appendHistory(const std::string& name) {
hist.push_back(name);
}
void hello() {
std::cout << "Hello World!\n";
... |
var range = intArrayOf()
val history = mutableListOf<String>()
fun greeting() {
ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor()
println("** Welcome to the Ranger readline interface **")
println("** which performs operations on a range of integers **\n")
println("Command... |
Translate the given C++ code snippet into Scala without altering its behavior. | #include <iostream>
#include <tuple>
#include <vector>
std::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int);
std::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) {
if (pos > minLen || seq[0] > n) return { minLen, 0 };
else if (seq[0] == n) return ... |
var example: List<Int>? = null
fun checkSeq(pos: Int, seq: List<Int>, n: Int, minLen: Int): Pair<Int, Int> =
if (pos > minLen || seq[0] > n) minLen to 0
else if (seq[0] == n) { example = seq; pos to 1 }
else if (pos < minLen) tryPerm(0, pos, seq, n, minLen)
else ... |
Produce a language-to-language conversion: from C++ to Scala, same semantics. | #include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
typedef struct {
int s[4];
}userI;
class jit{
public:
void decode( std::string& file, std::vector<userI>& ui ) {
std::ifstream f( file.c_str(), std::ios_base::in );
fileBuffer = std::string( ( std::istreambuf_iterator<... |
import java.io.File
data class UserInput(val formFeed: Int, val lineFeed: Int, val tab: Int, val space: Int)
fun getUserInput(): List<UserInput> {
val h = "0 18 0 0 0 68 0 1 0 100 0 32 0 114 0 45 0 38 0 26 0 16 0 21 0 17 0 59 0 11 " +
"0 29 0 102 0 0 0 10 0 50 0 39 0 42 0 33 0 50 0 46 0 54 0 76 0 47... |
Generate an equivalent Scala version of this C++ code. | #include <iostream>
#define DEBUG(msg,...) fprintf(stderr, "[DEBUG %s@%d] " msg "\n", __FILE__, __LINE__, __VA_ARGS__)
int main() {
DEBUG("Hello world");
DEBUG("Some %d Things", 42);
return 0;
}
| fun printDebug(message: String) {
val exception = RuntimeException()
val stackTrace = exception.stackTrace
val stackTraceElement = stackTrace[1]
val fileName = stackTraceElement.fileName
val className = stackTraceElement.className
val methodName = stackTraceElement.methodName
val lineNumber ... |
Generate an equivalent Scala version of this C++ code. | #include<iostream>
#include<conio.h>
using namespace std;
typedef unsigned long ulong;
int ith_digit_finder(long long n, long b, long i){
while(i>0){
n/=b;
i--;
}
return (n%b);
}
long eeuclid(long m, long b, long *inverse){
long A1 = 1, A2 = 0, A3 = m,
B1 = 0, B... |
import java.math.BigInteger
val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE
val bigTwo = BigInteger.valueOf(2L)
class Montgomery(val m: BigInteger) {
val n: Int
val rrm: BigInteger
init {
require(m > bigZero && m.testBit(0))
n = m.bitLength()
rrm = bigOne.s... |
Translate this program into Scala but keep the logic exactly as in C++. | #include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <regex>
#include <tuple>
#include <set>
#include <array>
using namespace std;
class Board
{
public:
vector<vector<char>> sData, dData;
int px, py;
Board(string b)
{
regex pattern("([^\\n]+)\\n?");
sregex_iterator end, it... |
import java.util.LinkedList
class Sokoban(board: List<String>) {
val destBoard: String
val currBoard: String
val nCols = board[0].length
var playerX = 0
var playerY = 0
init {
val destBuf = StringBuilder()
val currBuf = StringBuilder()
for (r in 0 until board.size) {
... |
Translate this program into Scala but keep the logic exactly as in C++. | #include <iostream">
#include <cmath>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <numeric>
using namespace std;
const uint* binary(uint n, uint length);
uint sum_subset_unrank_bin(const vector<uint>& d, uint r);
vector<uint> factors(uint x);
bool isPrime(uint number);
bool isZum(uint n)... | import java.util.ArrayList
import kotlin.math.sqrt
object ZumkellerNumbers {
@JvmStatic
fun main(args: Array<String>) {
var n = 1
println("First 220 Zumkeller numbers:")
run {
var count = 1
while (count <= 220) {
if (isZumkeller(n)) {
... |
Please provide an equivalent version of this C++ code in Scala. | #include <functional>
#include <iostream>
#include <vector>
struct Node {
std::string sub = "";
std::vector<int> ch;
Node() {
}
Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {
ch.insert(ch.end(), children);
}
};
struct SuffixTree {
s... |
class Node {
var sub = ""
var ch = mutableListOf<Int>()
}
class SuffixTree(val str: String) {
val nodes = mutableListOf<Node>(Node())
init {
for (i in 0 until str.length) addSuffix(str.substring(i))
}
private fun addSuffix(suf: String) {
var n = 0
... |
Rewrite the snippet below in Scala so it works the same as the original C++ code. | #include <functional>
#include <iostream>
#include <vector>
struct Node {
std::string sub = "";
std::vector<int> ch;
Node() {
}
Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) {
ch.insert(ch.end(), children);
}
};
struct SuffixTree {
s... |
class Node {
var sub = ""
var ch = mutableListOf<Int>()
}
class SuffixTree(val str: String) {
val nodes = mutableListOf<Node>(Node())
init {
for (i in 0 until str.length) addSuffix(str.substring(i))
}
private fun addSuffix(suf: String) {
var n = 0
... |
Generate a Scala translation of this C++ snippet without changing its computational steps. | #include <iostream>
#include <functional>
#include <map>
#include <vector>
struct Node {
int length;
std::map<char, int> edges;
int suffix;
Node(int l) : length(l), suffix(0) {
}
Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {
}
};
co... |
class Node {
val edges = mutableMapOf<Char, Node>()
var link: Node? = null
var len = 0
}
class Eertree(str: String) {
val nodes = mutableListOf<Node>()
private val rto = Node()
private val rte = Node()
priva... |
Produce a functionally identical Scala code for the snippet given in C++. | #include <iostream>
#include <functional>
#include <map>
#include <vector>
struct Node {
int length;
std::map<char, int> edges;
int suffix;
Node(int l) : length(l), suffix(0) {
}
Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) {
}
};
co... |
class Node {
val edges = mutableMapOf<Char, Node>()
var link: Node? = null
var len = 0
}
class Eertree(str: String) {
val nodes = mutableListOf<Node>()
private val rto = Node()
private val rte = Node()
priva... |
Ensure the translated Scala code behaves exactly like the original C++ snippet. | #include <algorithm>
#include <functional>
#include <iostream>
#include <numeric>
#include <vector>
typedef std::vector<std::vector<int>> matrix;
matrix dList(int n, int start) {
start--;
std::vector<int> a(n);
std::iota(a.begin(), a.end(), 0);
a[start] = a[0];
a[0] = start;
std::sort(a.begi... | typealias Matrix = MutableList<MutableList<Int>>
fun dList(n: Int, sp: Int): Matrix {
val start = sp - 1
val a = generateSequence(0) { it + 1 }.take(n).toMutableList()
a[start] = a[0].also { a[0] = a[start] }
a.subList(1, a.size).sort()
val first = a[1]
val r = mutableListOf<MutableList... |
Ensure the translated Scala code behaves exactly like the original C++ snippet. | #include <functional>
#include <iostream>
#include <ostream>
#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);
}
whil... |
val g = listOf(
intArrayOf(1),
intArrayOf(2),
intArrayOf(0),
intArrayOf(1, 2, 4),
intArrayOf(3, 5),
intArrayOf(2, 6),
intArrayOf(5),
intArrayOf(4, 6, 7)
)
fun kosaraju(g: List<IntArray>): List<List<Int>> {
val size = g.size
... |
Rewrite the snippet below in Scala so it works the same as the original C++ code. | #include <iomanip>
#include <ctime>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>
const int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25;
class Cell {
public:
Cell() : val( 0 ), cntOverlap( 0 ) {}
char val; int cntOverlap;
};
class Word {
public:
... |
import java.util.Random
import java.io.File
val dirs = listOf(
intArrayOf( 1, 0), intArrayOf(0, 1), intArrayOf( 1, 1), intArrayOf( 1, -1),
intArrayOf(-1, 0), intArrayOf(0, -1), intArrayOf(-1, -1), intArrayOf(-1, 1)
)
val nRows = 10
val nCols = 10
val gridSize = nRows * nCols
val minWords = 25
val rand = ... |
Rewrite the snippet below in Scala so it works the same as the original C++ code. | #include <ctime>
#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>
#include <vector>
#include <map>
class markov {
public:
void create( std::string& file, unsigned int keyLen, unsigned int words ) {
std::ifstream f( file.c_str(), std::ios_base::in );
fileBuffer = std::str... |
import java.io.File
fun markov(filePath: String, keySize: Int, outputSize: Int): String {
require(keySize >= 1) { "Key size can't be less than 1" }
val words = File(filePath).readText().trimEnd().split(' ')
require(outputSize in keySize..words.size) { "Output size is out of range" }
val dict = muta... |
Port the provided C++ code into Scala while preserving the original functionality. | #include <algorithm>
#include <iostream>
#include <random>
#include <vector>
double uniform01() {
static std::default_random_engine generator;
static std::uniform_real_distribution<double> distribution(0.0, 1.0);
return distribution(generator);
}
int bitCount(int i) {
i -= ((i >> 1) & 0x55555555);
... | fun bitCount(i: Int): Int {
var j = i
j -= ((j shr 1) and 0x55555555)
j = (j and 0x33333333) + ((j shr 2) and 0x33333333)
j = (j + (j shr 4)) and 0x0F0F0F0F
j += (j shr 8)
j += (j shr 16)
return j and 0x0000003F
}
fun reorderingSign(i: Int, j: Int): Double {
var k = i shr 1
var sum ... |
Write a version of this C++ function in Scala with identical behavior. | #include <iostream>
#include <string>
using namespace std;
class playfair
{
public:
void doIt( string k, string t, bool ij, bool e )
{
createGrid( k, ij ); getTextReady( t, ij, e );
if( e ) doIt( 1 ); else doIt( -1 );
display();
}
private:
void doIt( int dir )
{
int a, b, c, d; string ntxt;
... |
enum class PlayfairOption {
NO_Q,
I_EQUALS_J
}
class Playfair(keyword: String, val pfo: PlayfairOption) {
private val table: Array<CharArray> = Array(5, { CharArray(5) })
init {
val used = BooleanArray(26)
if (pfo == PlayfairOption.NO_Q)
used[16] = true
... |
Write the same code in Scala as shown below in C++. | #include <iostream>
#include <string>
using namespace std;
class playfair
{
public:
void doIt( string k, string t, bool ij, bool e )
{
createGrid( k, ij ); getTextReady( t, ij, e );
if( e ) doIt( 1 ); else doIt( -1 );
display();
}
private:
void doIt( int dir )
{
int a, b, c, d; string ntxt;
... |
enum class PlayfairOption {
NO_Q,
I_EQUALS_J
}
class Playfair(keyword: String, val pfo: PlayfairOption) {
private val table: Array<CharArray> = Array(5, { CharArray(5) })
init {
val used = BooleanArray(26)
if (pfo == PlayfairOption.NO_Q)
used[16] = true
... |
Translate the given C++ code snippet into Scala without altering its behavior. | #include <iostream>
#include <iomanip>
#include <string>
class oo {
public:
void evolve( int l, int rule ) {
std::string cells = "O";
std::cout << " Rule #" << rule << ":\n";
for( int x = 0; x < l; x++ ) {
addNoCells( cells );
std::cout << std::setw( 40 + ( static... |
fun evolve(l: Int, rule: Int) {
println(" Rule #$rule:")
var cells = StringBuilder("*")
for (x in 0 until l) {
addNoCells(cells)
val width = 40 + (cells.length shr 1)
println(cells.padStart(width))
cells = step(cells, rule)
}
}
fun step(cells: StringBuilder, rule: Int)... |
Translate the given C++ code snippet into Scala without altering its behavior. | #include <algorithm>
#include <iostream>
#include <optional>
#include <set>
#include <string>
#include <string_view>
#include <vector>
struct string_comparator {
using is_transparent = void;
bool operator()(const std::string& lhs, const std::string& rhs) const {
return lhs < rhs;
}
bool operato... |
import java.io.File
val partitions = mutableListOf<List<String>>()
fun partitionString(s: String, ml: MutableList<String>, level: Int) {
for (i in s.length - 1 downTo 1) {
val part1 = s.substring(0, i)
val part2 = s.substring(i)
ml.add(part1)
ml.add(part2)
partitions.add(... |
Generate an equivalent Scala version of this C++ code. | #include <iostream>
#include <map>
#include <utility>
using namespace std;
template<typename T>
class FixedMap : private T
{
T m_defaultValues;
public:
FixedMap(T map)
: T(map), m_defaultValues(move(map)){}
using T::cbegin;
using T::cend;
using T::empty;... |
fun main(args: Array<String>) {
val map = mapOf('A' to 65, 'B' to 66, 'C' to 67)
println(map)
}
|
Port the following code from C++ to Scala with equivalent syntax and logic. |
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)
{
std::string r = "";
if (remainder)
{
r = " r: " + std::to_string(polynomial.back());
polynomial.pop_back();
}
std::string formatted = "";
int deg... |
fun extendedSyntheticDivision(dividend: IntArray, divisor: IntArray): Pair<IntArray, IntArray> {
val out = dividend.copyOf()
val normalizer = divisor[0]
val separator = dividend.size - divisor.size + 1
for (i in 0 until separator) {
out[i] /= normalizer
val coef = out[i]
if (co... |
Convert this C++ snippet to Scala and keep its semantics consistent. |
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)
{
std::string r = "";
if (remainder)
{
r = " r: " + std::to_string(polynomial.back());
polynomial.pop_back();
}
std::string formatted = "";
int deg... |
fun extendedSyntheticDivision(dividend: IntArray, divisor: IntArray): Pair<IntArray, IntArray> {
val out = dividend.copyOf()
val normalizer = divisor[0]
val separator = dividend.size - divisor.size + 1
for (i in 0 until separator) {
out[i] /= normalizer
val coef = out[i]
if (co... |
Please provide an equivalent version of this C++ code in Scala. |
#include "colorwheelwidget.h"
#include <QPainter>
#include <QPaintEvent>
#include <cmath>
namespace {
QColor hsvToRgb(int h, double s, double v) {
double hp = h/60.0;
double c = s * v;
double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));
double m = v - c;
double r = 0, g = 0, b = 0;
if (hp <=... |
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
import kotlin.math.*
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val... |
Write the same code in Scala as shown below in C++. | #include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" };
template<const uint N>
void lucas(ulong b) {
std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b... | import java.math.BigDecimal
import java.math.BigInteger
val names = listOf("Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead")
fun lucas(b: Long) {
println("Lucas sequence for ${names[b.toInt()]} ratio, where b = $b:")
print("First 15 elements: ")
var x0 = 1L
... |
Change the following C++ code into Scala without altering its purpose. | #include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>
const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" };
template<const uint N>
void lucas(ulong b) {
std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b... | import java.math.BigDecimal
import java.math.BigInteger
val names = listOf("Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead")
fun lucas(b: Long) {
println("Lucas sequence for ${names[b.toInt()]} ratio, where b = $b:")
print("First 15 elements: ")
var x0 = 1L
... |
Keep all operations the same but rewrite the snippet in Scala. | #include <iostream>
struct link
{
link* next;
int data;
link(int newItem, link* head)
: next{head}, data{newItem}{}
};
void PrintList(link* head)
{
if(!head) return;
std::cout << head->data << " ";
PrintList(head->next);
}
link* RemoveItem(int valueToRemove, link*&head)
{
for(link... |
class Node<T: Number>(var data: T, var next: Node<T>? = null) {
override fun toString(): String {
val sb = StringBuilder(this.data.toString())
var node = this.next
while (node != null) {
sb.append(" -> ", node.data.toString())
node = node.next
}
retu... |
Preserve the algorithm and functionality while converting the code from C++ to Scala. | #include <cmath>
#include <iostream>
#include <string>
using namespace std;
struct LoggingMonad
{
double Value;
string Log;
};
auto operator>>(const LoggingMonad& monad, auto f)
{
auto result = f(monad.Value);
return LoggingMonad{result.Value, monad.Log + "\n" + result.Log};
}
auto Root = [](doub... |
import kotlin.math.sqrt
class Writer<T : Any> private constructor(val value: T, s: String) {
var log = " ${s.padEnd(17)}: $value\n"
private set
fun bind(f: (T) -> Writer<T>): Writer<T> {
val new = f(this.value)
new.log = this.log + new.log
return new
}
companion obj... |
Convert this C++ block to Scala, preserving its control flow and logic. | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type val... |
typealias Matrix = Array<DoubleArray>
fun Matrix.inverse(): Matrix {
val len = this.size
require(this.all { it.size == len }) { "Not a square matrix" }
val aug = Array(len) { DoubleArray(2 * len) }
for (i in 0 until len) {
for (j in 0 until len) aug[i][j] = this[i][j]
aug[i][... |
Can you help me rewrite this code in Scala instead of C++, keeping it the same logically? | #include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type val... |
typealias Matrix = Array<DoubleArray>
fun Matrix.inverse(): Matrix {
val len = this.size
require(this.all { it.size == len }) { "Not a square matrix" }
val aug = Array(len) { DoubleArray(2 * len) }
for (i in 0 until len) {
for (j in 0 until len) aug[i][j] = this[i][j]
aug[i][... |
Write the same algorithm in Scala as shown in this C++ implementation. | #include <ctime>
#include <iostream>
#include <string>
#include <algorithm>
class chessBoard {
public:
void generateRNDBoard( int brds ) {
int a, b, i; char c;
for( int cc = 0; cc < brds; cc++ ) {
memset( brd, 0, 64 );
std::string pieces = "PPPPPPPPNNBBRRQKppppppppnnbbrrqk";... |
import java.util.Random
import kotlin.math.abs
val rand = Random()
val grid = List(8) { CharArray(8) }
const val NUL = '\u0000'
fun createFen(): String {
placeKings()
placePieces("PPPPPPPP", true)
placePieces("pppppppp", true)
placePieces("RNBQBNR", false)
placePieces("rnbqbnr", false)
ret... |
Port the provided C++ code into Scala while preserving the original functionality. | #include <cmath>
#include <cstdint>
#include <iostream>
#include <functional>
uint64_t factorial(int n) {
uint64_t result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int inverse_factorial(uint64_t f) {
int p = 1;
int i = 1;
if (f == 1) {
return 0;... | import java.math.BigInteger
import java.util.function.Function
fun factorial(n: Int): BigInteger {
val bn = BigInteger.valueOf(n.toLong())
var result = BigInteger.ONE
var i = BigInteger.TWO
while (i <= bn) {
result *= i++
}
return result
}
fun inverseFactorial(f: BigInteger): Int {
... |
Write the same code in Scala as shown below in C++. | #include <windows.h>
#include <iostream>
#include <ctime>
const int WID = 79, HEI = 22;
const float NCOUNT = ( float )( WID * HEI );
class coord : public COORD {
public:
coord( short x = 0, short y = 0 ) { set( x, y ); }
void set( short x, short y ) { X = x; Y = y; }
};
class winConsole {
public:
static w... |
import kotlinx.cinterop.*
import platform.posix.*
import platform.windows.*
const val WID = 79
const val HEI = 22
const val NCOUNT = (WID * HEI).toFloat()
class WinConsole {
val conOut: HANDLE
val conIn: HANDLE
private constructor() {
conOut = GetStdHandle(STD_OUTPUT_HANDLE)!!
conIn = ... |
Write the same algorithm in Scala as shown in this C++ implementation. | #include <windows.h>
#include <iostream>
#include <ctime>
const int WID = 79, HEI = 22;
const float NCOUNT = ( float )( WID * HEI );
class coord : public COORD {
public:
coord( short x = 0, short y = 0 ) { set( x, y ); }
void set( short x, short y ) { X = x; Y = y; }
};
class winConsole {
public:
static w... |
import kotlinx.cinterop.*
import platform.posix.*
import platform.windows.*
const val WID = 79
const val HEI = 22
const val NCOUNT = (WID * HEI).toFloat()
class WinConsole {
val conOut: HANDLE
val conIn: HANDLE
private constructor() {
conOut = GetStdHandle(STD_OUTPUT_HANDLE)!!
conIn = ... |
Translate the given C++ code snippet into Scala without altering its behavior. | #include <cctype>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
struct number_names {
const char* cardinal;
const char* ordinal;
};
const number_names small[] = {
{ "zero", "zeroth" }, { "one", "first" }, { "two", "second" },
{ "three", "third" }, { "fou... |
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",
... |
Convert this C++ snippet to Scala and keep its semantics consistent. |
class NG_8 : public matrixNG {
private: int a12, a1, a2, a, b12, b1, b2, b, t;
double ab, a1b1, a2b2, a12b12;
const int chooseCFN(){return fabs(a1b1-ab) > fabs(a2b2-ab)? 0 : 1;}
const bool needTerm() {
if (b1==0 and b==0 and b2==0 and b12==0) return false;
if (b==0){cfn = b2==0? 0:1; return tr... |
import kotlin.math.abs
abstract class MatrixNG {
var cfn = 0
var thisTerm = 0
var haveTerm = false
abstract fun consumeTerm()
abstract fun consumeTerm(n: Int)
abstract fun needTerm(): Boolean
}
class NG4(
var a1: Int, var a: Int, var b1: Int, var b: Int
) : MatrixNG() {
private va... |
Convert this C++ block to Scala, preserving its control flow and logic. |
class NG_8 : public matrixNG {
private: int a12, a1, a2, a, b12, b1, b2, b, t;
double ab, a1b1, a2b2, a12b12;
const int chooseCFN(){return fabs(a1b1-ab) > fabs(a2b2-ab)? 0 : 1;}
const bool needTerm() {
if (b1==0 and b==0 and b2==0 and b12==0) return false;
if (b==0){cfn = b2==0? 0:1; return tr... |
import kotlin.math.abs
abstract class MatrixNG {
var cfn = 0
var thisTerm = 0
var haveTerm = false
abstract fun consumeTerm()
abstract fun consumeTerm(n: Int)
abstract fun needTerm(): Boolean
}
class NG4(
var a1: Int, var a: Int, var b1: Int, var b: Int
) : MatrixNG() {
private va... |
Rewrite the snippet below in Scala so it works the same as the original C++ code. | #include <string>
#include <vector>
#include <map>
#include <iostream>
#include <algorithm>
#include <utility>
#include <sstream>
std::string mostFreqKHashing ( const std::string & input , int k ) {
std::ostringstream oss ;
std::map<char, int> frequencies ;
for ( char c : input ) {
frequencies[ c ] = st... |
fun mostFreqKHashing(input: String, k: Int): String =
input.groupBy { it }.map { Pair(it.key, it.value.size) }
.sortedByDescending { it.second }
.take(k)
.fold("") { acc, v -> acc + "${v.first}${v.second.toChar()}" }
fun mostFreqKSimilarit... |
Ensure the translated Scala code behaves exactly like the original C++ snippet. | #include <cmath>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
int main() {
std::ofstream out("penrose_tiling.svg");
if (!out) {
std::cerr << "Cannot open output file.\n";
return... |
import java.awt.*
import java.awt.geom.Path2D
import javax.swing.*
class PenroseTiling(w: Int, h: Int) : JPanel() {
private enum class Type {
KITE, DART
}
private class Tile(
val type: Type,
val x: Double,
val y: Double,
val angle: Double,
val size: Do... |
Generate a Scala translation of this C++ snippet without changing its computational steps. |
#include <algorithm>
#include <iostream>
#include <list>
#include <string>
#include <vector>
struct noncopyable {
noncopyable() {}
noncopyable(const noncopyable&) = delete;
noncopyable& operator=(const noncopyable&) = delete;
};
template <typename T>
class tarjan;
template <typename T>
class vertex :... |
import java.util.Stack
typealias Nodes = List<Node>
class Node(val n: Int) {
var index = -1
var lowLink = -1
var onStack = false
override fun toString() = n.toString()
}
class DirectedGraph(val vs: Nodes, val es: Map<Node, Nodes>)
fun tarjan(g: DirectedGraph): List<Nodes> {
val sccs = mu... |
Maintain the same structure and functionality when rewriting this code in Icon. | #include<conio.h>
#define COLOURS 8
int main()
{
int colour=0,i,j,MAXROW,MAXCOL;
struct text_info tInfo;
gettextinfo(&tInfo);
MAXROW = tInfo.screenheight;
MAXCOL = tInfo.screenwidth;
textbackground(BLACK);
clrscr();
for(colour=0;colour<COLOURS;colour++)
{
getch();
got... | link graphics,printf
procedure main()
DrawTestCard(Simple_TestCard())
WDone()
end
procedure DrawTestCard(TC)
size := sprintf("size=%d,%d",TC.width,TC.height)
&window := TC.window := open(TC.id,"g","bg=black",size) |
stop("Unable to open window")
every R ... |
Transform the following C implementation into Icon, maintaining the same output and logic. | #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <setjmp.h>
#include <time.h>
jmp_buf ctx;
const char *msg;
enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };
typedef struct expr_t *expr, expr_t;
struct expr_t {
int op, val, used;
expr left, right;
};
#define N_DIGITS 4
expr_t dig... | invocable all
link strings
procedure main()
help()
repeat {
every (n := "") ||:= (1 to 4, string(1+?8))
writes("Your four digits are : ")
every writes(!n," ")
write()
e := trim(read()) | fail
case e of {
"q"|"quit": return
"?"|"help": help()
default: {
e := del... |
Write a version of this C function in Icon with identical behavior. | #include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <setjmp.h>
#include <time.h>
jmp_buf ctx;
const char *msg;
enum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };
typedef struct expr_t *expr, expr_t;
struct expr_t {
int op, val, used;
expr left, right;
};
#define N_DIGITS 4
expr_t dig... | invocable all
link strings
procedure main()
help()
repeat {
every (n := "") ||:= (1 to 4, string(1+?8))
writes("Your four digits are : ")
every writes(!n," ")
write()
e := trim(read()) | fail
case e of {
"q"|"quit": return
"?"|"help": help()
default: {
e := del... |
Change the following C code into Icon without altering its purpose. | #include <stdio.h>
#include <stdlib.h>
#define N 100000
int main()
{
int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;
q[1] = q[2] = 1;
for (i = 3; i <= N; i++)
q[i] = q[i - q[i - 1]] + q[i - q[i - 2]];
for (i = 1; i <= 10; i++)
printf("%d%c", q[i], i == 10 ? '\n' : ' ');
printf("%d\n", q[1000]);
f... | link printf
procedure main()
V := [1, 1, 2, 3, 3, 4, 5, 5, 6, 6]
every i := 1 to *V do
if Q(i) ~= V[i] then stop("Assertion failure for position ",i)
printf("Q(1 to %d) - verified.\n",*V)
q := Q(n := 1000)
v := 502
printf("Q[%d]=%d - %s.\n",n,v,if q = v then "verified" else "failed")
invcount := 0
every i :=... |
Rewrite this program in Icon while keeping its functionality equivalent to the C version. | #include <stdio.h>
#include <stdlib.h>
#define N 100000
int main()
{
int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1;
q[1] = q[2] = 1;
for (i = 3; i <= N; i++)
q[i] = q[i - q[i - 1]] + q[i - q[i - 2]];
for (i = 1; i <= 10; i++)
printf("%d%c", q[i], i == 10 ? '\n' : ' ');
printf("%d\n", q[1000]);
f... | link printf
procedure main()
V := [1, 1, 2, 3, 3, 4, 5, 5, 6, 6]
every i := 1 to *V do
if Q(i) ~= V[i] then stop("Assertion failure for position ",i)
printf("Q(1 to %d) - verified.\n",*V)
q := Q(n := 1000)
v := 502
printf("Q[%d]=%d - %s.\n",n,v,if q = v then "verified" else "failed")
invcount := 0
every i :=... |
Change the programming language of this snippet from C to Icon without modifying what it does. | #include <stdio.h>
#include <string.h>
int match(const char *s, const char *p, int overlap)
{
int c = 0, l = strlen(p);
while (*s != '\0') {
if (strncmp(s++, p, l)) continue;
if (!overlap) s += l - 1;
c++;
}
return c;
}
int main()
{
... | procedure main()
every A := ![ ["the three truths","th"], ["ababababab","abab"] ] do
write("The string ",image(A[2])," occurs as a non-overlapping substring ",
countSubstring!A , " times in ",image(A[1]))
end
procedure countSubstring(s1,s2)
c := 0
s1 ? while tab(find(s2)) do {
move(*s2)
c... |
Write the same algorithm in Icon as shown in this C implementation. | #include <gtk/gtk.h>
void ok_hit(GtkButton *o, GtkWidget **w)
{
GtkMessageDialog *msg;
gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]);
const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]);
msg = (GtkMessageDialog *)
gtk_message_dialog_new(NULL,
GTK_DIALOG_MODAL,
(v==75000) ? GT... | procedure main()
WOpen("size=800,800") | stop("Unable to open window")
WWrite("Enter a string:")
s := WRead()
WWrite("You entered ",image(s))
WWrite("Enter the integer 75000:")
i := WRead()
if i := integer(i) then
WWrite("You entered: ",i)
else
WWrite(image(i)," isn't an integer")
WDone()
end
link graphics
|
Ensure the translated Icon code behaves exactly like the original C snippet. | #include <SDL/SDL.h>
#ifdef WITH_CAIRO
#include <cairo.h>
#else
#include <SDL/sge.h>
#endif
#include <cairo.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#ifdef WITH_CAIRO
#define PI 3.1415926535
#endif
#define SIZE 800
#define SCALE 5
#define BRANCHES 14
#define ROT... | procedure main()
WOpen("size=800,600", "bg=black", "fg=white") | stop("*** cannot open window")
drawtree(400,500,-90,9)
WDone()
end
link WOpen
procedure drawtree(x,y,angle,depth)
if depth > 0 then {
x2 := integer(x + cos(dtor(angle)) * depth * 10)
y2 := integer(y + sin(dtor(angle)) * depth * 10)
DrawLine(x,y... |
Port the following code from C to Icon with equivalent syntax and logic. | #include <stdio.h>
#include <stdlib.h>
#define LEN 3
int rand_idx(double *p, int n)
{
double s = rand() / (RAND_MAX + 1.0);
int i;
for (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++);
return i;
}
int main()
{
int user_action, my_action;
int user_rec[] = {0, 0, 0};
const char *names[] = { "Rock", "Paper", "Scisso... | link printf
procedure main()
printf("Welcome to Rock, Paper, Scissors.\n_
Rock beats scissors, Scissors beat paper, and Paper beats rock.\n\n")
historyP := ["rock","paper","scissors"]
winP := winC := draws := 0
beats := ["rock","scissors","paper","rock"]
repeat {
printf("En... |
Rewrite the snippet below in Icon so it works the same as the original C code. | #include <stdio.h>
static const char *dog = "Benjamin";
static const char *Dog = "Samba";
static const char *DOG = "Bernie";
int main()
{
printf("The three dogs are named %s, %s and %s.\n", dog, Dog, DOG);
return 0;
}
| procedure main()
dog := "Benjamin"
Dog := "Samba"
DOG := "Bernie"
if dog == DOG then
write("There is just one dog named ", dog,".")
else
write("The three dogs are named ", dog, ", ", Dog, " and ", DOG, ".")
end
|
Can you help me rewrite this code in Icon instead of C, keeping it the same logically? | #include <stdio.h>
#define SWAP(r,s) do{ t=r; r=s; s=t; } while(0)
void StoogeSort(int a[], int i, int j)
{
int t;
if (a[j] < a[i]) SWAP(a[i], a[j]);
if (j - i > 1)
{
t = (j - i + 1) / 3;
StoogeSort(a, i, j - t);
StoogeSort(a, i + t, j);
StoogeSort(a, i, j - t);
}
}
... | procedure main()
demosort(stoogesort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end
procedure stoogesort(X,op,i,j)
local t
if /i := 0 then {
j := *X
op := sortop(op,X)
}
if op(X[j],X[i]) then
X[i] :=: X[j]
if j - i > 1 then {
t := (j - i +... |
Translate the given C code snippet into Icon without altering its behavior. | #include <stdio.h>
void shell_sort (int *a, int n) {
int h, i, j, t;
for (h = n; h /= 2;) {
for (i = h; i < n; i++) {
t = a[i];
for (j = i; j >= h && t < a[j - h]; j -= h) {
a[j] = a[j - h];
}
a[j] = t;
}
}
}
int main (int ac,... | procedure main()
demosort(shellsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end
procedure shellsort(X,op)
local i,j,inc,temp
op := sortop(op,X)
inc := *X/2
while inc > 0 do {
every i := inc to *X do {
temp := X[j := i]
while op(temp,X... |
Produce a language-to-language conversion: from C to Icon, same semantics. | #include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <err.h>
int read_file_line(const char *path, int line_no)
{
struct stat s;
char *buf;
off_t start = -1, end = -1;
size_t i;
int ln, fd, ret = 1;
if (line_no == 1) start = 0;
else if (line_no < 1)... | procedure main()
write(readline("foo.bar.txt",7)|"failed")
end
procedure readline(f,n)
f := open(\f,"r") | fail
every i := n & line := |read(f) \ n do i -:= 1
close(f)
if i = 0 then return line
end
|
Transform the following C implementation into Icon, maintaining the same output and logic. | #include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <err.h>
int read_file_line(const char *path, int line_no)
{
struct stat s;
char *buf;
off_t start = -1, end = -1;
size_t i;
int ln, fd, ret = 1;
if (line_no == 1) start = 0;
else if (line_no < 1)... | procedure main()
write(readline("foo.bar.txt",7)|"failed")
end
procedure readline(f,n)
f := open(\f,"r") | fail
every i := n & line := |read(f) \ n do i -:= 1
close(f)
if i = 0 then return line
end
|
Please provide an equivalent version of this C code in Icon. | #include <stdio.h>
#include <stdlib.h>
#define otherwise do { register int _o = 2; do { switch (_o) { case 1:
#define given(Mc) ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)
int foo() { return 1; }
main()
{
int a = 0;
otherwise a = 4 given (foo());
... | procedure main()
raining := TRUE := 1
if \raining then needumbrella := TRUE
needumbrella := 1(TRUE, \raining)
end
|
Convert the following code from C to Icon, ensuring the logic remains intact. | #include <stdio.h>
#include <stdlib.h>
#define otherwise do { register int _o = 2; do { switch (_o) { case 1:
#define given(Mc) ;case 0: break; case 2: _o = !!(Mc); continue; } break; } while (1); } while (0)
int foo() { return 1; }
main()
{
int a = 0;
otherwise a = 4 given (foo());
... | procedure main()
raining := TRUE := 1
if \raining then needumbrella := TRUE
needumbrella := 1(TRUE, \raining)
end
|
Please provide an equivalent version of this C code in Icon. | #include <stdio.h>
#include <ctype.h>
char rfc3986[256] = {0};
char html5[256] = {0};
void encode(const char *s, char *enc, char *tb)
{
for (; *s; s++) {
if (tb[*s]) sprintf(enc, "%c", tb[*s]);
else sprintf(enc, "%%%02X", *s);
while (*++enc);
}
}
int main()
{
const char url[] = "http:
char enc[(s... | link hexcvt
procedure main()
write("text = ",image(u := "http://foo bar/"))
write("encoded = ",image(ue := encodeURL(u)))
end
procedure encodeURL(s)
static en
initial {
en := table()
every en[c := !string(~(&digits++&letters))] := "%"||hexstrin... |
Keep all operations the same but rewrite the snippet in Icon. | #include <stdio.h>
#include <ctype.h>
char rfc3986[256] = {0};
char html5[256] = {0};
void encode(const char *s, char *enc, char *tb)
{
for (; *s; s++) {
if (tb[*s]) sprintf(enc, "%c", tb[*s]);
else sprintf(enc, "%%%02X", *s);
while (*++enc);
}
}
int main()
{
const char url[] = "http:
char enc[(s... | link hexcvt
procedure main()
write("text = ",image(u := "http://foo bar/"))
write("encoded = ",image(ue := encodeURL(u)))
end
procedure encodeURL(s)
static en
initial {
en := table()
every en[c := !string(~(&digits++&letters))] := "%"||hexstrin... |
Translate this program into Icon but keep the logic exactly as in C. | #include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
typedef const char * String;
typedef struct sTable {
String * *rows;
int n_rows,n_cols;
} *Table;
typedef int (*CompareFctn)(String a, String b);
struct {
CompareFctn compare;
int column;
int ... |
procedure main()
X := [ [1,2,3], [2,3,1], [3,1,2])
Sort(X)
Sort(X,"ordering","numeric","column",2,"reverse")
end
procedure Sort(X,A[])
while a := get(A) do {
case a of {
... |
Port the provided C code into Icon while preserving the original functionality. | #include <stdio.h>
#include <ctype.h>
static int
owp(int odd)
{
int ch, ret;
ch = getc(stdin);
if (!odd) {
putc(ch, stdout);
if (ch == EOF || ch == '.')
return EOF;
if (ispunct(ch))
return 0;
... | procedure main()
every OddWord(!["what,is,the;meaning,of:life.",
"we,are;not,in,kansas;any,more."])
end
procedure OddWord(stream)
write("Input stream: ",stream)
writes("Output stream: ") & eWord(create !stream,'.,;:') & write()
end
procedure eWord(stream,marks) ... |
Generate an equivalent Icon version of this C code. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct rec_t rec_t;
struct rec_t {
int depth;
rec_t * p[10];
};
rec_t root = {0, {0}};
#define USE_POOL_ALLOC
#ifdef USE_POOL_ALLOC
rec_t *tail = 0, *head = 0;
#define POOL_SIZE (1 << 20)
inline rec_t *new_rec()
{
if (head == tail) {
head = cal... | link printf
procedure main()
every L := !longestselfrefseq(1000000) do
every printf(" %i : %i\n",i := 1 to *L,L[i])
end
procedure longestselfrefseq(N)
mlen := 0
every L := selfrefseq(n := 1 to N) do {
if mlen <:= *L then
ML := [L]
else if mlen = *L then
put(ML,L)
}
return ML
end
... |
Can you help me rewrite this code in Icon instead of C, keeping it the same logically? | #include <stdio.h>
inline int self_desc(unsigned long long xx)
{
register unsigned int d, x;
unsigned char cnt[10] = {0}, dig[10] = {0};
for (d = 0; xx > ~0U; xx /= 10)
cnt[ dig[d++] = xx % 10 ]++;
for (x = xx; x; x /= 10)
cnt[ dig[d++] = x % 10 ]++;
while(d-- && dig[x++] == cnt[d]);
return d == -1;
... | procedure count (test_item, str)
result := 0
every item := !str do
if test_item == item then result +:= 1
return result
end
procedure is_self_describing (n)
ns := string (n)
every i := 1 to *ns do {
if count (string(i-1), ns) ~= ns[i] then fail
}
return 1
end
procedure self_describing_number... |
Change the programming language of this snippet from C to Icon without modifying what it does. | #include <stdio.h>
#define N_COND 3
#define COND_LEN (1 << N_COND)
struct { const char *str, *truth;}
cond[N_COND] = {
{"Printer does not print", "1111...."},
{"A red light is flashing", "11..11.."},
{"Printer is unrecognised", "1.1.1.1."},
},
solu[] = {
{"Check the power cable", "..1....."},
{"Check the pr... | record cond(text,flags)
record act(text,flags,aflags)
procedure main()
DT := [
cond("Printer does not print", "YYYYNNNN"),
cond("A red light is flashing", "YYNNYYNN"),
cond("Printer is unrecognised", "YNYNYNYN"),
,
... |
Port the following code from C to Icon with equivalent syntax and logic. | #include <stdio.h>
#include <stdlib.h>
void bead_sort(int *a, int len)
{
int i, j, max, sum;
unsigned char *beads;
# define BEAD(i, j) beads[i * max + j]
for (i = 1, max = a[0]; i < len; i++)
if (a[i] > max) max = a[i];
beads = calloc(1, max * len);
for (i = 0; i < len; i++)
for (j = 0; j < a[i]; j++)
... | procedure main()
write("Sorting Demo using ",image(beadsort))
writes(" on list : ")
writex(UL := [3, 14, 1, 5, 9, 2, 6, 3])
displaysort(beadsort,copy(UL))
end
procedure beadsort(X)
local base,i,j,x
poles :... |
Rewrite the snippet below in Icon so it works the same as the original C code. | void runCode(const char *code)
{
int c_len = strlen(code);
int i, bottles;
unsigned accumulator=0;
for(i=0;i<c_len;i++)
{
switch(code[i])
{
case 'Q':
printf("%s\n", code);
break;
case 'H':
printf("Hello, world!\... | procedure main(A)
repeat writes("Enter HQ9+ code: ") & HQ9(get(A)|read()|break)
end
procedure HQ9(code)
static bnw,bcr
initial {
bnw := table(" bottles"); bnw[1] := " bottle"; bnw[0] := "No more bottles"
bcr := table("\n"); bcr[0]:=""
}
every c := map(!code) do
case c of { ... |
Can you help me rewrite this code in Icon instead of C, keeping it the same logically? | void runCode(const char *code)
{
int c_len = strlen(code);
int i, bottles;
unsigned accumulator=0;
for(i=0;i<c_len;i++)
{
switch(code[i])
{
case 'Q':
printf("%s\n", code);
break;
case 'H':
printf("Hello, world!\... | procedure main(A)
repeat writes("Enter HQ9+ code: ") & HQ9(get(A)|read()|break)
end
procedure HQ9(code)
static bnw,bcr
initial {
bnw := table(" bottles"); bnw[1] := " bottle"; bnw[0] := "No more bottles"
bcr := table("\n"); bcr[0]:=""
}
every c := map(!code) do
case c of { ... |
Convert this C snippet to Icon and keep its semantics consistent. | #include <stdio.h>
#include <stdlib.h>
#include <locale.h>
int locale_ok = 0;
wchar_t s_suits[] = L"♠♥♦♣";
const char *s_suits_ascii[] = { "S", "H", "D", "C" };
const char *s_nums[] = { "WHAT",
"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K",
"OVERFLOW"
};
typedef struct { int suit, number, _s;... | procedure main(arglist)
cards := 2
players := 5
write("New deck : ", showcards(D := newcarddeck()))
write("Shuffled : ", showcards(D := shufflecards(D)))
H := list(players)
every H[1 to players] :... |
Generate a Icon translation of this C snippet without changing its computational steps. | #include<stdio.h>
typedef struct{
int a;
}layer1;
typedef struct{
layer1 l1;
float b,c;
}layer2;
typedef struct{
layer2 l2;
layer1 l1;
int d,e;
}layer3;
void showCake(layer3 cake){
printf("\ncake.d = %d",cake.d);
printf("\ncake.e = %d",cake.e);
printf("\ncake.l1.a = %d",cake.l1.a);
printf("\ncake.l2.b = %... | link printf,ximage
procedure main()
knot := makeknot()
knota := knot
knotc := copy(knot)
knotdc := deepcopy(knot)
showdeep("knota (assignment) vs. knot",knota,knot)
showdeep("knotc (copy) vs. knot",knotc,knot)
showdeep("knotdc (deepcopy) vs. knot",knotdc,... |
Transform the following C implementation into Icon, maintaining the same output and logic. | #include<stdio.h>
typedef struct{
int a;
}layer1;
typedef struct{
layer1 l1;
float b,c;
}layer2;
typedef struct{
layer2 l2;
layer1 l1;
int d,e;
}layer3;
void showCake(layer3 cake){
printf("\ncake.d = %d",cake.d);
printf("\ncake.e = %d",cake.e);
printf("\ncake.l1.a = %d",cake.l1.a);
printf("\ncake.l2.b = %... | link printf,ximage
procedure main()
knot := makeknot()
knota := knot
knotc := copy(knot)
knotdc := deepcopy(knot)
showdeep("knota (assignment) vs. knot",knota,knot)
showdeep("knotc (copy) vs. knot",knotc,knot)
showdeep("knotdc (deepcopy) vs. knot",knotdc,... |
Generate an equivalent Icon version of this C code. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int(*cmp_func)(const void*, const void*);
void perm_sort(void *a, int n, size_t msize, cmp_func _cmp)
{
char *p, *q, *tmp = malloc(msize);
# define A(i) ((char *)a + msize * (i))
# define swap(a, b) {\
memcpy(tmp, a, msize);\
memcpy(a, b, msize);... | procedure do_permute(l, i, n)
if i >= n then
return l
else
suspend l[i to n] <-> l[i] & do_permute(l, i+1, n)
end
procedure permute(l)
suspend do_permute(l, 1, *l)
end
procedure sorted(l)
local i
if (i := 2 to *l & l[i] >= l[i-1]) then return &fail else return 1
end
proce... |
Change the following C code into Icon without altering its purpose. | #include<windows.h>
#include<unistd.h>
#include<stdio.h>
const char g_szClassName[] = "weirdWindow";
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitM... | link graphics
procedure main()
Delay := 3000
W1 := open("Window 1","g","resize=on","size=400,400","pos=100,100","bg=black","fg=red") |
stop("Unable to open window 1")
W2 := open("Window 2","g","resize=on","size=400,400","pos=450,450","bg=blue","fg=yellow") |
stop("Unable to open window 2")... |
Ensure the translated Icon code behaves exactly like the original C snippet. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BALLS 1024
int n, w, h = 45, *x, *y, cnt = 0;
char *b;
#define B(y, x) b[(y)*w + x]
#define C(y, x) ' ' == b[(y)*w + x]
#define V(i) B(y[i], x[i])
inline int rnd(int a) { return (rand()/(RAND_MAX/a))%a; }
void show_board()
{
int i, j;
for (puts("\0... | link graphics
global pegsize, pegsize2, height, width, delay
procedure main(args)
pegsize2 := (pegsize := 10) * 2
delay := 2
setup_galtonwindow(pegsize)
n := integer(args[1]) | 100
every 1 to n do galton(pegsize)
WDone()
end
procedure setup_galtonwindow(n) ... |
Change the programming language of this snippet from C to Icon without modifying what it does. | #include <X11/Xlib.h>
void
get_pixel_color (Display *d, int x, int y, XColor *color)
{
XImage *image;
image = XGetImage (d, RootWindow (d, DefaultScreen (d)), x, y, 1, 1, AllPlanes, XYPixmap);
color->pixel = XGetPixel (image, 0, 0);
XFree (image);
XQueryColor (d, DefaultColormap(d, DefaultScreen (d)), color);... | link graphics,printf
procedure main()
WOpen("canvas=hidden")
height := WAttrib("displayheight") - 45
width := WAttrib("displaywidth") - 20
WClose(&window)
W := WOpen("size="||width||","||height,"bg=black") |
stop("Unable to open window")
every 1 to 10 do ... |
Produce a functionally identical Icon code for the snippet given in C. |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "wren.h"
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *m... | link printf,strings
procedure main()
YS := YahooSearch("rosettacode")
every 1 to 2 do {
YS.readnext()
YS.showinfo()
}
end
class YahooSearch(urlpat,page,response)
method readnext()
self.page +:= 1
readurl()
end
method readurl()
url := sprintf(self.urlpat,(s... |
Translate this program into Icon but keep the logic exactly as in C. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
long long x, y, dx, dy, scale, clen, cscale;
typedef struct { double r, g, b; } rgb;
rgb ** pix;
void sc_up()
{
scale *= 2; x *= 2; y *= 2;
cscale *= 3;
}
void h_rgb(long long x, long long y)
{
rgb *p = &pix[y][x];
# define SAT 1
d... | link wopen
procedure main(A)
local width, margin, x, y
width := 2 ^ (order := (0 < integer(\A[1])) | 8)
wsize := width + 2 * (margin := 30 )
WOpen("label=Sierpinski", "size="||wsize||","||wsize) |
stop("*** cannot open window")
every y := 0 to width - 1 do
every x := 0 to width - 1 do
... |
Generate an equivalent Icon version of this C code. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
long long x, y, dx, dy, scale, clen, cscale;
typedef struct { double r, g, b; } rgb;
rgb ** pix;
void sc_up()
{
scale *= 2; x *= 2; y *= 2;
cscale *= 3;
}
void h_rgb(long long x, long long y)
{
rgb *p = &pix[y][x];
# define SAT 1
d... | link wopen
procedure main(A)
local width, margin, x, y
width := 2 ^ (order := (0 < integer(\A[1])) | 8)
wsize := width + 2 * (margin := 30 )
WOpen("label=Sierpinski", "size="||wsize||","||wsize) |
stop("*** cannot open window")
every y := 0 to width - 1 do
every x := 0 to width - 1 do
... |
Can you help me rewrite this code in Icon instead of C, keeping it the same logically? | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N_SITES 150
double site[N_SITES][2];
unsigned char rgb[N_SITES][3];
int size_x = 640, size_y = 480;
inline double sq2(double x, double y)
{
return x * x + y * y;
}
#define for_k for (k = 0; k < N_SITES; k++)
int nearest_site(double x, double y)
{
... | link graphics,printf,strings
record site(x,y,colour)
invocable all
procedure main(A)
&window := open("Voronoi","g","bg=black") | stop("Unable to open window")
WAttrib("canvas=hidden")
WAttrib(sprintf("size=%d,%d",WAttrib("displaywidth"),WAttrib("displayheight")))
WAttrib("canvas=maximal")
he... |
Port the provided C code into Icon while preserving the original functionality. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N_SITES 150
double site[N_SITES][2];
unsigned char rgb[N_SITES][3];
int size_x = 640, size_y = 480;
inline double sq2(double x, double y)
{
return x * x + y * y;
}
#define for_k for (k = 0; k < N_SITES; k++)
int nearest_site(double x, double y)
{
... | link graphics,printf,strings
record site(x,y,colour)
invocable all
procedure main(A)
&window := open("Voronoi","g","bg=black") | stop("Unable to open window")
WAttrib("canvas=hidden")
WAttrib(sprintf("size=%d,%d",WAttrib("displaywidth"),WAttrib("displayheight")))
WAttrib("canvas=maximal")
he... |
Preserve the algorithm and functionality while converting the code from C to Icon. | #include <stdio.h>
int main(int argc, char **argv){
int i;
const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL};
enum {CREATE,PRINT,TITLE,DATE,AUTH};
if (argc<2) {
usage: printf ("Usage: %s [commands]\n"
"-c Create new entry.\n"
"-p Print the latest entry.\n"
... | link options
procedure main(ARGLIST)
/errproc := stop
opstring := "f!s:i+r.flag!string:integer+real."
opttable := options(ARGLIST,optstring,errproc)
if \opttable[flag] then ...
r := opttable(real)
r2 := opttable(r)
s := opttable(s)
i := opttab... |
Ensure the translated Icon code behaves exactly like the original C snippet. | #include <stdio.h>
int main(int argc, char **argv){
int i;
const char *commands[]={"-c", "-p", "-t", "-d", "-a", NULL};
enum {CREATE,PRINT,TITLE,DATE,AUTH};
if (argc<2) {
usage: printf ("Usage: %s [commands]\n"
"-c Create new entry.\n"
"-p Print the latest entry.\n"
... | link options
procedure main(ARGLIST)
/errproc := stop
opstring := "f!s:i+r.flag!string:integer+real."
opttable := options(ARGLIST,optstring,errproc)
if \opttable[flag] then ...
r := opttable(real)
r2 := opttable(r)
s := opttable(s)
i := opttab... |
Translate the given C code snippet into Icon without altering its behavior. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
#include <glib.h>
#define ROWS 4
#define COLS 10
#define NPRX "/"
const char *table[ROWS][COLS] =
{
{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" },
{ "H", "O", "L", NULL, "M", "E", "S", NULL, "R", ... | procedure main()
StraddlingCheckerBoard("setup","HOLMESRTABCDFGIJKNPQUVWXYZ./", 3,7)
text := "One night. it was on the twentieth of March, 1888. I was returning"
write("text = ",image(text))
write("encode = ",image(en := StraddlingCheckerBoard("encode",text)))
write("decode = ",image(StraddlingCheckerBoard("decode",... |
Produce a functionally identical Icon code for the snippet given in C. | #include <string.h>
#include <memory.h>
static unsigned int _parseDecimal ( const char** pchCursor )
{
unsigned int nVal = 0;
char chNow;
while ( chNow = **pchCursor, chNow >= '0' && chNow <= '9' )
{
nVal *= 10;
nVal += chNow - '0';
++*pchCursor;
}
return nVal... | link printf, hexcvt
procedure main()
L := ["192.168.0.1",
"127.0.0.1",
"127.0.0.1:80",
"2001:db8:85a3:0:0:8a2e:370:7334",
"2001:db8:85a3::8a2e:370:7334",
... |
Generate an equivalent Icon version of this C code. | count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
|
record token_record (line_no, column_no, tok, tokval)
record token_getter (nxt, curr)
procedure main (args)
local inpf_name, outf_name
local inpf, outf
local nexttok, currtok, current_token, gettok
local ast
inpf_name := "-"
outf_name := "-"
if 1 <= *args then inpf_name := args[1]
if 2 <= *... |
Transform the following C implementation into Icon, maintaining the same output and logic. | count = 1;
while (count < 10) {
print("count is: ", count, "\n");
count = count + 1;
}
|
record token_record (line_no, column_no, tok, tokval)
record token_getter (nxt, curr)
procedure main (args)
local inpf_name, outf_name
local inpf, outf
local nexttok, currtok, current_token, gettok
local ast
inpf_name := "-"
outf_name := "-"
if 1 <= *args then inpf_name := args[1]
if 2 <= *... |
Convert this C block to Icon, preserving its control flow and logic. | #include<stdio.h>
#include<ctype.h>
void typeDetector(char* str){
if(isalnum(str[0])!=0)
printf("\n%c is alphanumeric",str[0]);
if(isalpha(str[0])!=0)
printf("\n%c is alphabetic",str[0]);
if(iscntrl(str[0])!=0)
printf("\n%c is a control character",str[0]);
if(isdigit(str[0])!=0)
printf("\n%c is a digit",s... | procedure main()
print_text("This\nis\na text.\n")
print_text(open("type_detection-icon.icn"))
end
procedure print_text(source)
case type(source) of {
"string" : writes(source)
"file" : while write(read(source))
}
end
|
Maintain the same structure and functionality when rewriting this code in Icon. | #include <stdio.h>
typedef struct {int val, op, left, right;} Node;
Node nodes[10000];
int iNodes;
int b;
float eval(Node x){
if (x.op != -1){
float l = eval(nodes[x.left]), r = eval(nodes[x.right]);
switch(x.op){
case 0: return l+r;
case 1: return l-r;
case 2:... | invocable all
link strings
procedure main()
static eL
initial {
eoP := []
every ( e := !["a@b
( o := !(opers := "+-*/") || !opers || !opers ) do
put( eoP, map(e,"@
eL := []
every ( e := !eoP ) & ( p := permutes("wxyz") ) do
put(eL, map(e,"abcd",p))
}
write("This will ... |
Maintain the same structure and functionality when rewriting this code in Icon. | #include <stdio.h>
typedef struct {int val, op, left, right;} Node;
Node nodes[10000];
int iNodes;
int b;
float eval(Node x){
if (x.op != -1){
float l = eval(nodes[x.left]), r = eval(nodes[x.right]);
switch(x.op){
case 0: return l+r;
case 1: return l-r;
case 2:... | invocable all
link strings
procedure main()
static eL
initial {
eoP := []
every ( e := !["a@b
( o := !(opers := "+-*/") || !opers || !opers ) do
put( eoP, map(e,"@
eL := []
every ( e := !eoP ) & ( p := permutes("wxyz") ) do
put(eL, map(e,"abcd",p))
}
write("This will ... |
Translate the given C code snippet into Icon without altering its behavior. | #include <stdio.h>
#define JOBS 12
#define jobs(a) for (switch_to(a = 0); a < JOBS || !printf("\n"); switch_to(++a))
typedef struct { int seq, cnt; } env_t;
env_t env[JOBS] = {{0, 0}};
int *seq, *cnt;
void hail()
{
printf("% 4d", *seq);
if (*seq == 1) return;
++*cnt;
*seq = (*seq & 1) ? 3 * *seq + 1 : *seq / 2;
... | link printf
procedure main()
every put(environment := [], hailenv(1 to 12,0))
printf("Sequences:\n")
while (e := !environment).sequence > 1 do {
every hailstep(!environment)
printf("\n")
}
printf("\nCounts:\n")
every printf("%4d ",(!environment).count)
printf("\n")
end
record h... |
Transform the following C implementation into Icon, maintaining the same output and logic. | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define USE_FAKES 1
const char *states[] = {
#if USE_FAKES
"New Kory", "Wen Kory", "York New", "Kory New", "New Kory",
#endif
"Alabama", "Alaska", "Arizona", "Arkansas",
"California", "Colorado", "Connecticut",
"Delaware",
"Florida", "Georgia", "Hawa... | link strings
procedure main(arglist)
ECsolve(S1 := getStates())
ECsolve(S2 := getStates2())
GNsolve(S1)
GNsolve(S2)
end
procedure ECsolve(S)
local T,x,y,z,i,t,s,l,m
st := &time
/S := getStates()
every insert(states := set(),delet... |
Convert the following code from C to Icon, ensuring the logic remains intact. | '--- added a flush to exit cleanly
PRAGMA LDFLAGS `pkg-config --cflags --libs x11`
PRAGMA INCLUDE <X11/Xlib.h>
PRAGMA INCLUDE <X11/Xutil.h>
OPTION PARSE FALSE
'---XLIB is so ugly
ALIAS XNextEvent TO EVENT
ALIAS XOpenDisplay TO DISPLAY
ALIAS DefaultScreen TO SCREEN
ALIAS XCreateSimpleWindow TO CREATE
ALIAS XCloseD... | procedure main()
W1 := open("X-Window","g","size=250,250","bg=black","fg=red") | stop("unable to open window")
FillRectangle(W1,50,50,150,150)
WDone(W1)
end
link graphics
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.