Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Produce a functionally identical Clojure code for the snippet given in VB.
Sub foo1() err.raise(vbObjectError + 1050) End Sub Sub foo2() Error vbObjectError + 1051 End Sub
(try (if (> (rand) 0.5) (throw (RuntimeException. "oops!")) (println "see this half the time") (catch RuntimeException e (println e) (finally (println "always see this"))
Keep all operations the same but rewrite the snippet in Clojure.
Sub Rosetta_24game() Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer Dim stUserExpression As String Dim stFailMessage As String, stFailDigits As String Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant G...
(ns rosettacode.24game) (def ^:dynamic *luser* "You guessed wrong, or your input was not in prefix notation.") (def ^:private start #(println "Your numbers are: " %1 ". Your goal is " %2 ".\n" "Use the ops [+ - * /] in prefix notation to reach" %2 ".\n" "q[enter] to quit.")) (defn play ([] (play 24)) ([goal] (p...
Maintain the same structure and functionality when rewriting this code in Clojure.
Sub Rosetta_24game() Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer Dim stUserExpression As String Dim stFailMessage As String, stFailDigits As String Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant G...
(ns rosettacode.24game) (def ^:dynamic *luser* "You guessed wrong, or your input was not in prefix notation.") (def ^:private start #(println "Your numbers are: " %1 ". Your goal is " %2 ".\n" "Use the ops [+ - * /] in prefix notation to reach" %2 ".\n" "q[enter] to quit.")) (defn play ([] (play 24)) ([goal] (p...
Convert this VB snippet to Clojure and keep its semantics consistent.
Public Q(100000) As Long Public Sub HofstadterQ() Dim n As Long, smaller As Long Q(1) = 1 Q(2) = 1 For n = 3 To 100000 Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2)) If Q(n) < Q(n - 1) Then smaller = smaller + 1 Next n Debug.Print "First ten terms:" For i = 1 To 10 Debug.Pr...
(defn qs [q] (let [n (count q)] (condp = n 0 [1] 1 [1 1] (conj q (+ (q (- n (q (- n 1)))) (q (- n (q (- n 2))))))))) (defn qfirst [n] (-> (iterate qs []) (nth n))) (println "first 10:" (qfirst 10)) (println "1000th:" (last (qfirst 1000))) (println "extra credit:" (->> (qfirst ...
Generate a Clojure translation of this VB snippet without changing its computational steps.
Public Q(100000) As Long Public Sub HofstadterQ() Dim n As Long, smaller As Long Q(1) = 1 Q(2) = 1 For n = 3 To 100000 Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2)) If Q(n) < Q(n - 1) Then smaller = smaller + 1 Next n Debug.Print "First ten terms:" For i = 1 To 10 Debug.Pr...
(defn qs [q] (let [n (count q)] (condp = n 0 [1] 1 [1 1] (conj q (+ (q (- n (q (- n 1)))) (q (- n (q (- n 2))))))))) (defn qfirst [n] (-> (iterate qs []) (nth n))) (println "first 10:" (qfirst 10)) (println "1000th:" (last (qfirst 1000))) (println "extra credit:" (->> (qfirst ...
Write a version of this VB function in Clojure with identical behavior.
Public Sub Main() Print countSubstring("the three truths", "th") Print countSubstring("ababababab", "abab") Print countSubString("zzzzzzzzzzzzzzz", "z") End Function countSubstring(s As String, search As String) As Integer If s = "" Or search = "" Then Return 0 Dim count As Integer = 0, length As ...
(defn re-quote "Produces a string that can be used to create a Pattern that would match the string text as if it were a literal pattern. Metacharacters or escape sequences in text will be given no special meaning" [text] (java.util.regex.Pattern/quote text)) (defn count-substring [txt sub] (count (re-...
Port the following code from VB to Clojure with equivalent syntax and logic.
type TSettings extends QObject FullName as string FavouriteFruit as string NeedSpelling as integer SeedsRemoved as integer OtherFamily as QStringlist Constructor FullName = "" FavouriteFruit = "" NeedSpelling = 0 SeedsRemoved = 0 OtherFamily.clear ...
(ns read-conf-file.core (:require [clojure.java.io :as io] [clojure.string :as str]) (:gen-class)) (def conf-keys ["fullname" "favouritefruit" "needspeeling" "seedsremoved" "otherfamily"]) (defn get-lines "Read file returning vec of lin...
Maintain the same structure and functionality when rewriting this code in Clojure.
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbrevia...
(defn words [str] "Split string into words" (.split str "\\s+")) (defn join-words [strings] "Join words into a single string" (clojure.string/join " " strings)) (def cmd-table "Command Table - List of words to match against" (words "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPre...
Can you help me rewrite this code in Clojure instead of VB, keeping it the same logically?
Private Function ValidateUserWords(userstring As String) As String Dim s As String Dim user_words() As String Dim command_table As Scripting.Dictionary Set command_table = New Scripting.Dictionary Dim abbreviations As Scripting.Dictionary Set abbreviations = New Scripting.Dictionary abbrevia...
(defn words [str] "Split string into words" (.split str "\\s+")) (defn join-words [strings] "Join words into a single string" (clojure.string/join " " strings)) (def cmd-table "Command Table - List of words to match against" (words "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPre...
Change the following VB code into Clojure without altering its purpose.
Sub truncate(fpath,n) Set objfso = CreateObject("Scripting.FileSystemObject") If objfso.FileExists(fpath) = False Then WScript.Echo fpath & " does not exist" Exit Sub End If content = "" Set objinstream = CreateObject("Adodb.Stream") With objinstream .Type = 1 .Open .LoadFromFile(fpath) If n <=...
(defn truncate [file size] (with-open [chan (.getChannel (java.io.FileOutputStream. file true))] (.truncate chan size))) (truncate "truncate_test.txt" 2)
Write the same code in Clojure as shown below in VB.
Sub truncate(fpath,n) Set objfso = CreateObject("Scripting.FileSystemObject") If objfso.FileExists(fpath) = False Then WScript.Echo fpath & " does not exist" Exit Sub End If content = "" Set objinstream = CreateObject("Adodb.Stream") With objinstream .Type = 1 .Open .LoadFromFile(fpath) If n <=...
(defn truncate [file size] (with-open [chan (.getChannel (java.io.FileOutputStream. file true))] (.truncate chan size))) (truncate "truncate_test.txt" 2)
Write the same algorithm in Clojure as shown in this VB implementation.
Function read_line(filepath,n) Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(filepath,1) arrLines = Split(objFile.ReadAll,vbCrLf) If UBound(arrLines) >= n-1 Then If arrLines(n-1) <> "" Then read_line = arrLines(n-1) Else read_line = "Line " & n & " is null." E...
(defn read-nth-line "Read line-number from the given text file. The first line has the number 1." [file line-number] (with-open [rdr (clojure.java.io/reader file)] (nth (line-seq rdr) (dec line-number))))
Keep all operations the same but rewrite the snippet in Clojure.
Function read_line(filepath,n) Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile(filepath,1) arrLines = Split(objFile.ReadAll,vbCrLf) If UBound(arrLines) >= n-1 Then If arrLines(n-1) <> "" Then read_line = arrLines(n-1) Else read_line = "Line " & n & " is null." E...
(defn read-nth-line "Read line-number from the given text file. The first line has the number 1." [file line-number] (with-open [rdr (clojure.java.io/reader file)] (nth (line-seq rdr) (dec line-number))))
Can you help me rewrite this code in Clojure instead of VB, keeping it the same logically?
Dim URL As String = "http://foo bar/" URL = EncodeURLComponent(URL) Print(URL)
(import 'java.net.URLEncoder) (URLEncoder/encode "http://foo bar/" "UTF-8")
Generate a Clojure translation of this VB snippet without changing its computational steps.
Dim URL As String = "http://foo bar/" URL = EncodeURLComponent(URL) Print(URL)
(import 'java.net.URLEncoder) (URLEncoder/encode "http://foo bar/" "UTF-8")
Please provide an equivalent version of this VB code in Clojure.
Private Sub optional_parameters(theRange As String, _ Optional ordering As Integer = 0, _ Optional column As Integer = 1, _ Optional reverse As Integer = 1) ActiveSheet.Sort.SortFields.Clear ActiveSheet.Sort.SortFields.Add _ Key:=Range(theRange).Columns(column), _ SortOn:...
(defn sort [table & {:keys [ordering column reverse?] :or {ordering :lex, column 1}}] (println table ordering column reverse?)) (sort [1 8 3] :reverse? true) [1 8 3] :lex 1 true
Rewrite the snippet below in Clojure so it works the same as the original VB code.
Option Explicit Function JaroWinkler(text1 As String, text2 As String, Optional p As Double = 0.1) As Double Dim dummyChar, match1, match2 As String Dim i, f, t, j, m, l, s1, s2, limit As Integer i = 1 Do dummyChar = Chr(i) i = i + 1 Loop Until InStr(1, text1 & text2, dummyChar, vbTextCompare) = 0 s1 = Len(t...
(ns test-project-intellij.core (:gen-class)) (defn find-matches [s t] " find match locations in the two strings " " s_matches is set to true wherever there is a match in t and t_matches is set conversely " (let [s_len (count s) t_len (count t) match_distance (int (- (/ (max s_len t_len) 2) 1)) ...
Convert the following code from VB to Clojure, ensuring the logic remains intact.
Private Function OddWordFirst(W As String) As String Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String count = 1 Do flag = Not flag l = FindNextPunct(i, W) - count + 1 If flag Then temp = temp & ExtractWord(W, count, l) Else temp = temp & R...
(defn next-char [] (char (.read *in*))) (defn forward [] (let [ch (next-char)] (print ch) (if (Character/isLetter ch) (forward) (not= ch \.)))) (defn backward [] (let [ch (next-char)] (if (Character/isLetter ch) (let [result (backward)] (print ch) result) (fn ...
Write the same algorithm in Clojure as shown in this VB implementation.
Friend Class Tile Public Sub New() Me.Value = 0 Me.IsBlocked = False End Sub Public Property Value As Integer Public Property IsBlocked As Boolean End Class Friend Enum MoveDirection Up Down Left Right End Enum Friend Class G2048 Public Sub New() ...
(ns 2048 (:require [clojure.string :as str])) (def textures {:wall "----+" :cell "%4s|" :cell-edge "|" :wall-edge "+"}) (def directions {:w :up :s :down :a :left :d :right}) (def field-size {:y 4 :x 4}) (de...
Port the provided VB code into Clojure while preserving the original functionality.
Function Multiply(a As Integer, b As Integer) As Integer Return a * b End Function
(defn multiply [a b] (* a b))
Produce a functionally identical Clojure code for the snippet given in VB.
s=7*8*9 m=9876432 for i=(m\s)*s to 1 step -s if instr(i,"5")=0 and instr(i,"0")=0 then b=false: j=1 while j<=len(i)-1 and not b if instr(j+1,i,mid(i,j,1))<>0 then b=true j=j+1 wend if not b then j=1 while j<=len(i) and not b if (i mod mid(i,j,1))<>0 then b=true j=...
(require '[clojure.string :as str]) (def the_base 16) (def digits (rest (range the_base))) (def primes []) (for [n digits] (if (= 1 (count (filter (fn[m] (and (< m n) (= 0 (mod n m)))) digits)) ) (def primes (conj primes n)))) (defn duplicity [n p partial] (if (= 0 (mod n p)) (duplicity (/ n p) p (conj partial...
Transform the following VB implementation into Clojure, maintaining the same output and logic.
s=7*8*9 m=9876432 for i=(m\s)*s to 1 step -s if instr(i,"5")=0 and instr(i,"0")=0 then b=false: j=1 while j<=len(i)-1 and not b if instr(j+1,i,mid(i,j,1))<>0 then b=true j=j+1 wend if not b then j=1 while j<=len(i) and not b if (i mod mid(i,j,1))<>0 then b=true j=...
(require '[clojure.string :as str]) (def the_base 16) (def digits (rest (range the_base))) (def primes []) (for [n digits] (if (= 1 (count (filter (fn[m] (and (< m n) (= 0 (mod n m)))) digits)) ) (def primes (conj primes n)))) (defn duplicity [n p partial] (if (= 0 (mod n p)) (duplicity (/ n p) p (conj partial...
Generate an equivalent Clojure version of this VB code.
Option Explicit Dim objFSO, DBSource Set objFSO = CreateObject("Scripting.FileSystemObject") DBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\postal_address.accdb" With CreateObject("ADODB.Connection") .Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBSource .Execute "CREATE TABLE ADDRE...
(require '[clojure.java.jdbc :as sql]) (def db {:classname "org.h2.Driver" :subprotocol "h2:file" :subname "db/my-dbname"}) (sql/db-do-commands db (sql/create-table-ddl :address [:id "bigint primary key auto_increment"] [:street "varchar"] [:city "varchar"] [:state "varcha...
Produce a language-to-language conversion: from VB to Clojure, same semantics.
Option Base 1 Private Function sq_add(arr As Variant, x As Double) As Variant Dim res() As Variant ReDim res(UBound(arr)) For i = 1 To UBound(arr) res(i) = arr(i) + x Next i sq_add = res End Function Private Function beadsort(ByVal a As Variant) As Variant Dim poles() As Variant Re...
(defn transpose [xs] (loop [ret [], remain xs] (if (empty? remain) ret (recur (conj ret (map first remain)) (filter not-empty (map rest remain)))))) (defn bead-sort [xs] (->> xs (map #(repeat % 1)) transpose transpose (map #(reduce + %)))) (-> [5 2 4 ...
Ensure the translated Clojure code behaves exactly like the original VB snippet.
Public Sub Main() Print "The tau functions for the first 100 positive integers are:\n" For i As Integer = 1 To 100 Print Format$(numdiv(i), "####"); If i Mod 10 = 0 Then Print Next End Public Function numdiv(n As Integer) As Integer Dim c As Integer = 1 For i As Integer = 1 To (n + 1...
(require '[clojure.string :refer [join]]) (require '[clojure.pprint :refer [cl-format]]) (defn divisors [n] (filter #(zero? (rem n %)) (range 1 (inc n)))) (defn display-results [label per-line width nums] (doall (map println (cons (str "\n" label ":") (list (join "\n" (map #(join " " %) (partition-all pe...
Change the programming language of this snippet from VB to Clojure without modifying what it does.
Public Sub Main() Print "The tau functions for the first 100 positive integers are:\n" For i As Integer = 1 To 100 Print Format$(numdiv(i), "####"); If i Mod 10 = 0 Then Print Next End Public Function numdiv(n As Integer) As Integer Dim c As Integer = 1 For i As Integer = 1 To (n + 1...
(require '[clojure.string :refer [join]]) (require '[clojure.pprint :refer [cl-format]]) (defn divisors [n] (filter #(zero? (rem n %)) (range 1 (inc n)))) (defn display-results [label per-line width nums] (doall (map println (cons (str "\n" label ":") (list (join "\n" (map #(join " " %) (partition-all pe...
Change the following VB code into Clojure without altering its purpose.
Function BFInpt(s, sp, d, dp, i, ip, o) While sp < Len(s) Select Case Mid(s, sp + 1, 1) Case "+" newd = Asc(d(dp)) + 1 If newd > 255 Then newd = newd Mod 256 d(dp) = Chr(newd) Case "-" newd = Asc(d(dp)) - 1 ...
(ns brainfuck) (def ^:dynamic *input*) (def ^:dynamic *output*) (defrecord Data [ptr cells]) (defn inc-ptr [next-cmd] (fn [data] (next-cmd (update-in data [:ptr] inc)))) (defn dec-ptr [next-cmd] (fn [data] (next-cmd (update-in data [:ptr] dec)))) (defn inc-cell [next-cmd] (fn [data] (next-cmd (u...
Write a version of this VB function in Clojure with identical behavior.
Function BFInpt(s, sp, d, dp, i, ip, o) While sp < Len(s) Select Case Mid(s, sp + 1, 1) Case "+" newd = Asc(d(dp)) + 1 If newd > 255 Then newd = newd Mod 256 d(dp) = Chr(newd) Case "-" newd = Asc(d(dp)) - 1 ...
(ns brainfuck) (def ^:dynamic *input*) (def ^:dynamic *output*) (defrecord Data [ptr cells]) (defn inc-ptr [next-cmd] (fn [data] (next-cmd (update-in data [:ptr] inc)))) (defn dec-ptr [next-cmd] (fn [data] (next-cmd (update-in data [:ptr] dec)))) (defn inc-cell [next-cmd] (fn [data] (next-cmd (u...
Write a version of this VB function in Clojure with identical behavior.
suite$ = "CDHS" #Club, Diamond, Heart, Spade card$ = "A23456789TJQK" #Cards Ace to King card = 0 dim n(55) #make ordered deck for i = 1 to 52 # of 52 cards n[i] = i next i for i = 1 to 52 * 3 #shuffle deck 3 times i1 = int(rand * 5...
(def suits [:club :diamond :heart :spade]) (def pips [:ace 2 3 4 5 6 7 8 9 10 :jack :queen :king]) (defn deck [] (for [s suits p pips] [s p])) (def shuffle clojure.core/shuffle) (def deal first) (defn output [deck] (doseq [[suit pip] deck] (println (format "%s of %ss" (if (keyword? pip) (na...
Rewrite the snippet below in Clojure so it works the same as the original VB code.
print "The first 100 tau numbers are:" n = 0 num = 0 limit = 100 while num < limit n = n +1 tau = 0 for m = 1 to n if n mod m = 0 then tau = tau +1 next m if n mod tau = 0 then num = num +1 if num mod 10 = 1 then print print using("######", n); end if wend end
(require '[clojure.string :refer [join]]) (require '[clojure.pprint :refer [cl-format]]) (defn divisors [n] (filter #(zero? (rem n %)) (range 1 (inc n)))) (defn display-results [label per-line width nums] (doall (map println (cons (str "\n" label ":") (list (join "\n" (map #(join " " %) (partition-all pe...
Please provide an equivalent version of this VB code in Clojure.
sub ensure_cscript() if instrrev(ucase(WScript.FullName),"WSCRIPT.EXE")then createobject("wscript.shell").run "CSCRIPT //nologo """ &_ WScript.ScriptFullName &"""" ,,0 wscript.quit end if end sub class bargraph private bar,mn,mx,nn,cnt Private sub class_initialize() bar=chrw(&h2581)&chrw(&h258...
(defn sparkline [nums] (let [sparks "▁▂▃▄▅▆▇█" high (apply max nums) low (apply min nums) spread (- high low) quantize #(Math/round (* 7.0 (/ (- % low) spread)))] (apply str (map #(nth sparks (quantize %)) nums)))) (defn spark [line] (if line (let [nums (rea...
Generate a Clojure translation of this VB snippet without changing its computational steps.
Sub Lis(arr() As Integer) Dim As Integer lb = Lbound(arr), ub = Ubound(arr) Dim As Integer i, lo, hi, mitad, newl, l = 0 Dim As Integer p(ub), m(ub) For i = lb To ub lo = 1 hi = l Do While lo <= hi mitad = Int((lo+hi)/2) If arr(m(mitad)) < arr(i) Then lo = mitad + 1 Else h...
(defn place [piles card] (let [[les gts] (->> piles (split-with #(<= (ffirst %) card))) newelem (cons card (->> les last first)) modpile (cons newelem (first gts))] (concat les (cons modpile (rest gts))))) (defn a-longest [cards] (let [piles (reduce place '() cards)] (->> piles last first r...
Port the following code from VB to Clojure with equivalent syntax and logic.
option explicit class playingcard dim suit dim pips public sub print dim s,p select case suit case "S":s=chrW(&h2660) case "D":s=chrW(&h2666) case "C":s=chrW(&h2663) case "H":s=chrW(&h2665) end select select case pips case 1:p="A" case 11:p="J" case 12:p="Q" case 13:p="K" case else:...
(defn rank [card] (let [[fst _] card] (if (Character/isDigit fst) (Integer/valueOf (str fst)) ({\T 10, \J 11, \Q 12, \K 13, \A 14} fst)))) (defn suit [card] (let [[_ snd] card] (str snd))) (defn n-of-a-kind [hand n] (not (empty? (filter #(= true %) (map #(>= % n) (vals (frequencies (map rank...
Write the same algorithm in Clojure as shown in this VB implementation.
option explicit class playingcard dim suit dim pips public sub print dim s,p select case suit case "S":s=chrW(&h2660) case "D":s=chrW(&h2666) case "C":s=chrW(&h2663) case "H":s=chrW(&h2665) end select select case pips case 1:p="A" case 11:p="J" case 12:p="Q" case 13:p="K" case else:...
(defn rank [card] (let [[fst _] card] (if (Character/isDigit fst) (Integer/valueOf (str fst)) ({\T 10, \J 11, \Q 12, \K 13, \A 14} fst)))) (defn suit [card] (let [[_ snd] card] (str snd))) (defn n-of-a-kind [hand n] (not (empty? (filter #(= true %) (map #(>= % n) (vals (frequencies (map rank...
Translate the given VB code snippet into Clojure without altering its behavior.
Option Explicit Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) Private Const HT As String = "H T" Public Sub PenneysGame() Dim S$, YourSeq$, ComputeSeq$, i&, Seq$, WhoWin$, flag As Boolean Do S = WhoWillBeFirst(Choice("Who will be first")) If S = "ABORT" Then Exit Do ...
(ns penney.core (:gen-class)) (def heads \H) (def tails \T) (defn flip-coin [] (let [flip (rand-int 2)] (if (= flip 0) heads tails))) (defn turn [coin] (if (= coin heads) tails heads)) (defn first-index [combo coll] (some #(if (= (second %) combo) (first %)) coll)) (defn find-winner [h c] (if (< h c)...
Produce a functionally identical Clojure code for the snippet given in VB.
Option Explicit Public Sub coconuts() Dim sailors As Integer Dim share As Long Dim finalshare As Integer Dim minimum As Long, pile As Long Dim i As Long, j As Integer Debug.Print "Sailors", "Pile", "Final share" For sailors = 2 To 6 i = 1 Do While True pile = i ...
(defn solves-for? [sailors initial-coconut-count] (with-local-vars [coconuts initial-coconut-count, hidings 0] (while (and (> @coconuts sailors) (= (mod @coconuts sailors) 1) (var-set coconuts (/ (* (dec @coconuts) (dec sailors)) sailors)) (var-set hidings (inc @hidings))) (and (zero? (mod @coconu...
Preserve the algorithm and functionality while converting the code from VB to Clojure.
Option Explicit Public Sub coconuts() Dim sailors As Integer Dim share As Long Dim finalshare As Integer Dim minimum As Long, pile As Long Dim i As Long, j As Integer Debug.Print "Sailors", "Pile", "Final share" For sailors = 2 To 6 i = 1 Do While True pile = i ...
(defn solves-for? [sailors initial-coconut-count] (with-local-vars [coconuts initial-coconut-count, hidings 0] (while (and (> @coconuts sailors) (= (mod @coconuts sailors) 1) (var-set coconuts (/ (* (dec @coconuts) (dec sailors)) sailors)) (var-set hidings (inc @hidings))) (and (zero? (mod @coconu...
Generate an equivalent Clojure version of this VB code.
Option Explicit Declare Function Beep Lib "kernel32" (ByVal Freq As Long, ByVal Dur As Long) As Long Sub Musical_Scale() Dim Fqs, i As Integer Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528) For i = LBound(Fqs) To UBound(Fqs) Beep Fqs(i), 500 Next End Sub
(use 'overtone.live) (definst saw-wave [freq 440 attack 0.01 sustain 0.4 release 0.1 vol 0.4] (* (env-gen (env-lin attack sustain release) 1 1 0 1 FREE) (saw freq) vol)) (defn play [note ms] (saw-wave (midi->hz note)) (Thread/sleep ms)) (doseq [note (scale :c4 :major)] (play note 500))
Write the same algorithm in Clojure as shown in this VB implementation.
Option Explicit Declare Function Beep Lib "kernel32" (ByVal Freq As Long, ByVal Dur As Long) As Long Sub Musical_Scale() Dim Fqs, i As Integer Fqs = Array(264, 297, 330, 352, 396, 440, 495, 528) For i = LBound(Fqs) To UBound(Fqs) Beep Fqs(i), 500 Next End Sub
(use 'overtone.live) (definst saw-wave [freq 440 attack 0.01 sustain 0.4 release 0.1 vol 0.4] (* (env-gen (env-lin attack sustain release) 1 1 0 1 FREE) (saw freq) vol)) (defn play [note ms] (saw-wave (midi->hz note)) (Thread/sleep ms)) (doseq [note (scale :c4 :major)] (play note 500))
Produce a functionally identical Clojure code for the snippet given in VB.
Sub Main() Dim HttpReq As WinHttp.WinHttpRequest Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 As Long = &H80& Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 As Long = &H200& Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 As Long = &H800& Const HTTPREQUEST_PROXYSETTING_PROXY As Long = 2 #Const USE_PROXY = 1 Set Http...
(clj-http.client/get "https://somedomain.com" {:basic-auth ["user" "pass"]})
Please provide an equivalent version of this VB code in Clojure.
Set objFSO = CreateObject("Scripting.FileSystemObject") Set srcFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\unixdict.txt",1,False,0) cei = 0 : cie = 0 : ei = 0 : ie = 0 Do Until srcFile.AtEndOfStream word = srcFile.ReadLine If InStr(word,"cei") Then cei = cei + 1 ElseIf In...
(ns i-before-e.core (:require [clojure.string :as s]) (:gen-class)) (def patterns {:cie #"cie" :ie #"(?<!c)ie" :cei #"cei" :ei #"(?<!c)ei"}) (defn update-counts "Given a map of counts of matching patterns and a word, increment any count if the word matches it's pattern." [counts [word freq]] (apply hash-map...
Rewrite this program in Clojure while keeping its functionality equivalent to the VB version.
Set objFSO = CreateObject("Scripting.FileSystemObject") Set srcFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\unixdict.txt",1,False,0) cei = 0 : cie = 0 : ei = 0 : ie = 0 Do Until srcFile.AtEndOfStream word = srcFile.ReadLine If InStr(word,"cei") Then cei = cei + 1 ElseIf In...
(ns i-before-e.core (:require [clojure.string :as s]) (:gen-class)) (def patterns {:cie #"cie" :ie #"(?<!c)ie" :cei #"cei" :ei #"(?<!c)ei"}) (defn update-counts "Given a map of counts of matching patterns and a word, increment any count if the word matches it's pattern." [counts [word freq]] (apply hash-map...
Rewrite this program in Clojure while keeping its functionality equivalent to the VB version.
Sub write_event(event_type,msg) Set objShell = CreateObject("WScript.Shell") Select Case event_type Case "SUCCESS" n = 0 Case "ERROR" n = 1 Case "WARNING" n = 2 Case "INFORMATION" n = 4 Case "AUDIT_SUCCESS" n = 8 Case "AUDIT_FAILURE" n = 16 End Select objShell.LogEvent n, msg Set objS...
(use 'clojure.java.shell) (sh "eventcreate" "/T" "INFORMATION" "/ID" "123" "/D" "Rosetta Code example")
Change the following VB code into Clojure without altering its purpose.
Private Function ordinal(s As String) As String Dim irregs As New Collection irregs.Add "first", "one" irregs.Add "second", "two" irregs.Add "third", "three" irregs.Add "fifth", "five" irregs.Add "eighth", "eight" irregs.Add "ninth", "nine" irregs.Add "twelfth", "twelve" Dim i As Int...
(def test-cases [1 2 3 4 5 11 65 100 101 272 23456 8007006005004003]) (pprint (sort (zipmap test-cases (map #(clojure.pprint/cl-format nil "~:R" %) test-cases))))
Rewrite the snippet below in Clojure so it works the same as the original VB code.
Public Type tuple i As Variant j As Variant sum As Variant End Type Public Type tuple3 i1 As Variant j1 As Variant i2 As Variant j2 As Variant i3 As Variant j3 As Variant sum As Variant End Type Sub taxicab_numbers() Dim i As Variant, j As Variant Dim k As Long Const ...
(ns test-project-intellij.core (:gen-class)) (defn cube [x] "Cube a number through triple multiplication" (* x x x)) (defn sum3 [[i j]] " [i j] -> i^3 + j^3" (+ (cube i) (cube j))) (defn next-pair [[i j]] " Generate next [i j] pair of sequence (producing lower triangle pairs) " (if (< j i) [i (in...
Port the following code from VB to Clojure with equivalent syntax and logic.
Public Sub Main() For i As Integer = 1 To 10000 If is_steady_square(i) Then Print Format$(i, "####"); "^2 = "; Format$(i ^ 2, "########") Next End Function numdig(n As Integer) As Integer Dim d As Integer = 0 While n d += 1 n \= 10 Wend Return d End Function Function is_stea...
(= steadySquares (fn (maxNumber) (let powerOfTen 10) (let lastDigit (list 1 5 6)) (let lastResult (cons 0 nil)) (let result lastResult) (let n -10) (while (do (= n (+ n 10)) (<= n maxNumber) ...
Generate a Clojure translation of this VB snippet without changing its computational steps.
Dim t_age(4,1) t_age(0,0) = 27 : t_age(0,1) = "Jonah" t_age(1,0) = 18 : t_age(1,1) = "Alan" t_age(2,0) = 28 : t_age(2,1) = "Glory" t_age(3,0) = 18 : t_age(3,1) = "Popeye" t_age(4,0) = 28 : t_age(4,1) = "Alan" Dim t_nemesis(4,1) t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales" t_nemesis(1,0) = "Jonah" : t_nemesis(1...
(defn hash-join [table1 col1 table2 col2] (let [hashed (group-by col1 table1)] (flatten (for [r table2] (for [s (hashed (col2 r))] (merge s r)))))) (def s '({:age 27 :name "Jonah"} {:age 18 :name "Alan"} {:age 28 :name "Glory"} {:age 18 :name "Popeye"} ...
Write a version of this VB function in Clojure with identical behavior.
Imports System.Numerics Module Module1 Class Solution ReadOnly root1 As BigInteger ReadOnly root2 As BigInteger ReadOnly exists As Boolean Sub New(r1 As BigInteger, r2 As BigInteger, e As Boolean) root1 = r1 root2 = r2 exists = e End Sub...
(defn find-first " Finds first element of collection that satisifies predicate function pred " [pred coll] (first (filter pred coll))) (defn modpow " b^e mod m (using Java which solves some cases the pure clojure method has to be modified to tackle--i.e. with large b & e and calculation simplications when g...
Write the same algorithm in Clojure as shown in this VB implementation.
Imports System.Numerics Module Module1 Class Solution ReadOnly root1 As BigInteger ReadOnly root2 As BigInteger ReadOnly exists As Boolean Sub New(r1 As BigInteger, r2 As BigInteger, e As Boolean) root1 = r1 root2 = r2 exists = e End Sub...
(defn find-first " Finds first element of collection that satisifies predicate function pred " [pred coll] (first (filter pred coll))) (defn modpow " b^e mod m (using Java which solves some cases the pure clojure method has to be modified to tackle--i.e. with large b & e and calculation simplications when g...
Translate this program into Clojure but keep the logic exactly as in VB.
Sub InsertaElto(lista() As String, posic As Integer = 1) For i As Integer = Lbound(lista) To Ubound(lista) If i = posic Then Swap lista(i), lista(Ubound(lista)) Next i End Sub Sub mostrarLista(lista() As String, titulo As String) Print !"\n"; titulo; For i As Integer = Lbound(lista) To Ubo...
(ns double-list) (defprotocol PDoubleList (get-head [this]) (add-head [this x]) (get-tail [this]) (add-tail [this x]) (remove-node [this node]) (add-before [this node x]) (add-after [this node x]) (get-nth [this n])) (defrecord Node [prev next data]) (defn make-node "Create an internal or finalized...
Write a version of this VB function in Clojure with identical behavior.
Imports System.Text Module Module1 Structure Operator_ Public ReadOnly Symbol As Char Public ReadOnly Precedence As Integer Public ReadOnly Arity As Integer Public ReadOnly Fun As Func(Of Boolean, Boolean, Boolean) Public Sub New(symbol As Char, precedence As Integer, f As ...
(ns clojure-sandbox.truthtables (:require [clojure.string :as s] [clojure.pprint :as pprint])) (defn !op [expr] (not expr)) (defn |op [e1 e2] (not (and (not e1) (not e2)))) (defn &op [e1 e2] (and e1 e2)) (defn ->op [e1 e2] (if e1 e2 true)) (def operators {"!" !op ...
Write the same code in Clojure as shown below in VB.
Imports System.Text Module Module1 Structure Operator_ Public ReadOnly Symbol As Char Public ReadOnly Precedence As Integer Public ReadOnly Arity As Integer Public ReadOnly Fun As Func(Of Boolean, Boolean, Boolean) Public Sub New(symbol As Char, precedence As Integer, f As ...
(ns clojure-sandbox.truthtables (:require [clojure.string :as s] [clojure.pprint :as pprint])) (defn !op [expr] (not expr)) (defn |op [e1 e2] (not (and (not e1) (not e2)))) (defn &op [e1 e2] (and e1 e2)) (defn ->op [e1 e2] (if e1 e2 true)) (def operators {"!" !op ...
Convert this VB block to Clojure, preserving its control flow and logic.
Imports System.Numerics Module Module1 Sub Main() Dim rd = {"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"} Dim one As BigInteger = 1 Dim nine As BigInteger = 9 For ii = 2 To 9 Console.WriteLine("First 10 super-{0} numbers:", ii) ...
(defn super [d] (let [run (apply str (repeat d (str d)))] (filter #(clojure.string/includes? (str (* d (Math/pow % d ))) run) (range)))) (doseq [d (range 2 9)] (println (str d ": ") (take 10 (super d))))
Please provide an equivalent version of this VB code in Clojure.
Imports System.Numerics Module Module1 Sub Main() Dim rd = {"22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"} Dim one As BigInteger = 1 Dim nine As BigInteger = 9 For ii = 2 To 9 Console.WriteLine("First 10 super-{0} numbers:", ii) ...
(defn super [d] (let [run (apply str (repeat d (str d)))] (filter #(clojure.string/includes? (str (* d (Math/pow % d ))) run) (range)))) (doseq [d (range 2 9)] (println (str d ": ") (take 10 (super d))))
Write a version of this VB function in Clojure with identical behavior.
Set objFSO = CreateObject("Scripting.FileSystemObject") Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ "\unixdict.txt",1) Set objKeyMap = CreateObject("Scripting.Dictionary") With objKeyMap .Add "ABC", "2" : .Add "DEF", "3" : .Add "GHI", "4" : .Add "JKL", "5" .Add "MNO",...
(def table {\a 2 \b 2 \c 2 \A 2 \B 2 \C 2 \d 3 \e 3 \f 3 \D 3 \E 3 \F 3 \g 4 \h 4 \i 4 \G 4 \H 4 \I 4 \j 5 \k 5 \l 5 \J 5 \K 5 \L 5 \m 6 \n 6 \o 6 \M 6 \N 6 \O 6 \p 7 \q 7 \r 7 \s 7 \P 7 \Q 7 \R 7 \S 7 \t 8 \u 8 \v 8 \T 8 \U 8 \V 8 \w 9 \x 9 \y 9 \z 9 \W 9 \X...
Rewrite the snippet below in Clojure so it works the same as the original VB code.
Type mina Dim mina As Byte Dim flag As Byte Dim ok As Byte Dim numero As Byte End Type Dim Shared As Integer size = 16, NX = 20, NY = 20 Dim Shared As Double mina = 0.10 Dim Shared tablero(NX+1,NY+1) As mina Dim Shared As Integer GameOver, ddx, ddy, kolor, nbDESCANSO Dim Shared As Double temp...
(defn take-random [n coll] (->> (repeatedly #(rand-nth coll)) distinct (take n ,))) (defn postwalk-fs "Depth first post-order traversal of form, apply successive fs at each level. (f1 (map f2 [..]))" [[f & fs] form] (f (if (and (seq fs) (coll? form)) (into (empty form) (map (partial pos...
Can you help me rewrite this code in Scala instead of C++, keeping it the same logically?
#include <iostream> int main() { std::cout << R"EOF( A raw string begins with R, then a double-quote ("), then an optional identifier (here I've used "EOF"), then an opening parenthesis ('('). If you use an identifier, it cannot be longer than 16 characters, and it cannot contain a space, either op...
fun main(args: Array<String>) { val ev = "embed variables" val here = """ This is a raw string literal which does not treat escaped characters (\t, \b, \n, \r, \', \", \\, \$ and \u) specially and can contain new lines, indentatio...
Translate the given C++ code snippet into Scala without altering its behavior.
class fifteenSolver{ const int Nr[16]{3,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3}, Nc[16]{3,0,1,2,3,0,1,2,3,0,1,2,3,0,1,2}; int n{},_n{}, N0[100]{},N3[100]{},N4[100]{}; unsigned long N2[100]{}; const bool fY(){ if (N4[n]<_n) return fN(); if (N2[n]==0x123456789abcdef0) {std::cout<<"Solution found in "<<n<<" moves ...
import scala.collection.mutable case class Board(table: Array[Int], r: Int, c: Int, parent: List[String] = List()) { def cloneSwap(r: Int, c: Int, rr: Int, cc: Int) = { val cTable = table.clone cTable(r << 2 | c) = table(rr << 2 | cc) cTable(rr << 2 | cc) = table(r << 2 | c) cTable } def...
Produce a language-to-language conversion: from C++ to Scala, same semantics.
int i; void* address_of_i = &i;
import kotlinx.cinterop.* fun main(args: Array<String>) { val intVar = nativeHeap.alloc<IntVar>() intVar.value = 42 with(intVar) { println("Value is $value, address is $rawPtr") } nativeHeap.free(intVar) }
Can you help me rewrite this code in Scala instead of C++, keeping it the same logically?
#include <time.h> #include <iostream> #include <string> #include <iomanip> #include <cstdlib> typedef unsigned int uint; using namespace std; enum movDir { UP, DOWN, LEFT, RIGHT }; class tile { public: tile() : val( 0 ), blocked( false ) {} uint val; bool blocked; }; class g2048 { public: g2048() : d...
import java.io.BufferedReader import java.io.InputStreamReader const val positiveGameOverMessage = "So sorry, but you won the game." const val negativeGameOverMessage = "So sorry, but you lost the game." fun main(args: Array<String>) { val grid = arrayOf( arrayOf(0, 0, 0, 0), arrayOf(0, 0,...
Keep all operations the same but rewrite the snippet in Scala.
#include <iostream> #include <algorithm> #include <ctime> #include <string> #include <vector> typedef std::vector<char> vecChar; class master { public: master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) { std::string color = "ABCDEFGHIJKLMNOPQRST"; if( code_len < 4 ) code_l...
import java.util.Random val rand = Random() class Mastermind { private val codeLen: Int private val colorsCnt: Int private var guessCnt = 0 private val repeatClr: Boolean private val colors: String private var combo = "" private val guesses = mutableListOf<CharArray>() private val ...
Can you help me rewrite this code in Scala instead of C++, keeping it the same logically?
while (true) std::cout << "SPAM\n";
fun main(args: Array<String>) { while (true) println("SPAM") }
Write a version of this C++ function in Scala with identical behavior.
T* foo = new(arena) T;
import kotlinx.cinterop.* fun main(args: Array<String>) { memScoped { val intVar1 = alloc<IntVar>() intVar1.value = 1 val intVar2 = alloc<IntVar>() intVar2.value = 2 println("${intVar1.value} + ${intVar2.value} = ${intVar1.value + intVar2.value}") } }
Port the provided C++ code into Scala while preserving the original functionality.
T* foo = new(arena) T;
import kotlinx.cinterop.* fun main(args: Array<String>) { memScoped { val intVar1 = alloc<IntVar>() intVar1.value = 1 val intVar2 = alloc<IntVar>() intVar2.value = 2 println("${intVar1.value} + ${intVar2.value} = ${intVar1.value + intVar2.value}") } }
Rewrite this program in Scala while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <cstdint> #include <vector> #include "prime_sieve.hpp" using integer = uint32_t; using vector = std::vector<integer>; void print_vector(const vector& vec) { if (!vec.empty()) { auto i = vec.begin(); std::cout << '(' << *i; for (++i; i != vec.end(); ++i) ...
private fun sieve(limit: Int): Array<Int> { val primes = mutableListOf<Int>() primes.add(2) val c = BooleanArray(limit + 1) var p = 3 while (true) { val p2 = p * p if (p2 > limit) { break } var i = p2 while (i <= limit) { c[i] = t...
Transform the following C++ implementation into Scala, maintaining the same output and logic.
#include <iostream> #include <locale> #include <primesieve.hpp> int main() { std::cout.imbue(std::locale("")); std::cout << "The 10,001st prime is " << primesieve::nth_prime(10001) << ".\n"; }
object Prime10001 extends App { val oddPrimes: LazyList[Int] = 3 #:: LazyList.from(5, 2) .filter(p => oddPrimes.takeWhile(_ <= math.sqrt(p)).forall(p % _ > 0)) val primes = 2 #:: oddPrimes val index = 10_001 println(s"prime($index): " + primes.drop(index - 1).take(1).head) }
Transform the following C++ implementation into Scala, maintaining the same output and logic.
#include <iostream> #include <locale> #include <primesieve.hpp> int main() { std::cout.imbue(std::locale("")); std::cout << "The 10,001st prime is " << primesieve::nth_prime(10001) << ".\n"; }
object Prime10001 extends App { val oddPrimes: LazyList[Int] = 3 #:: LazyList.from(5, 2) .filter(p => oddPrimes.takeWhile(_ <= math.sqrt(p)).forall(p % _ > 0)) val primes = 2 #:: oddPrimes val index = 10_001 println(s"prime($index): " + primes.drop(index - 1).take(1).head) }
Produce a functionally identical Scala code for the snippet given in C++.
#include <iostream> bool is_prime(int n) { if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } int i = 5; while (i * i <= n) { if (n % i == 0) { return false; } i += 2; ...
object PrimeSum extends App { val oddPrimes: LazyList[Int] = 3 #:: LazyList.from(5, 2) .filter(p => oddPrimes.takeWhile(_ <= math.sqrt(p)).forall(p % _ > 0)) val primes = 2 #:: oddPrimes def isPrime(n: Int): Boolean = { if (n < 5) (n | 1) == 3 else primes.takeWhile(_ <= math.sqrt(n)).forall(n ...
Write the same code in Scala as shown below in C++.
#include <iostream> bool is_prime(int n) { if (n < 2) { return false; } if (n % 2 == 0) { return n == 2; } if (n % 3 == 0) { return n == 3; } int i = 5; while (i * i <= n) { if (n % i == 0) { return false; } i += 2; ...
object PrimeSum extends App { val oddPrimes: LazyList[Int] = 3 #:: LazyList.from(5, 2) .filter(p => oddPrimes.takeWhile(_ <= math.sqrt(p)).forall(p % _ > 0)) val primes = 2 #:: oddPrimes def isPrime(n: Int): Boolean = { if (n < 5) (n | 1) == 3 else primes.takeWhile(_ <= math.sqrt(n)).forall(n ...
Preserve the algorithm and functionality while converting the code from C++ to Scala.
#include <iostream> #include <sstream> #include <set> bool checkDec(int num) { std::set<int> set; std::stringstream ss; ss << num; auto str = ss.str(); for (int i = 0; i < str.size(); ++i) { char c = str[i]; int d = c - '0'; if (d == 0) return false; if (num % d !=...
fun Int.divByAll(digits: List<Char>) = digits.all { this % (it - '0') == 0 } fun main(args: Array<String>) { val magic = 9 * 8 * 7 val high = 9876432 / magic * magic for (i in high downTo magic step magic) { if (i % 10 == 0) continue val s = i.toString() if ('0' in s |...
Convert the following code from C++ to Scala, ensuring the logic remains intact.
#include <iostream> #include <sstream> #include <set> bool checkDec(int num) { std::set<int> set; std::stringstream ss; ss << num; auto str = ss.str(); for (int i = 0; i < str.size(); ++i) { char c = str[i]; int d = c - '0'; if (d == 0) return false; if (num % d !=...
fun Int.divByAll(digits: List<Char>) = digits.all { this % (it - '0') == 0 } fun main(args: Array<String>) { val magic = 9 * 8 * 7 val high = 9876432 / magic * magic for (i in high downTo magic step magic) { if (i % 10 == 0) continue val s = i.toString() if ('0' in s |...
Convert the following code from C++ to Scala, ensuring the logic remains intact.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> int jacobi(int n, int k) { assert(k > 0 && k % 2 == 1); n %= k; int t = 1; while (n != 0) { while (n % 2 == 0) { n /= 2; int r = k % 8; if (r == 3 || r == 5) t = -t...
fun jacobi(A: Int, N: Int): Int { assert(N > 0 && N and 1 == 1) var a = A % N var n = N var result = 1 while (a != 0) { var aMod4 = a and 3 while (aMod4 == 0) { a = a shr 2 aMod4 = a and 3 } if (aMod4 == 2) { a = a shr 1 ...
Port the provided C++ code into Scala while preserving the original functionality.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> int jacobi(int n, int k) { assert(k > 0 && k % 2 == 1); n %= k; int t = 1; while (n != 0) { while (n % 2 == 0) { n /= 2; int r = k % 8; if (r == 3 || r == 5) t = -t...
fun jacobi(A: Int, N: Int): Int { assert(N > 0 && N and 1 == 1) var a = A % N var n = N var result = 1 while (a != 0) { var aMod4 = a and 3 while (aMod4 == 0) { a = a shr 2 aMod4 = a and 3 } if (aMod4 == 2) { a = a shr 1 ...
Write the same algorithm in Scala as shown in this C++ implementation.
#include <iostream> #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) { os << ", " << *i...
typealias Matrix = Array<DoubleArray> 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: In...
Translate this program into Scala but keep the logic exactly as in C++.
#include <iostream> #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) { os << ", " << *i...
typealias Matrix = Array<DoubleArray> 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: In...
Convert this C++ block to Scala, preserving its control flow and logic.
#include <iostream> int digitSum(int n) { int s = 0; do {s += n % 10;} while (n /= 10); return s; } int main() { for (int i=0; i<1000; i++) { auto s_i = std::to_string(i); auto s_ds = std::to_string(digitSum(i)); if (s_i.find(s_ds) != std::string::npos) { std::cout ...
fun digitSum(n: Int): Int { var nn = n var sum = 0 while (nn > 0) { sum += (nn % 10) nn /= 10 } return sum } fun main() { var c = 0 for (i in 0 until 1000) { val ds = digitSum(i) if (i.toString().contains(ds.toString())) { print("%3d ".format(i)) ...
Convert this C++ snippet to Scala and keep its semantics consistent.
#include <iostream> int digitSum(int n) { int s = 0; do {s += n % 10;} while (n /= 10); return s; } int main() { for (int i=0; i<1000; i++) { auto s_i = std::to_string(i); auto s_ds = std::to_string(digitSum(i)); if (s_i.find(s_ds) != std::string::npos) { std::cout ...
fun digitSum(n: Int): Int { var nn = n var sum = 0 while (nn > 0) { sum += (nn % 10) nn /= 10 } return sum } fun main() { var c = 0 for (i in 0 until 1000) { val ds = digitSum(i) if (i.toString().contains(ds.toString())) { print("%3d ".format(i)) ...
Change the following C++ code into Scala without altering its purpose.
#include <ctime> #include <string> #include <iostream> #include <algorithm> class cycle{ public: template <class T> void cy( T* a, int len ) { int i, j; show( "original: ", a, len ); std::srand( unsigned( time( 0 ) ) ); for( int i = len - 1; i > 0; i-- ) { do { ...
fun <T> sattolo(items: Array<T>) { for (i in items.size - 1 downTo 1) { val j = (Math.random() * i).toInt() val t = items[i] items[i] = items[j] items[j] = t } } fun main(args: Array<String>) { val items = arrayOf(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22) println...
Rewrite this program in Scala while keeping its functionality equivalent to the C++ version.
#include <ctime> #include <string> #include <iostream> #include <algorithm> class cycle{ public: template <class T> void cy( T* a, int len ) { int i, j; show( "original: ", a, len ); std::srand( unsigned( time( 0 ) ) ); for( int i = len - 1; i > 0; i-- ) { do { ...
fun <T> sattolo(items: Array<T>) { for (i in items.size - 1 downTo 1) { val j = (Math.random() * i).toInt() val t = items[i] items[i] = items[j] items[j] = t } } fun main(args: Array<String>) { val items = arrayOf(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22) println...
Rewrite the snippet below in Scala so it works the same as the original C++ code.
#include <iostream> #include <string> #include <cstring> #include <fstream> #include <sys/stat.h> #include <ftplib.h> #include <ftp++.hpp> int stat(const char *pathname, struct stat *buf); char *strerror(int errnum); char *basename(char *path); namespace stl { using std::cout; ...
import kotlinx.cinterop.* import ftplib.* fun main(args: Array<String>) { val nbuf = nativeHeap.allocPointerTo<netbuf>() FtpInit() FtpConnect("ftp.easynet.fr", nbuf.ptr) val vnbuf = nbuf.value FtpLogin("anonymous", "ftptest@example.com", vnbuf) FtpOptions(FTPLIB_CONNMODE, FTPLIB_PASSIVE.toLon...
Port the following code from C++ to Scala with equivalent syntax and logic.
#include <time.h> #include <iostream> #include <vector> using namespace std; class cSort { public: void doIt( vector<unsigned> s ) { sq = s; display(); c_sort(); cout << "writes: " << wr << endl; display(); } private: void display() { copy( sq.begin(), sq.end(), ostream_iterator<unsigned>( std...
fun <T : Comparable<T>> cycleSort(array: Array<T>): Int { var writes = 0 for (cycleStart in 0 until array.size - 1) { var item = array[cycleStart] var pos = cycleStart for (i in cycleStart + 1 until array.size) if (array[i] < item) pos++ if (pos == cy...
Port the provided C++ code into Scala while preserving the original functionality.
#include <time.h> #include <iostream> #include <vector> using namespace std; class cSort { public: void doIt( vector<unsigned> s ) { sq = s; display(); c_sort(); cout << "writes: " << wr << endl; display(); } private: void display() { copy( sq.begin(), sq.end(), ostream_iterator<unsigned>( std...
fun <T : Comparable<T>> cycleSort(array: Array<T>): Int { var writes = 0 for (cycleStart in 0 until array.size - 1) { var item = array[cycleStart] var pos = cycleStart for (i in cycleStart + 1 until array.size) if (array[i] < item) pos++ if (pos == cy...
Maintain the same structure and functionality when rewriting this code in Scala.
#include <cstdint> #include <iostream> #include <string> #include <primesieve.hpp> void print_twin_prime_count(long long limit) { std::cout << "Number of twin prime pairs less than " << limit << " is " << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\n'; } int main(int argc, char** argv) { ...
import java.math.BigInteger import java.util.* fun main() { val input = Scanner(System.`in`) println("Search Size: ") val max = input.nextBigInteger() var counter = 0 var x = BigInteger("3") while (x <= max) { val sqrtNum = x.sqrt().add(BigInteger.ONE) if (x.add(BigInteger.TWO) ...
Convert this C++ block to Scala, preserving its control flow and logic.
#include <iostream> bool sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) { if (n % b != f) { return false; } } return true; } bool isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0)return true; for (int b = 2; b < n - 1; b++) { ...
fun sameDigits(n: Int, b: Int): Boolean { var n2 = n val f = n % b while (true) { n2 /= b if (n2 > 0) { if (n2 % b != f) { return false } } else { break } } return true } fun isBrazilian(n: Int): Boolean { if (n...
Rewrite this program in Scala while keeping its functionality equivalent to the C++ version.
#include <iostream> bool sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) { if (n % b != f) { return false; } } return true; } bool isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0)return true; for (int b = 2; b < n - 1; b++) { ...
fun sameDigits(n: Int, b: Int): Boolean { var n2 = n val f = n % b while (true) { n2 /= b if (n2 > 0) { if (n2 % b != f) { return false } } else { break } } return true } fun isBrazilian(n: Int): Boolean { if (n...
Generate a Scala translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <fstream> #if defined(_WIN32) || defined(WIN32) constexpr auto FILENAME = "tape.file"; #else constexpr auto FILENAME = "/dev/tape"; #endif int main() { std::filebuf fb; fb.open(FILENAME,std::ios::out); std::ostream os(&fb); os << "Hello World\n"; fb.close(); return...
import java.io.FileWriter fun main(args: Array<String>) { val lp0 = FileWriter("/dev/tape") lp0.write("Hello, world!") lp0.close() }
Port the provided C++ code into Scala while preserving the original functionality.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { ...
fun main(args: Array<String>) { val a = mutableListOf(0) val used = mutableSetOf(0) val used1000 = mutableSetOf(0) var foundDup = false var n = 1 while (n <= 15 || !foundDup || used1000.size < 1001) { var next = a[n - 1] - n if (next < 1 || used.contains(next)) next += 2 * n ...
Produce a functionally identical Scala code for the snippet given in C++.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { ...
fun main(args: Array<String>) { val a = mutableListOf(0) val used = mutableSetOf(0) val used1000 = mutableSetOf(0) var foundDup = false var n = 1 while (n <= 15 || !foundDup || used1000.size < 1001) { var next = a[n - 1] - n if (next < 1 || used.contains(next)) next += 2 * n ...
Port the provided C++ code into Scala while preserving the original functionality.
#include <iostream> #include <functional> template <typename F> struct RecursiveFunc { std::function<F(RecursiveFunc)> o; }; template <typename A, typename B> std::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) { RecursiveFunc<std::function<B(A)>> r = { std::function<std::function<B(...
typealias Func<T, R> = (T) -> R class RecursiveFunc<T, R>(val p: (RecursiveFunc<T, R>) -> Func<T, R>) fun <T, R> y(f: (Func<T, R>) -> Func<T, R>): Func<T, R> { val rec = RecursiveFunc<T, R> { r -> f { r.p(r)(it) } } return rec.p(rec) } fun fac(f: Func<Int, Int>) = { x: Int -> if (x <= 1) 1 else x * f(x - ...
Translate the given C++ code snippet into Scala without altering its behavior.
#include <iostream> class factorion_t { public: factorion_t() { f[0] = 1u; for (uint n = 1u; n < 12u; n++) f[n] = f[n - 1] * n; } bool operator()(uint i, uint b) const { uint sum = 0; for (uint j = i; j > 0u; j /= b) sum += f[j % b]; return s...
object Factorion extends App { private def is_factorion(i: Int, b: Int): Boolean = { var sum = 0L var j = i while (j > 0) { sum += f(j % b) j /= b } sum == i } private val f = Array.ofDim[Long](12) f(0) = 1L (1 until 12).foreach(n => ...
Write the same code in Scala as shown below in C++.
#include <iostream> class factorion_t { public: factorion_t() { f[0] = 1u; for (uint n = 1u; n < 12u; n++) f[n] = f[n - 1] * n; } bool operator()(uint i, uint b) const { uint sum = 0; for (uint j = i; j > 0u; j /= b) sum += f[j % b]; return s...
object Factorion extends App { private def is_factorion(i: Int, b: Int): Boolean = { var sum = 0L var j = i while (j > 0) { sum += f(j % b) j /= b } sum == i } private val f = Array.ofDim[Long](12) f(0) = 1L (1 until 12).foreach(n => ...
Keep all operations the same but rewrite the snippet in Scala.
#include <iomanip> #include <iostream> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) total += power; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0;...
fun divisorSum(n: Long): Long { var nn = n var total = 1L var power = 2L while ((nn and 1) == 0L) { total += power power = power shl 1 nn = nn shr 1 } var p = 3L while (p * p <= nn) { var sum = 1L power = p while (nn % p == 0L) { ...
Maintain the same structure and functionality when rewriting this code in Scala.
#include <iomanip> #include <iostream> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) total += power; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0;...
fun divisorSum(n: Long): Long { var nn = n var total = 1L var power = 2L while ((nn and 1) == 0L) { total += power power = power shl 1 nn = nn shr 1 } var p = 3L while (p * p <= nn) { var sum = 1L power = p while (nn % p == 0L) { ...
Preserve the algorithm and functionality while converting the code from C++ to Scala.
#include <iostream> #include <vector> #include <boost/integer/common_factor.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/multiprecision/miller_rabin.hpp> typedef boost::multiprecision::cpp_int integer; integer fermat(unsigned int n) { unsigned int p = 1; for (unsigned int i = 0; i < n; ++i...
import java.math.BigInteger import kotlin.math.pow fun main() { println("First 10 Fermat numbers:") for (i in 0..9) { println("F[$i] = ${fermat(i)}") } println() println("First 12 Fermat numbers factored:") for (i in 0..12) { println("F[$i] = ${getString(getFactors(i, fermat(i))...
Transform the following C++ implementation into Scala, maintaining the same output and logic.
#include <iostream> #include <vector> using std::cout; using std::vector; void distribute(int dist, vector<int> &List) { if (dist > List.size() ) List.resize(dist); for (int i=0; i < dist; i++) List[i]++; } vector<int> beadSort(int *myints, int n) { vector<int> list, list2, fifth ...
fun beadSort(a: IntArray) { val n = a.size if (n < 2) return var max = a.max()!! val beads = ByteArray(max * n) for (i in 0 until n) for (j in 0 until a[i]) beads[i * max + j] = 1 for (j in 0 until max) { var sum = 0 for (i in 0 until n) { ...
Generate a Scala translation of this C++ snippet without changing its computational steps.
#include <iostream> int main() { int Base = 10; const int N = 2; int c1 = 0; int c2 = 0; for (int k=1; k<pow((double)Base,N); k++){ c1++; if (k%(Base-1) == (k*k)%(Base-1)){ c2++; std::cout << k << " "; } } std::cout << "\nTrying " << c2 << " numbers instead of " << c1 << " numbers saves " << 100 ...
fun castOut(base: Int, start: Int, end: Int): List<Int> { val b = base - 1 val ran = (0 until b).filter { it % b == (it * it) % b } var x = start / b val result = mutableListOf<Int>() while (true) { for (n in ran) { val k = b * x + n if (k < start) continue ...
Transform the following C++ implementation into Scala, maintaining the same output and logic.
#include <iostream> int main() { int Base = 10; const int N = 2; int c1 = 0; int c2 = 0; for (int k=1; k<pow((double)Base,N); k++){ c1++; if (k%(Base-1) == (k*k)%(Base-1)){ c2++; std::cout << k << " "; } } std::cout << "\nTrying " << c2 << " numbers instead of " << c1 << " numbers saves " << 100 ...
fun castOut(base: Int, start: Int, end: Int): List<Int> { val b = base - 1 val ran = (0 until b).filter { it % b == (it * it) % b } var x = start / b val result = mutableListOf<Int>() while (true) { for (n in ran) { val k = b * x + n if (k < start) continue ...
Port the provided C++ code into Scala while preserving the original functionality.
void runCode(string code) { int c_len = code.length(); unsigned accumulator=0; int bottles; for(int i=0;i<c_len;i++) { switch(code[i]) { case 'Q': cout << code << endl; break; case 'H': cout << "Hello, world!" <...
fun hq9plus(code: String) { var acc = 0 val sb = StringBuilder() for (c in code) { sb.append( when (c) { 'h', 'H' -> "Hello, world!\n" 'q', 'Q' -> code + "\n" '9'-> { val sb2 = StringBuilder() for (...
Convert this C++ block to Scala, preserving its control flow and logic.
void runCode(string code) { int c_len = code.length(); unsigned accumulator=0; int bottles; for(int i=0;i<c_len;i++) { switch(code[i]) { case 'Q': cout << code << endl; break; case 'H': cout << "Hello, world!" <...
fun hq9plus(code: String) { var acc = 0 val sb = StringBuilder() for (c in code) { sb.append( when (c) { 'h', 'H' -> "Hello, world!\n" 'q', 'Q' -> code + "\n" '9'-> { val sb2 = StringBuilder() for (...
Change the programming language of this snippet from C++ to Scala without modifying what it does.
#include <iomanip> #include <iostream> #include <vector> constexpr int MU_MAX = 1'000'000; std::vector<int> MU; int mobiusFunction(int n) { if (!MU.empty()) { return MU[n]; } MU.resize(MU_MAX + 1, 1); int root = sqrt(MU_MAX); for (int i = 2; i <= root; i++) { if (MU[i] == 1)...
import kotlin.math.sqrt fun main() { println("First 199 terms of the möbius function are as follows:") print(" ") for (n in 1..199) { print("%2d ".format(mobiusFunction(n))) if ((n + 1) % 20 == 0) { println() } } } private const val MU_MAX = 1000000 private var ...