Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Keep all operations the same but rewrite the snippet in PHP.
function bitwiseOps(a,b) disp(sprintf(' disp(sprintf(' disp(sprintf(' disp(sprintf(' disp(sprintf(' end
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
Convert the following code from Nim to PHP, ensuring the logic remains intact.
proc bitwise(a, b) = echo "a and b: " , a and b echo "a or b: ", a or b echo "a xor b: ", a xor b echo "not a: ", not a echo "a << b: ", a shl b echo "a >> b: ", a shr b
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
Change the following OCaml code into PHP without altering its purpose.
let bitwise a b = Printf.printf "a and b: %d\n" (a land b); Printf.printf "a or b: %d\n" (a lor b); Printf.printf "a xor b: %d\n" (a lxor b); Printf.printf "not a: %d\n" (lnot a); Printf.printf "a lsl b: %d\n" (a lsl b); Printf.printf "a asr b: %d\n" (a asr b); Printf.printf "a lsr b: %d\n" (a lsr b); ;;
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
Produce a language-to-language conversion: from Pascal to PHP, same semantics.
program Bitwise; var x:shortint = 2; y:ShortInt = 3; begin Writeln('2 and 3 = ', x and y); Writeln('2 or 3 = ', x or y); Writeln('2 xor 3 = ', x xor y); Writeln('not 2 = ', not x); Writeln('2 shl 3 = ', x >> y); Writeln('2 shr 3 = ', x << y); writeln('2 rol 3 = ', rolbyte(x,y)); writeln('2 ror 3 = ', rorbyte(x,y)); writeln('2 sar 3 = ', sarshortint(x,y)); Readln; end.
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
Write a version of this Perl function in PHP with identical behavior.
use integer; sub bitwise :prototype($$) { ($a, $b) = @_; print 'a and b: '. ($a & $b) ."\n"; print 'a or b: '. ($a | $b) ."\n"; print 'a xor b: '. ($a ^ $b) ."\n"; print 'not a: '. (~$a) ."\n"; print 'a >> b: ', $a >> $b, "\n"; use integer; print "after use integer:\n"; print 'a << b: ', $a << $b, "\n"; print 'a >> b: ', $a >> $b, "\n"; }
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
Maintain the same structure and functionality when rewriting this code in PHP.
$X -band $Y $X -bor $Y $X -bxor $Y -bnot $X
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
Transform the following Racket implementation into PHP, maintaining the same output and logic.
#lang racket (define a 255) (define b 5) (list (bitwise-and a b) (bitwise-ior a b) (bitwise-xor a b) (bitwise-not a) (arithmetic-shift a b) (arithmetic-shift a (- b)))
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
Generate a PHP translation of this COBOL snippet without changing its computational steps.
IDENTIFICATION DIVISION. PROGRAM-ID. bitwise-ops. DATA DIVISION. LOCAL-STORAGE SECTION. 01 a PIC 1(32) USAGE BIT. 01 b PIC 1(32) USAGE BIT. 01 result PIC 1(32) USAGE BIT. 01 result-disp REDEFINES result PIC S9(9) COMP. LINKAGE SECTION. 01 a-int USAGE BINARY-LONG. 01 b-int USAGE BINARY-LONG. PROCEDURE DIVISION USING a-int, b-int. MOVE FUNCTION BOOLEAN-OF-INTEGER(a-int, 32) TO a MOVE FUNCTION BOOLEAN-OF-INTEGER(b-int, 32) TO b COMPUTE result = a B-AND b DISPLAY "a and b is " result-disp COMPUTE result = a B-OR b DISPLAY "a or b is " result-disp COMPUTE result = B-NOT a DISPLAY "Not a is " result-disp COMPUTE result = a B-XOR b DISPLAY "a exclusive-or b is " result-disp GOBACK .
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
Convert this REXX snippet to PHP and keep its semantics consistent.
/ Bit Operations work as in Rexx (of course) * Bit operations are performed up to the length of the shorter string. * The rest of the longer string is copied to the result. * ooRexx introduces the possibility to specify a padding character * to be used for expanding the shorter string. * 10.11.2012 Walter Pachl taken over from REXX and extended for ooRexx **********************************************************************/ a=21 b=347 Say ' a :'c2b(a) ' 'c2x(a) Say ' b :'c2b(b) c2x(b) Say 'bitand(a,b) :'c2b(bitand(a,b)) c2x(bitand(a,b)) Say 'bitor(a,b)  :'c2b(bitor(a,b)) c2x(bitor(a,b)) Say 'bitxor(a,b) :'c2b(bitxor(a,b)) c2x(bitxor(a,b)) p='11111111'B Say 'ooRexx only:' Say 'a~bitor(b,p):'c2b(a~bitor(b,p)) c2x(a~bitor(b,p)) Exit c2b: return x2b(c2x(arg(1)))
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
Rewrite this program in PHP while keeping its functionality equivalent to the Ruby version.
def bitwise(a, b) form = "%1$7s:%2$6d %2$016b" puts form % ["a", a] puts form % ["b", b] puts form % ["a and b", a & b] puts form % ["a or b ", a | b] puts form % ["a xor b", a ^ b] puts form % ["not a ", ~a] puts form % ["a << b ", a << b] puts form % ["a >> b ", a >> b] end bitwise(14,3)
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
Rewrite this program in PHP while keeping its functionality equivalent to the Scala version.
def bitwise(a: Int, b: Int) { println("a and b: " + (a & b)) println("a or b: " + (a | b)) println("a xor b: " + (a ^ b)) println("not a: " + (~a)) println("a << b: " + (a << b)) println("a >> b: " + (a >> b)) println("a >>> b: " + (a >>> b)) println("a rot b: " + Integer.rotateLeft(a, b)) println("a rol b: " + Integer.rotateRight(a, b)) }
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
Write the same algorithm in PHP as shown in this Swift implementation.
func bitwise(a: Int, b: Int) { println("a AND b: \(a & b)") println("a OR b: \(a | b)") println("a XOR b: \(a ^ b)") println("NOT a: \(~a)") println("a << b: \(a << b)") println("a >> b: \(a >> b)") println("a lsr b: \(Int(bitPattern: UInt(bitPattern: a) >> UInt(bitPattern: b)))") } bitwise(-15,3)
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
Keep all operations the same but rewrite the snippet in PHP.
proc bitwise {a b} { puts [format "a and b: % puts [format "a or b: % puts [format "a xor b: % puts [format "not a: % puts [format "a << b: % puts [format "a >> b: % }
function bitwise($a, $b) { function zerofill($a,$b) { if($a>=0) return $a>>$b; if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens return ((~$a)>>$b)^(0x7fffffff>>($b-1)); echo '$a AND $b: ' . $a & $b . '\n'; echo '$a OR $b: ' . $a | $b . '\n'; echo '$a XOR $b: ' . $a ^ $b . '\n'; echo 'NOT $a: ' . ~$a . '\n'; echo '$a << $b: ' . $a << $b . '\n'; // left shift echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift }
Write the same code in Rust as shown below in Java.
module BitwiseOps { @Inject Console console; void run() { for ((Int64 n1, Int64 n2) : [0=7, 1=5, 42=2, 0x123456789ABCDEF=0xFF]) { static String hex(Int64 n) { return n.toByteArray() [(n.leadingZeroCount / 8).minOf(7) ..< 8].toString(); } console.print($|For values {n1} ({hex(n1)}) and {n2} ({hex(n2)}): | {hex(n1)} AND {hex(n2)} = {hex(n1 & n2)} | {hex(n1)} OR {hex(n2)} = {hex(n1 | n2)} | {hex(n1)} XOR {hex(n2)} = {hex(n1 ^ n2)} | NOT {hex(n1)} = {hex(~n1)} | left shift {hex(n1)} by {n2} = {hex(n1 << n2)} | right shift {hex(n1)} by {n2} = {hex(n1 >> n2)} | right arithmetic shift {hex(n1)} by {n2} = {hex(n1 >>> n2)} | left rotate {hex(n1)} by {n2} = {hex(n1.rotateLeft(n2))} | right rotate {hex(n1)} by {n2} = {hex(n1.rotateRight(n2))} | leftmost bit of {hex(n1)} = {hex(n1.leftmostBit)} | rightmost bit of {hex(n1)} = {hex(n1.rightmostBit)} | leading zero count of {hex(n1)} = {n1.leadingZeroCount} | trailing zero count of {hex(n1)} = {n1.trailingZeroCount} | bit count (aka "population") of {hex(n1)} = {n1.bitCount} | reversed bits of {hex(n1)} = {hex(n1.reverseBits())} | reverse bytes of {hex(n1)} = {hex(n1.reverseBytes())} | ); } } }
fn main() { let a: u8 = 105; let b: u8 = 91; println!("a = {:0>8b}", a); println!("b = {:0>8b}", b); println!("a | b = {:0>8b}", a | b); println!("a & b = {:0>8b}", a & b); println!("a ^ b = {:0>8b}", a ^ b); println!("!a = {:0>8b}", !a); println!("a << 3 = {:0>8b}", a << 3); println!("a >> 3 = {:0>8b}", a >> 3); }
Produce a functionally identical Python code for the snippet given in Rust.
fn main() { let a: u8 = 105; let b: u8 = 91; println!("a = {:0>8b}", a); println!("b = {:0>8b}", b); println!("a | b = {:0>8b}", a | b); println!("a & b = {:0>8b}", a & b); println!("a ^ b = {:0>8b}", a ^ b); println!("!a = {:0>8b}", !a); println!("a << 3 = {:0>8b}", a << 3); println!("a >> 3 = {:0>8b}", a >> 3); }
def bitwise_built_ins(width, a, b): mask = (1 << width) - 1 print(f) def rotr(width, a, n): "Rotate a, n times to the right" if n < 0: return rotl(width, a, -n) elif n == 0: return a else: mask = (1 << width) - 1 a, n = a & mask, n % width return ((a >> n) | ((a & ((1 << n) - 1)) << (width - n))) def rotl(width, a, n): "Rotate a, n times to the left" if n < 0: return rotr(width, a, -n) elif n == 0: return a else: mask = (1 << width) - 1 a, n = a & mask, n % width return (((a << n) & mask) | (a >> (width - n))) def asr(width, a, n): "Arithmetic shift a, n times to the right. (sign preserving)." mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1) if n < 0: return (a << -n) & mask elif n == 0: return a elif n >= width: return mask if a & top_bit_mask else 0 else: a = a & mask if a & top_bit_mask: signs = (1 << n) - 1 return a >> n | (signs << width - n) else: return a >> n def helper_funcs(width, a): mask, top_bit_mask = ((1 << width) - 1), 1 << (width - 1) aa = a | top_bit_mask print(f) if __name__ == '__main__': bitwise_built_ins(8, 27, 125) helper_funcs(8, 27)
Rewrite this program in VB while keeping its functionality equivalent to the Rust version.
fn main() { let a: u8 = 105; let b: u8 = 91; println!("a = {:0>8b}", a); println!("b = {:0>8b}", b); println!("a | b = {:0>8b}", a | b); println!("a & b = {:0>8b}", a & b); println!("a ^ b = {:0>8b}", a ^ b); println!("!a = {:0>8b}", !a); println!("a << 3 = {:0>8b}", a << 3); println!("a >> 3 = {:0>8b}", a >> 3); }
Debug.Print Hex(&HF0F0 And &HFF00) Debug.Print Hex(&HF0F0 Or &HFF00) Debug.Print Hex(&HF0F0 Xor &HFF00) Debug.Print Hex(Not &HF0F0) Debug.Print Hex(&HF0F0 Eqv &HFF00) Debug.Print Hex(&HF0F0 Imp &HFF00)
Generate an equivalent Rust version of this C code.
void bitwise(int a, int b) { printf("a and b: %d\n", a & b); printf("a or b: %d\n", a | b); printf("a xor b: %d\n", a ^ b); printf("not a: %d\n", ~a); printf("a << n: %d\n", a << b); printf("a >> n: %d\n", a >> b); unsigned int c = a; printf("c >> b: %d\n", c >> b); return 0; }
fn main() { let a: u8 = 105; let b: u8 = 91; println!("a = {:0>8b}", a); println!("b = {:0>8b}", b); println!("a | b = {:0>8b}", a | b); println!("a & b = {:0>8b}", a & b); println!("a ^ b = {:0>8b}", a ^ b); println!("!a = {:0>8b}", !a); println!("a << 3 = {:0>8b}", a << 3); println!("a >> 3 = {:0>8b}", a >> 3); }
Can you help me rewrite this code in Rust instead of C++, keeping it the same logically?
#include <iostream> void bitwise(int a, int b) { std::cout << "a and b: " << (a & b) << '\n'; std::cout << "a or b: " << (a | b) << '\n'; std::cout << "a xor b: " << (a ^ b) << '\n'; std::cout << "not a: " << ~a << '\n'; std::cout << "a shl b: " << (a << b) << '\n'; std::cout << "a shr b: " << (a >> b) << '\n'; unsigned int ua = a; std::cout << "a lsr b: " << (ua >> b) << '\n'; std::cout << "a rol b: " << std::rotl(ua, b) << '\n'; std::cout << "a ror b: " << std::rotr(ua, b) << '\n'; }
fn main() { let a: u8 = 105; let b: u8 = 91; println!("a = {:0>8b}", a); println!("b = {:0>8b}", b); println!("a | b = {:0>8b}", a | b); println!("a & b = {:0>8b}", a & b); println!("a ^ b = {:0>8b}", a ^ b); println!("!a = {:0>8b}", !a); println!("a << 3 = {:0>8b}", a << 3); println!("a >> 3 = {:0>8b}", a >> 3); }
Ensure the translated Rust code behaves exactly like the original C# snippet.
static void bitwise(int a, int b) { Console.WriteLine("a and b is {0}", a & b); Console.WriteLine("a or b is {0}", a | b); Console.WriteLine("a xor b is {0}", a ^ b); Console.WriteLine("not a is {0}", ~a); Console.WriteLine("a lshift b is {0}", a << b); Console.WriteLine("a arshift b is {0}", a >> b); uint c = (uint)a; Console.WriteLine("c rshift b is {0}", c >> b); }
fn main() { let a: u8 = 105; let b: u8 = 91; println!("a = {:0>8b}", a); println!("b = {:0>8b}", b); println!("a | b = {:0>8b}", a | b); println!("a & b = {:0>8b}", a & b); println!("a ^ b = {:0>8b}", a ^ b); println!("!a = {:0>8b}", !a); println!("a << 3 = {:0>8b}", a << 3); println!("a >> 3 = {:0>8b}", a >> 3); }
Preserve the algorithm and functionality while converting the code from Go to Rust.
package main import "fmt" func bitwise(a, b int16) { fmt.Printf("a: %016b\n", uint16(a)) fmt.Printf("b: %016b\n", uint16(b)) fmt.Printf("and: %016b\n", uint16(a&b)) fmt.Printf("or: %016b\n", uint16(a|b)) fmt.Printf("xor: %016b\n", uint16(a^b)) fmt.Printf("not: %016b\n", uint16(^a)) if b < 0 { fmt.Println("Right operand is negative, but all shifts require an unsigned right operand (shift distance).") return } ua := uint16(a) ub := uint32(b) fmt.Printf("shl: %016b\n", uint16(ua<<ub)) fmt.Printf("shr: %016b\n", uint16(ua>>ub)) fmt.Printf("las: %016b\n", uint16(a<<ub)) fmt.Printf("ras: %016b\n", uint16(a>>ub)) fmt.Printf("rol: %016b\n", uint16(a<<ub|int16(uint16(a)>>(16-ub)))) fmt.Printf("ror: %016b\n", uint16(int16(uint16(a)>>ub)|a<<(16-ub))) } func main() { var a, b int16 = -460, 6 bitwise(a, b) }
fn main() { let a: u8 = 105; let b: u8 = 91; println!("a = {:0>8b}", a); println!("b = {:0>8b}", b); println!("a | b = {:0>8b}", a | b); println!("a & b = {:0>8b}", a & b); println!("a ^ b = {:0>8b}", a ^ b); println!("!a = {:0>8b}", !a); println!("a << 3 = {:0>8b}", a << 3); println!("a >> 3 = {:0>8b}", a >> 3); }
Produce a functionally identical C# code for the snippet given in Ada.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Gnat.Heap_Sort_G; procedure stemleaf is data : array(Natural Range <>) of Integer := ( 0,12,127,28,42,39,113, 42,18,44,118,44,37,113,124,37,48,127,36,29,31, 125,139,131,115,105,132,104,123,35,113,122,42,117,119,58,109,23,105, 63,27,44,105,99,41,128,121,116,125,32,61,37,127,29,113,121,58,114,126, 53,114,96,25,109,7,31,141,46,13,27,43,117,116,27,7,68,40,31,115,124,42, 128,52,71,118,117,38,27,106,33,117,116,111,40,119,47,105,57,122,109, 124,115,43,120,43,27,27,18,28,48,125,107,114,34,133,45,120, 30,127, 31,116,146); procedure Move (from, to : in Natural) is begin data(to) := data(from); end Move; function Cmp (p1, p2 : Natural) return Boolean is begin return data(p1)<data(p2); end Cmp; package Sorty is new GNAT.Heap_Sort_G(Move,Cmp); min,max,p,stemw: Integer; begin Sorty.Sort(data'Last); min := data(1); max := data(data'Last); stemw := Integer'Image(max)'Length; p := 1; for stem in min/10..max/10 loop put(stem,Width=>stemw); put(" |"); Leaf_Loop: while data(p)/10=stem loop put(" "); put(data(p) mod 10,Width=>1); exit Leaf_loop when p=data'Last; p := p+1; end loop Leaf_Loop; new_line; end loop; end stemleaf;
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { const string data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " + "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 " + "105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 " + "114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 " + "115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 " + "105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 " + "133 45 120 30 127 31 116 146"; int[] ints = data.Split(' ').Select(int.Parse).ToArray(); StemAndLeafPlot(ints); Console.ReadKey(); } public static void StemAndLeafPlot(int[] arr) { int stemMax = arr.Max() / 10; int stemMin = arr.Min() / 10; Array.Sort(arr); for (int i = stemMin; i <= stemMax; i++) { Console.Write("{0,3} | ", i); foreach (var t in arr) { if (t < 10 * i) continue; if (t >= 10 * (i + 1)) break; Console.Write("{0} ", t % 10); } Console.WriteLine(""); } } }
Translate this program into C but keep the logic exactly as in Ada.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Gnat.Heap_Sort_G; procedure stemleaf is data : array(Natural Range <>) of Integer := ( 0,12,127,28,42,39,113, 42,18,44,118,44,37,113,124,37,48,127,36,29,31, 125,139,131,115,105,132,104,123,35,113,122,42,117,119,58,109,23,105, 63,27,44,105,99,41,128,121,116,125,32,61,37,127,29,113,121,58,114,126, 53,114,96,25,109,7,31,141,46,13,27,43,117,116,27,7,68,40,31,115,124,42, 128,52,71,118,117,38,27,106,33,117,116,111,40,119,47,105,57,122,109, 124,115,43,120,43,27,27,18,28,48,125,107,114,34,133,45,120, 30,127, 31,116,146); procedure Move (from, to : in Natural) is begin data(to) := data(from); end Move; function Cmp (p1, p2 : Natural) return Boolean is begin return data(p1)<data(p2); end Cmp; package Sorty is new GNAT.Heap_Sort_G(Move,Cmp); min,max,p,stemw: Integer; begin Sorty.Sort(data'Last); min := data(1); max := data(data'Last); stemw := Integer'Image(max)'Length; p := 1; for stem in min/10..max/10 loop put(stem,Width=>stemw); put(" |"); Leaf_Loop: while data(p)/10=stem loop put(" "); put(data(p) mod 10,Width=>1); exit Leaf_loop when p=data'Last; p := p+1; end loop Leaf_Loop; new_line; end loop; end stemleaf;
#include <stdio.h> #include <stdlib.h> int icmp(const void *a, const void *b) { return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*)b; } void leaf_plot(int *x, int len) { int i, j, d; qsort(x, len, sizeof(int), icmp); i = x[0] / 10 - 1; for (j = 0; j < len; j++) { d = x[j] / 10; while (d > i) printf("%s%3d |", j ? "\n" : "", ++i); printf(" %d", x[j] % 10); } } int main() { int data[] = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; leaf_plot(data, sizeof(data)/sizeof(data[0])); return 0; }
Convert this Ada snippet to C++ and keep its semantics consistent.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Gnat.Heap_Sort_G; procedure stemleaf is data : array(Natural Range <>) of Integer := ( 0,12,127,28,42,39,113, 42,18,44,118,44,37,113,124,37,48,127,36,29,31, 125,139,131,115,105,132,104,123,35,113,122,42,117,119,58,109,23,105, 63,27,44,105,99,41,128,121,116,125,32,61,37,127,29,113,121,58,114,126, 53,114,96,25,109,7,31,141,46,13,27,43,117,116,27,7,68,40,31,115,124,42, 128,52,71,118,117,38,27,106,33,117,116,111,40,119,47,105,57,122,109, 124,115,43,120,43,27,27,18,28,48,125,107,114,34,133,45,120, 30,127, 31,116,146); procedure Move (from, to : in Natural) is begin data(to) := data(from); end Move; function Cmp (p1, p2 : Natural) return Boolean is begin return data(p1)<data(p2); end Cmp; package Sorty is new GNAT.Heap_Sort_G(Move,Cmp); min,max,p,stemw: Integer; begin Sorty.Sort(data'Last); min := data(1); max := data(data'Last); stemw := Integer'Image(max)'Length; p := 1; for stem in min/10..max/10 loop put(stem,Width=>stemw); put(" |"); Leaf_Loop: while data(p)/10=stem loop put(" "); put(data(p) mod 10,Width=>1); exit Leaf_loop when p=data'Last; p := p+1; end loop Leaf_Loop; new_line; end loop; end stemleaf;
#include <algorithm> #include <iomanip> #include <iostream> #include <vector> const int dataset[] = { 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115,105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125, 32, 61, 37,127, 29,113, 121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116, 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117, 116,111, 40,119, 47,105, 57,122,109,124,115, 43,120, 43, 27, 27, 18, 28, 48,125,107,114, 34,133, 45,120, 30,127, 31,116,146 }; const int datasize = sizeof(dataset) / sizeof(dataset[0]); int main() { typedef std::pair<int,int> StemLeaf; std::vector<StemLeaf> stemplot; for (int i = 0; i < datasize; ++i) { stemplot.push_back(StemLeaf(dataset[i] / 10, dataset[i] % 10)); } std::sort(stemplot.begin(), stemplot.end()); int lo = stemplot.front().first; int hi = stemplot.back().first; for (std::vector<StemLeaf>::iterator itr = stemplot.begin(); lo <= hi; ++lo) { std::cout << std::setw(2) << lo << " |"; for ( ; itr != stemplot.end() && itr->first == lo; ++itr) { std::cout << " " << itr->second; } std::cout << std::endl; } }
Translate this program into Go but keep the logic exactly as in Ada.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Gnat.Heap_Sort_G; procedure stemleaf is data : array(Natural Range <>) of Integer := ( 0,12,127,28,42,39,113, 42,18,44,118,44,37,113,124,37,48,127,36,29,31, 125,139,131,115,105,132,104,123,35,113,122,42,117,119,58,109,23,105, 63,27,44,105,99,41,128,121,116,125,32,61,37,127,29,113,121,58,114,126, 53,114,96,25,109,7,31,141,46,13,27,43,117,116,27,7,68,40,31,115,124,42, 128,52,71,118,117,38,27,106,33,117,116,111,40,119,47,105,57,122,109, 124,115,43,120,43,27,27,18,28,48,125,107,114,34,133,45,120, 30,127, 31,116,146); procedure Move (from, to : in Natural) is begin data(to) := data(from); end Move; function Cmp (p1, p2 : Natural) return Boolean is begin return data(p1)<data(p2); end Cmp; package Sorty is new GNAT.Heap_Sort_G(Move,Cmp); min,max,p,stemw: Integer; begin Sorty.Sort(data'Last); min := data(1); max := data(data'Last); stemw := Integer'Image(max)'Length; p := 1; for stem in min/10..max/10 loop put(stem,Width=>stemw); put(" |"); Leaf_Loop: while data(p)/10=stem loop put(" "); put(data(p) mod 10,Width=>1); exit Leaf_loop when p=data'Last; p := p+1; end loop Leaf_Loop; new_line; end loop; end stemleaf;
package main import ( "fmt" "sort" "strconv" "strings" ) var data = `12 127 28 42` func main() { m := make(map[int][]string) for _, s := range strings.Fields(data) { if len(s) == 1 { m[0] = append(m[0], s) } else if i, err := strconv.Atoi(s[:len(s)-1]); err == nil { m[i] = append(m[i], s[len(s)-1:]) } else { panic("non numeric data") } } s := make([]int, len(m)) var i int for k := range m { s[i] = k i++ } sort.Ints(s) for k := s[0]; ; k++ { v := m[k] sort.Strings(v) fmt.Printf("%2d | %s\n", k, strings.Join(v, " ")) if k == s[len(s)-1] { break } } }
Produce a language-to-language conversion: from Ada to Java, same semantics.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Gnat.Heap_Sort_G; procedure stemleaf is data : array(Natural Range <>) of Integer := ( 0,12,127,28,42,39,113, 42,18,44,118,44,37,113,124,37,48,127,36,29,31, 125,139,131,115,105,132,104,123,35,113,122,42,117,119,58,109,23,105, 63,27,44,105,99,41,128,121,116,125,32,61,37,127,29,113,121,58,114,126, 53,114,96,25,109,7,31,141,46,13,27,43,117,116,27,7,68,40,31,115,124,42, 128,52,71,118,117,38,27,106,33,117,116,111,40,119,47,105,57,122,109, 124,115,43,120,43,27,27,18,28,48,125,107,114,34,133,45,120, 30,127, 31,116,146); procedure Move (from, to : in Natural) is begin data(to) := data(from); end Move; function Cmp (p1, p2 : Natural) return Boolean is begin return data(p1)<data(p2); end Cmp; package Sorty is new GNAT.Heap_Sort_G(Move,Cmp); min,max,p,stemw: Integer; begin Sorty.Sort(data'Last); min := data(1); max := data(data'Last); stemw := Integer'Image(max)'Length; p := 1; for stem in min/10..max/10 loop put(stem,Width=>stemw); put(" |"); Leaf_Loop: while data(p)/10=stem loop put(" "); put(data(p) mod 10,Width=>1); exit Leaf_loop when p=data'Last; p := p+1; end loop Leaf_Loop; new_line; end loop; end stemleaf;
import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class StemAndLeaf { private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; public static Map<Integer, List<Integer>> createPlot(int... data){ Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>(); int highestStem = -1; for(int datum:data){ int leaf = datum % 10; int stem = datum / 10; if(stem > highestStem){ highestStem = stem; } if(plot.containsKey(stem)){ plot.get(stem).add(leaf); }else{ LinkedList<Integer> list = new LinkedList<Integer>(); list.add(leaf); plot.put(stem, list); } } if(plot.keySet().size() < highestStem + 1 ){ for(int i = 0; i <= highestStem; i++){ if(!plot.containsKey(i)){ LinkedList<Integer> list = new LinkedList<Integer>(); plot.put(i, list); } } } return plot; } public static void printPlot(Map<Integer, List<Integer>> plot){ for(Map.Entry<Integer, List<Integer>> line : plot.entrySet()){ Collections.sort(line.getValue()); System.out.println(line.getKey() + " | " + line.getValue()); } } public static void main(String[] args){ Map<Integer, List<Integer>> plot = createPlot(data); printPlot(plot); } }
Please provide an equivalent version of this Ada code in Python.
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Gnat.Heap_Sort_G; procedure stemleaf is data : array(Natural Range <>) of Integer := ( 0,12,127,28,42,39,113, 42,18,44,118,44,37,113,124,37,48,127,36,29,31, 125,139,131,115,105,132,104,123,35,113,122,42,117,119,58,109,23,105, 63,27,44,105,99,41,128,121,116,125,32,61,37,127,29,113,121,58,114,126, 53,114,96,25,109,7,31,141,46,13,27,43,117,116,27,7,68,40,31,115,124,42, 128,52,71,118,117,38,27,106,33,117,116,111,40,119,47,105,57,122,109, 124,115,43,120,43,27,27,18,28,48,125,107,114,34,133,45,120, 30,127, 31,116,146); procedure Move (from, to : in Natural) is begin data(to) := data(from); end Move; function Cmp (p1, p2 : Natural) return Boolean is begin return data(p1)<data(p2); end Cmp; package Sorty is new GNAT.Heap_Sort_G(Move,Cmp); min,max,p,stemw: Integer; begin Sorty.Sort(data'Last); min := data(1); max := data(data'Last); stemw := Integer'Image(max)'Length; p := 1; for stem in min/10..max/10 loop put(stem,Width=>stemw); put(" |"); Leaf_Loop: while data(p)/10=stem loop put(" "); put(data(p) mod 10,Width=>1); exit Leaf_loop when p=data'Last; p := p+1; end loop Leaf_Loop; new_line; end loop; end stemleaf;
from collections import namedtuple from pprint import pprint as pp from math import floor Stem = namedtuple('Stem', 'data, leafdigits') data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146), 1.0) def stemplot(stem): d = [] interval = int(10**int(stem.leafdigits)) for data in sorted(stem.data): data = int(floor(data)) stm, lf = divmod(data,interval) d.append( (int(stm), int(lf)) ) stems, leafs = list(zip(*d)) stemwidth = max(len(str(x)) for x in stems) leafwidth = max(len(str(x)) for x in leafs) laststem, out = min(stems) - 1, [] for s,l in d: while laststem < s: laststem += 1 out.append('\n%*i |' % ( stemwidth, laststem)) out.append(' %0*i' % (leafwidth, l)) out.append('\n\nKey:\n Stem multiplier: %i\n X | Y => %i*X+Y\n' % (interval, interval)) return ''.join(out) if __name__ == '__main__': print( stemplot(data0) )
Convert this AutoHotKey block to C, preserving its control flow and logic.
SetWorkingDir %A_ScriptDir% #NoEnv Data := "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146"   While (Instr(Data," ")) StringReplace, Data, Data,%A_Space%%A_Space%,%A_Space%,All Sort, Data,ND%A_Space% OldStem := 0 Loop, parse, Data,%A_Space% { NewStem := SubStr(A_LoopField,1,StrLen(A_LoopField)-1)   If ( NewStem <> OldStem and StrLen(A_LoopField) <> 1) { While(OldStem+1<>NewStem)   OldStem++,ToPrint .= "`n" PadStem(oldStem) ToPrint .= "`n" PadStem(NewStem) OldStem := NewStem } Else If ( StrLen(A_LoopField)=1 and !FirstStem) ToPrint .= PadStem(0),FirstStem := true ToPrint .= SubStr(A_LoopField,strLen(A_LoopField)) " "   }   FileDelete Stem and leaf.txt FileAppend %ToPrint%, Stem and Leaf.txt Run Stem and leaf.txt return PadStem(Stem){ Spaces = 0 While ( 3 - StrLen(Stem) <> Spaces )   ToReturn .= " ",Spaces++ ToReturn .= Stem ToReturn .= " | " Return ToReturn }
#include <stdio.h> #include <stdlib.h> int icmp(const void *a, const void *b) { return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*)b; } void leaf_plot(int *x, int len) { int i, j, d; qsort(x, len, sizeof(int), icmp); i = x[0] / 10 - 1; for (j = 0; j < len; j++) { d = x[j] / 10; while (d > i) printf("%s%3d |", j ? "\n" : "", ++i); printf(" %d", x[j] % 10); } } int main() { int data[] = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; leaf_plot(data, sizeof(data)/sizeof(data[0])); return 0; }
Translate the given AutoHotKey code snippet into C# without altering its behavior.
SetWorkingDir %A_ScriptDir% #NoEnv Data := "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146"   While (Instr(Data," ")) StringReplace, Data, Data,%A_Space%%A_Space%,%A_Space%,All Sort, Data,ND%A_Space% OldStem := 0 Loop, parse, Data,%A_Space% { NewStem := SubStr(A_LoopField,1,StrLen(A_LoopField)-1)   If ( NewStem <> OldStem and StrLen(A_LoopField) <> 1) { While(OldStem+1<>NewStem)   OldStem++,ToPrint .= "`n" PadStem(oldStem) ToPrint .= "`n" PadStem(NewStem) OldStem := NewStem } Else If ( StrLen(A_LoopField)=1 and !FirstStem) ToPrint .= PadStem(0),FirstStem := true ToPrint .= SubStr(A_LoopField,strLen(A_LoopField)) " "   }   FileDelete Stem and leaf.txt FileAppend %ToPrint%, Stem and Leaf.txt Run Stem and leaf.txt return PadStem(Stem){ Spaces = 0 While ( 3 - StrLen(Stem) <> Spaces )   ToReturn .= " ",Spaces++ ToReturn .= Stem ToReturn .= " | " Return ToReturn }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { const string data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " + "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 " + "105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 " + "114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 " + "115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 " + "105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 " + "133 45 120 30 127 31 116 146"; int[] ints = data.Split(' ').Select(int.Parse).ToArray(); StemAndLeafPlot(ints); Console.ReadKey(); } public static void StemAndLeafPlot(int[] arr) { int stemMax = arr.Max() / 10; int stemMin = arr.Min() / 10; Array.Sort(arr); for (int i = stemMin; i <= stemMax; i++) { Console.Write("{0,3} | ", i); foreach (var t in arr) { if (t < 10 * i) continue; if (t >= 10 * (i + 1)) break; Console.Write("{0} ", t % 10); } Console.WriteLine(""); } } }
Transform the following AutoHotKey implementation into C++, maintaining the same output and logic.
SetWorkingDir %A_ScriptDir% #NoEnv Data := "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146"   While (Instr(Data," ")) StringReplace, Data, Data,%A_Space%%A_Space%,%A_Space%,All Sort, Data,ND%A_Space% OldStem := 0 Loop, parse, Data,%A_Space% { NewStem := SubStr(A_LoopField,1,StrLen(A_LoopField)-1)   If ( NewStem <> OldStem and StrLen(A_LoopField) <> 1) { While(OldStem+1<>NewStem)   OldStem++,ToPrint .= "`n" PadStem(oldStem) ToPrint .= "`n" PadStem(NewStem) OldStem := NewStem } Else If ( StrLen(A_LoopField)=1 and !FirstStem) ToPrint .= PadStem(0),FirstStem := true ToPrint .= SubStr(A_LoopField,strLen(A_LoopField)) " "   }   FileDelete Stem and leaf.txt FileAppend %ToPrint%, Stem and Leaf.txt Run Stem and leaf.txt return PadStem(Stem){ Spaces = 0 While ( 3 - StrLen(Stem) <> Spaces )   ToReturn .= " ",Spaces++ ToReturn .= Stem ToReturn .= " | " Return ToReturn }
#include <algorithm> #include <iomanip> #include <iostream> #include <vector> const int dataset[] = { 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115,105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125, 32, 61, 37,127, 29,113, 121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116, 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117, 116,111, 40,119, 47,105, 57,122,109,124,115, 43,120, 43, 27, 27, 18, 28, 48,125,107,114, 34,133, 45,120, 30,127, 31,116,146 }; const int datasize = sizeof(dataset) / sizeof(dataset[0]); int main() { typedef std::pair<int,int> StemLeaf; std::vector<StemLeaf> stemplot; for (int i = 0; i < datasize; ++i) { stemplot.push_back(StemLeaf(dataset[i] / 10, dataset[i] % 10)); } std::sort(stemplot.begin(), stemplot.end()); int lo = stemplot.front().first; int hi = stemplot.back().first; for (std::vector<StemLeaf>::iterator itr = stemplot.begin(); lo <= hi; ++lo) { std::cout << std::setw(2) << lo << " |"; for ( ; itr != stemplot.end() && itr->first == lo; ++itr) { std::cout << " " << itr->second; } std::cout << std::endl; } }
Translate this program into Java but keep the logic exactly as in AutoHotKey.
SetWorkingDir %A_ScriptDir% #NoEnv Data := "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146"   While (Instr(Data," ")) StringReplace, Data, Data,%A_Space%%A_Space%,%A_Space%,All Sort, Data,ND%A_Space% OldStem := 0 Loop, parse, Data,%A_Space% { NewStem := SubStr(A_LoopField,1,StrLen(A_LoopField)-1)   If ( NewStem <> OldStem and StrLen(A_LoopField) <> 1) { While(OldStem+1<>NewStem)   OldStem++,ToPrint .= "`n" PadStem(oldStem) ToPrint .= "`n" PadStem(NewStem) OldStem := NewStem } Else If ( StrLen(A_LoopField)=1 and !FirstStem) ToPrint .= PadStem(0),FirstStem := true ToPrint .= SubStr(A_LoopField,strLen(A_LoopField)) " "   }   FileDelete Stem and leaf.txt FileAppend %ToPrint%, Stem and Leaf.txt Run Stem and leaf.txt return PadStem(Stem){ Spaces = 0 While ( 3 - StrLen(Stem) <> Spaces )   ToReturn .= " ",Spaces++ ToReturn .= Stem ToReturn .= " | " Return ToReturn }
import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class StemAndLeaf { private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; public static Map<Integer, List<Integer>> createPlot(int... data){ Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>(); int highestStem = -1; for(int datum:data){ int leaf = datum % 10; int stem = datum / 10; if(stem > highestStem){ highestStem = stem; } if(plot.containsKey(stem)){ plot.get(stem).add(leaf); }else{ LinkedList<Integer> list = new LinkedList<Integer>(); list.add(leaf); plot.put(stem, list); } } if(plot.keySet().size() < highestStem + 1 ){ for(int i = 0; i <= highestStem; i++){ if(!plot.containsKey(i)){ LinkedList<Integer> list = new LinkedList<Integer>(); plot.put(i, list); } } } return plot; } public static void printPlot(Map<Integer, List<Integer>> plot){ for(Map.Entry<Integer, List<Integer>> line : plot.entrySet()){ Collections.sort(line.getValue()); System.out.println(line.getKey() + " | " + line.getValue()); } } public static void main(String[] args){ Map<Integer, List<Integer>> plot = createPlot(data); printPlot(plot); } }
Can you help me rewrite this code in Python instead of AutoHotKey, keeping it the same logically?
SetWorkingDir %A_ScriptDir% #NoEnv Data := "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146"   While (Instr(Data," ")) StringReplace, Data, Data,%A_Space%%A_Space%,%A_Space%,All Sort, Data,ND%A_Space% OldStem := 0 Loop, parse, Data,%A_Space% { NewStem := SubStr(A_LoopField,1,StrLen(A_LoopField)-1)   If ( NewStem <> OldStem and StrLen(A_LoopField) <> 1) { While(OldStem+1<>NewStem)   OldStem++,ToPrint .= "`n" PadStem(oldStem) ToPrint .= "`n" PadStem(NewStem) OldStem := NewStem } Else If ( StrLen(A_LoopField)=1 and !FirstStem) ToPrint .= PadStem(0),FirstStem := true ToPrint .= SubStr(A_LoopField,strLen(A_LoopField)) " "   }   FileDelete Stem and leaf.txt FileAppend %ToPrint%, Stem and Leaf.txt Run Stem and leaf.txt return PadStem(Stem){ Spaces = 0 While ( 3 - StrLen(Stem) <> Spaces )   ToReturn .= " ",Spaces++ ToReturn .= Stem ToReturn .= " | " Return ToReturn }
from collections import namedtuple from pprint import pprint as pp from math import floor Stem = namedtuple('Stem', 'data, leafdigits') data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146), 1.0) def stemplot(stem): d = [] interval = int(10**int(stem.leafdigits)) for data in sorted(stem.data): data = int(floor(data)) stm, lf = divmod(data,interval) d.append( (int(stm), int(lf)) ) stems, leafs = list(zip(*d)) stemwidth = max(len(str(x)) for x in stems) leafwidth = max(len(str(x)) for x in leafs) laststem, out = min(stems) - 1, [] for s,l in d: while laststem < s: laststem += 1 out.append('\n%*i |' % ( stemwidth, laststem)) out.append(' %0*i' % (leafwidth, l)) out.append('\n\nKey:\n Stem multiplier: %i\n X | Y => %i*X+Y\n' % (interval, interval)) return ''.join(out) if __name__ == '__main__': print( stemplot(data0) )
Produce a language-to-language conversion: from AutoHotKey to Go, same semantics.
SetWorkingDir %A_ScriptDir% #NoEnv Data := "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146"   While (Instr(Data," ")) StringReplace, Data, Data,%A_Space%%A_Space%,%A_Space%,All Sort, Data,ND%A_Space% OldStem := 0 Loop, parse, Data,%A_Space% { NewStem := SubStr(A_LoopField,1,StrLen(A_LoopField)-1)   If ( NewStem <> OldStem and StrLen(A_LoopField) <> 1) { While(OldStem+1<>NewStem)   OldStem++,ToPrint .= "`n" PadStem(oldStem) ToPrint .= "`n" PadStem(NewStem) OldStem := NewStem } Else If ( StrLen(A_LoopField)=1 and !FirstStem) ToPrint .= PadStem(0),FirstStem := true ToPrint .= SubStr(A_LoopField,strLen(A_LoopField)) " "   }   FileDelete Stem and leaf.txt FileAppend %ToPrint%, Stem and Leaf.txt Run Stem and leaf.txt return PadStem(Stem){ Spaces = 0 While ( 3 - StrLen(Stem) <> Spaces )   ToReturn .= " ",Spaces++ ToReturn .= Stem ToReturn .= " | " Return ToReturn }
package main import ( "fmt" "sort" "strconv" "strings" ) var data = `12 127 28 42` func main() { m := make(map[int][]string) for _, s := range strings.Fields(data) { if len(s) == 1 { m[0] = append(m[0], s) } else if i, err := strconv.Atoi(s[:len(s)-1]); err == nil { m[i] = append(m[i], s[len(s)-1:]) } else { panic("non numeric data") } } s := make([]int, len(m)) var i int for k := range m { s[i] = k i++ } sort.Ints(s) for k := s[0]; ; k++ { v := m[k] sort.Strings(v) fmt.Printf("%2d | %s\n", k, strings.Join(v, " ")) if k == s[len(s)-1] { break } } }
Change the programming language of this snippet from AWK to C without modifying what it does.
BEGIN { data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " \ "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 " \ "105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 " \ "109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 " \ "38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 " \ "28 48 125 107 114 34 133 45 120 30 127 31 116 146" data_points = split(data,data_arr," ") for (i=1; i<=data_points; i++) { x = data_arr[i] stem = int(x / 10) leaf = x % 10 if (i == 1) { lo = hi = stem } lo = min(lo,stem) hi = max(hi,stem) arr[stem][leaf]++ } PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1 for (i=lo; i<=hi; i++) { printf("%4d |",i) arr[i][""] for (j in arr[i]) { for (k=1; k<=arr[i][j]; k++) { printf(" %d",j) leaves_printed++ } } printf("\n") } if (data_points == leaves_printed) { exit(0) } else { printf("error: %d data points != %d leaves printed\n",data_points,leaves_printed) exit(1) } } function max(x,y) { return((x > y) ? x : y) } function min(x,y) { return((x < y) ? x : y) }
#include <stdio.h> #include <stdlib.h> int icmp(const void *a, const void *b) { return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*)b; } void leaf_plot(int *x, int len) { int i, j, d; qsort(x, len, sizeof(int), icmp); i = x[0] / 10 - 1; for (j = 0; j < len; j++) { d = x[j] / 10; while (d > i) printf("%s%3d |", j ? "\n" : "", ++i); printf(" %d", x[j] % 10); } } int main() { int data[] = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; leaf_plot(data, sizeof(data)/sizeof(data[0])); return 0; }
Keep all operations the same but rewrite the snippet in C#.
BEGIN { data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " \ "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 " \ "105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 " \ "109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 " \ "38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 " \ "28 48 125 107 114 34 133 45 120 30 127 31 116 146" data_points = split(data,data_arr," ") for (i=1; i<=data_points; i++) { x = data_arr[i] stem = int(x / 10) leaf = x % 10 if (i == 1) { lo = hi = stem } lo = min(lo,stem) hi = max(hi,stem) arr[stem][leaf]++ } PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1 for (i=lo; i<=hi; i++) { printf("%4d |",i) arr[i][""] for (j in arr[i]) { for (k=1; k<=arr[i][j]; k++) { printf(" %d",j) leaves_printed++ } } printf("\n") } if (data_points == leaves_printed) { exit(0) } else { printf("error: %d data points != %d leaves printed\n",data_points,leaves_printed) exit(1) } } function max(x,y) { return((x > y) ? x : y) } function min(x,y) { return((x < y) ? x : y) }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { const string data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " + "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 " + "105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 " + "114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 " + "115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 " + "105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 " + "133 45 120 30 127 31 116 146"; int[] ints = data.Split(' ').Select(int.Parse).ToArray(); StemAndLeafPlot(ints); Console.ReadKey(); } public static void StemAndLeafPlot(int[] arr) { int stemMax = arr.Max() / 10; int stemMin = arr.Min() / 10; Array.Sort(arr); for (int i = stemMin; i <= stemMax; i++) { Console.Write("{0,3} | ", i); foreach (var t in arr) { if (t < 10 * i) continue; if (t >= 10 * (i + 1)) break; Console.Write("{0} ", t % 10); } Console.WriteLine(""); } } }
Keep all operations the same but rewrite the snippet in C++.
BEGIN { data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " \ "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 " \ "105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 " \ "109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 " \ "38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 " \ "28 48 125 107 114 34 133 45 120 30 127 31 116 146" data_points = split(data,data_arr," ") for (i=1; i<=data_points; i++) { x = data_arr[i] stem = int(x / 10) leaf = x % 10 if (i == 1) { lo = hi = stem } lo = min(lo,stem) hi = max(hi,stem) arr[stem][leaf]++ } PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1 for (i=lo; i<=hi; i++) { printf("%4d |",i) arr[i][""] for (j in arr[i]) { for (k=1; k<=arr[i][j]; k++) { printf(" %d",j) leaves_printed++ } } printf("\n") } if (data_points == leaves_printed) { exit(0) } else { printf("error: %d data points != %d leaves printed\n",data_points,leaves_printed) exit(1) } } function max(x,y) { return((x > y) ? x : y) } function min(x,y) { return((x < y) ? x : y) }
#include <algorithm> #include <iomanip> #include <iostream> #include <vector> const int dataset[] = { 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115,105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125, 32, 61, 37,127, 29,113, 121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116, 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117, 116,111, 40,119, 47,105, 57,122,109,124,115, 43,120, 43, 27, 27, 18, 28, 48,125,107,114, 34,133, 45,120, 30,127, 31,116,146 }; const int datasize = sizeof(dataset) / sizeof(dataset[0]); int main() { typedef std::pair<int,int> StemLeaf; std::vector<StemLeaf> stemplot; for (int i = 0; i < datasize; ++i) { stemplot.push_back(StemLeaf(dataset[i] / 10, dataset[i] % 10)); } std::sort(stemplot.begin(), stemplot.end()); int lo = stemplot.front().first; int hi = stemplot.back().first; for (std::vector<StemLeaf>::iterator itr = stemplot.begin(); lo <= hi; ++lo) { std::cout << std::setw(2) << lo << " |"; for ( ; itr != stemplot.end() && itr->first == lo; ++itr) { std::cout << " " << itr->second; } std::cout << std::endl; } }
Convert the following code from AWK to Java, ensuring the logic remains intact.
BEGIN { data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " \ "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 " \ "105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 " \ "109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 " \ "38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 " \ "28 48 125 107 114 34 133 45 120 30 127 31 116 146" data_points = split(data,data_arr," ") for (i=1; i<=data_points; i++) { x = data_arr[i] stem = int(x / 10) leaf = x % 10 if (i == 1) { lo = hi = stem } lo = min(lo,stem) hi = max(hi,stem) arr[stem][leaf]++ } PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1 for (i=lo; i<=hi; i++) { printf("%4d |",i) arr[i][""] for (j in arr[i]) { for (k=1; k<=arr[i][j]; k++) { printf(" %d",j) leaves_printed++ } } printf("\n") } if (data_points == leaves_printed) { exit(0) } else { printf("error: %d data points != %d leaves printed\n",data_points,leaves_printed) exit(1) } } function max(x,y) { return((x > y) ? x : y) } function min(x,y) { return((x < y) ? x : y) }
import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class StemAndLeaf { private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; public static Map<Integer, List<Integer>> createPlot(int... data){ Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>(); int highestStem = -1; for(int datum:data){ int leaf = datum % 10; int stem = datum / 10; if(stem > highestStem){ highestStem = stem; } if(plot.containsKey(stem)){ plot.get(stem).add(leaf); }else{ LinkedList<Integer> list = new LinkedList<Integer>(); list.add(leaf); plot.put(stem, list); } } if(plot.keySet().size() < highestStem + 1 ){ for(int i = 0; i <= highestStem; i++){ if(!plot.containsKey(i)){ LinkedList<Integer> list = new LinkedList<Integer>(); plot.put(i, list); } } } return plot; } public static void printPlot(Map<Integer, List<Integer>> plot){ for(Map.Entry<Integer, List<Integer>> line : plot.entrySet()){ Collections.sort(line.getValue()); System.out.println(line.getKey() + " | " + line.getValue()); } } public static void main(String[] args){ Map<Integer, List<Integer>> plot = createPlot(data); printPlot(plot); } }
Port the provided AWK code into Python while preserving the original functionality.
BEGIN { data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " \ "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 " \ "105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 " \ "109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 " \ "38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 " \ "28 48 125 107 114 34 133 45 120 30 127 31 116 146" data_points = split(data,data_arr," ") for (i=1; i<=data_points; i++) { x = data_arr[i] stem = int(x / 10) leaf = x % 10 if (i == 1) { lo = hi = stem } lo = min(lo,stem) hi = max(hi,stem) arr[stem][leaf]++ } PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1 for (i=lo; i<=hi; i++) { printf("%4d |",i) arr[i][""] for (j in arr[i]) { for (k=1; k<=arr[i][j]; k++) { printf(" %d",j) leaves_printed++ } } printf("\n") } if (data_points == leaves_printed) { exit(0) } else { printf("error: %d data points != %d leaves printed\n",data_points,leaves_printed) exit(1) } } function max(x,y) { return((x > y) ? x : y) } function min(x,y) { return((x < y) ? x : y) }
from collections import namedtuple from pprint import pprint as pp from math import floor Stem = namedtuple('Stem', 'data, leafdigits') data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146), 1.0) def stemplot(stem): d = [] interval = int(10**int(stem.leafdigits)) for data in sorted(stem.data): data = int(floor(data)) stm, lf = divmod(data,interval) d.append( (int(stm), int(lf)) ) stems, leafs = list(zip(*d)) stemwidth = max(len(str(x)) for x in stems) leafwidth = max(len(str(x)) for x in leafs) laststem, out = min(stems) - 1, [] for s,l in d: while laststem < s: laststem += 1 out.append('\n%*i |' % ( stemwidth, laststem)) out.append(' %0*i' % (leafwidth, l)) out.append('\n\nKey:\n Stem multiplier: %i\n X | Y => %i*X+Y\n' % (interval, interval)) return ''.join(out) if __name__ == '__main__': print( stemplot(data0) )
Keep all operations the same but rewrite the snippet in Go.
BEGIN { data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " \ "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 " \ "105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 " \ "109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 " \ "38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 " \ "28 48 125 107 114 34 133 45 120 30 127 31 116 146" data_points = split(data,data_arr," ") for (i=1; i<=data_points; i++) { x = data_arr[i] stem = int(x / 10) leaf = x % 10 if (i == 1) { lo = hi = stem } lo = min(lo,stem) hi = max(hi,stem) arr[stem][leaf]++ } PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1 for (i=lo; i<=hi; i++) { printf("%4d |",i) arr[i][""] for (j in arr[i]) { for (k=1; k<=arr[i][j]; k++) { printf(" %d",j) leaves_printed++ } } printf("\n") } if (data_points == leaves_printed) { exit(0) } else { printf("error: %d data points != %d leaves printed\n",data_points,leaves_printed) exit(1) } } function max(x,y) { return((x > y) ? x : y) } function min(x,y) { return((x < y) ? x : y) }
package main import ( "fmt" "sort" "strconv" "strings" ) var data = `12 127 28 42` func main() { m := make(map[int][]string) for _, s := range strings.Fields(data) { if len(s) == 1 { m[0] = append(m[0], s) } else if i, err := strconv.Atoi(s[:len(s)-1]); err == nil { m[i] = append(m[i], s[len(s)-1:]) } else { panic("non numeric data") } } s := make([]int, len(m)) var i int for k := range m { s[i] = k i++ } sort.Ints(s) for k := s[0]; ; k++ { v := m[k] sort.Strings(v) fmt.Printf("%2d | %s\n", k, strings.Join(v, " ")) if k == s[len(s)-1] { break } } }
Convert the following code from BBC_Basic to C, ensuring the logic remains intact.
INSTALL @lib$+"SORTLIB" Sort% = FN_sortinit(0, 0) DIM Data%(120) Data%() = \ \ 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, \ \ 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, \ \ 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, \ \ 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, \ \ 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, \ \ 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, \ \ 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, \ \ 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, \ \ 34, 133, 45, 120, 30, 127, 31, 116, 146 PROCleafplot(Data%(), DIM(Data%(),1) + 1) END DEF PROCleafplot(x%(), n%) LOCAL @%, C%, i%, j%, d% @% = 2 C% = n% CALL Sort%, x%(0) i% = x%(0) DIV 10 - 1 FOR j% = 0 TO n% - 1 d% = x%(j%) DIV 10 WHILE d% > i% i% += 1 IF j% PRINT PRINT i% " |" ; ENDWHILE PRINT x%(j%) MOD 10 ; NEXT PRINT ENDPROC
#include <stdio.h> #include <stdlib.h> int icmp(const void *a, const void *b) { return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*)b; } void leaf_plot(int *x, int len) { int i, j, d; qsort(x, len, sizeof(int), icmp); i = x[0] / 10 - 1; for (j = 0; j < len; j++) { d = x[j] / 10; while (d > i) printf("%s%3d |", j ? "\n" : "", ++i); printf(" %d", x[j] % 10); } } int main() { int data[] = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; leaf_plot(data, sizeof(data)/sizeof(data[0])); return 0; }
Rewrite the snippet below in C# so it works the same as the original BBC_Basic code.
INSTALL @lib$+"SORTLIB" Sort% = FN_sortinit(0, 0) DIM Data%(120) Data%() = \ \ 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, \ \ 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, \ \ 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, \ \ 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, \ \ 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, \ \ 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, \ \ 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, \ \ 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, \ \ 34, 133, 45, 120, 30, 127, 31, 116, 146 PROCleafplot(Data%(), DIM(Data%(),1) + 1) END DEF PROCleafplot(x%(), n%) LOCAL @%, C%, i%, j%, d% @% = 2 C% = n% CALL Sort%, x%(0) i% = x%(0) DIV 10 - 1 FOR j% = 0 TO n% - 1 d% = x%(j%) DIV 10 WHILE d% > i% i% += 1 IF j% PRINT PRINT i% " |" ; ENDWHILE PRINT x%(j%) MOD 10 ; NEXT PRINT ENDPROC
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { const string data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " + "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 " + "105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 " + "114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 " + "115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 " + "105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 " + "133 45 120 30 127 31 116 146"; int[] ints = data.Split(' ').Select(int.Parse).ToArray(); StemAndLeafPlot(ints); Console.ReadKey(); } public static void StemAndLeafPlot(int[] arr) { int stemMax = arr.Max() / 10; int stemMin = arr.Min() / 10; Array.Sort(arr); for (int i = stemMin; i <= stemMax; i++) { Console.Write("{0,3} | ", i); foreach (var t in arr) { if (t < 10 * i) continue; if (t >= 10 * (i + 1)) break; Console.Write("{0} ", t % 10); } Console.WriteLine(""); } } }
Generate an equivalent C++ version of this BBC_Basic code.
INSTALL @lib$+"SORTLIB" Sort% = FN_sortinit(0, 0) DIM Data%(120) Data%() = \ \ 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, \ \ 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, \ \ 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, \ \ 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, \ \ 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, \ \ 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, \ \ 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, \ \ 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, \ \ 34, 133, 45, 120, 30, 127, 31, 116, 146 PROCleafplot(Data%(), DIM(Data%(),1) + 1) END DEF PROCleafplot(x%(), n%) LOCAL @%, C%, i%, j%, d% @% = 2 C% = n% CALL Sort%, x%(0) i% = x%(0) DIV 10 - 1 FOR j% = 0 TO n% - 1 d% = x%(j%) DIV 10 WHILE d% > i% i% += 1 IF j% PRINT PRINT i% " |" ; ENDWHILE PRINT x%(j%) MOD 10 ; NEXT PRINT ENDPROC
#include <algorithm> #include <iomanip> #include <iostream> #include <vector> const int dataset[] = { 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115,105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125, 32, 61, 37,127, 29,113, 121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116, 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117, 116,111, 40,119, 47,105, 57,122,109,124,115, 43,120, 43, 27, 27, 18, 28, 48,125,107,114, 34,133, 45,120, 30,127, 31,116,146 }; const int datasize = sizeof(dataset) / sizeof(dataset[0]); int main() { typedef std::pair<int,int> StemLeaf; std::vector<StemLeaf> stemplot; for (int i = 0; i < datasize; ++i) { stemplot.push_back(StemLeaf(dataset[i] / 10, dataset[i] % 10)); } std::sort(stemplot.begin(), stemplot.end()); int lo = stemplot.front().first; int hi = stemplot.back().first; for (std::vector<StemLeaf>::iterator itr = stemplot.begin(); lo <= hi; ++lo) { std::cout << std::setw(2) << lo << " |"; for ( ; itr != stemplot.end() && itr->first == lo; ++itr) { std::cout << " " << itr->second; } std::cout << std::endl; } }
Produce a functionally identical Java code for the snippet given in BBC_Basic.
INSTALL @lib$+"SORTLIB" Sort% = FN_sortinit(0, 0) DIM Data%(120) Data%() = \ \ 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, \ \ 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, \ \ 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, \ \ 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, \ \ 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, \ \ 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, \ \ 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, \ \ 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, \ \ 34, 133, 45, 120, 30, 127, 31, 116, 146 PROCleafplot(Data%(), DIM(Data%(),1) + 1) END DEF PROCleafplot(x%(), n%) LOCAL @%, C%, i%, j%, d% @% = 2 C% = n% CALL Sort%, x%(0) i% = x%(0) DIV 10 - 1 FOR j% = 0 TO n% - 1 d% = x%(j%) DIV 10 WHILE d% > i% i% += 1 IF j% PRINT PRINT i% " |" ; ENDWHILE PRINT x%(j%) MOD 10 ; NEXT PRINT ENDPROC
import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class StemAndLeaf { private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; public static Map<Integer, List<Integer>> createPlot(int... data){ Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>(); int highestStem = -1; for(int datum:data){ int leaf = datum % 10; int stem = datum / 10; if(stem > highestStem){ highestStem = stem; } if(plot.containsKey(stem)){ plot.get(stem).add(leaf); }else{ LinkedList<Integer> list = new LinkedList<Integer>(); list.add(leaf); plot.put(stem, list); } } if(plot.keySet().size() < highestStem + 1 ){ for(int i = 0; i <= highestStem; i++){ if(!plot.containsKey(i)){ LinkedList<Integer> list = new LinkedList<Integer>(); plot.put(i, list); } } } return plot; } public static void printPlot(Map<Integer, List<Integer>> plot){ for(Map.Entry<Integer, List<Integer>> line : plot.entrySet()){ Collections.sort(line.getValue()); System.out.println(line.getKey() + " | " + line.getValue()); } } public static void main(String[] args){ Map<Integer, List<Integer>> plot = createPlot(data); printPlot(plot); } }
Rewrite the snippet below in Python so it works the same as the original BBC_Basic code.
INSTALL @lib$+"SORTLIB" Sort% = FN_sortinit(0, 0) DIM Data%(120) Data%() = \ \ 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, \ \ 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, \ \ 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, \ \ 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, \ \ 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, \ \ 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, \ \ 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, \ \ 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, \ \ 34, 133, 45, 120, 30, 127, 31, 116, 146 PROCleafplot(Data%(), DIM(Data%(),1) + 1) END DEF PROCleafplot(x%(), n%) LOCAL @%, C%, i%, j%, d% @% = 2 C% = n% CALL Sort%, x%(0) i% = x%(0) DIV 10 - 1 FOR j% = 0 TO n% - 1 d% = x%(j%) DIV 10 WHILE d% > i% i% += 1 IF j% PRINT PRINT i% " |" ; ENDWHILE PRINT x%(j%) MOD 10 ; NEXT PRINT ENDPROC
from collections import namedtuple from pprint import pprint as pp from math import floor Stem = namedtuple('Stem', 'data, leafdigits') data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146), 1.0) def stemplot(stem): d = [] interval = int(10**int(stem.leafdigits)) for data in sorted(stem.data): data = int(floor(data)) stm, lf = divmod(data,interval) d.append( (int(stm), int(lf)) ) stems, leafs = list(zip(*d)) stemwidth = max(len(str(x)) for x in stems) leafwidth = max(len(str(x)) for x in leafs) laststem, out = min(stems) - 1, [] for s,l in d: while laststem < s: laststem += 1 out.append('\n%*i |' % ( stemwidth, laststem)) out.append(' %0*i' % (leafwidth, l)) out.append('\n\nKey:\n Stem multiplier: %i\n X | Y => %i*X+Y\n' % (interval, interval)) return ''.join(out) if __name__ == '__main__': print( stemplot(data0) )
Convert this BBC_Basic snippet to Go and keep its semantics consistent.
INSTALL @lib$+"SORTLIB" Sort% = FN_sortinit(0, 0) DIM Data%(120) Data%() = \ \ 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, \ \ 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, \ \ 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, \ \ 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, \ \ 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, \ \ 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, \ \ 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, \ \ 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, \ \ 34, 133, 45, 120, 30, 127, 31, 116, 146 PROCleafplot(Data%(), DIM(Data%(),1) + 1) END DEF PROCleafplot(x%(), n%) LOCAL @%, C%, i%, j%, d% @% = 2 C% = n% CALL Sort%, x%(0) i% = x%(0) DIV 10 - 1 FOR j% = 0 TO n% - 1 d% = x%(j%) DIV 10 WHILE d% > i% i% += 1 IF j% PRINT PRINT i% " |" ; ENDWHILE PRINT x%(j%) MOD 10 ; NEXT PRINT ENDPROC
package main import ( "fmt" "sort" "strconv" "strings" ) var data = `12 127 28 42` func main() { m := make(map[int][]string) for _, s := range strings.Fields(data) { if len(s) == 1 { m[0] = append(m[0], s) } else if i, err := strconv.Atoi(s[:len(s)-1]); err == nil { m[i] = append(m[i], s[len(s)-1:]) } else { panic("non numeric data") } } s := make([]int, len(m)) var i int for k := range m { s[i] = k i++ } sort.Ints(s) for k := s[0]; ; k++ { v := m[k] sort.Strings(v) fmt.Printf("%2d | %s\n", k, strings.Join(v, " ")) if k == s[len(s)-1] { break } } }
Maintain the same structure and functionality when rewriting this code in C.
(def data [12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 146 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116]) (defn calc-stem [number] (int (Math/floor (/ number 10)))) (defn calc-leaf [number] (mod number 10)) (defn new-plant "Returns a leafless plant, with `size` empty branches, i.e. a hash-map with integer keys (from 0 to `size` inclusive) mapped to empty vectors. (new-plant 2)  [size] (let [end (inc size)] (->> (repeat end []) (interleave (range end)) (apply hash-map)))) (defn sprout-leaves [plant [stem leaf]] (update plant stem conj leaf)) (defn stem-and-leaf [numbers] (let [max-stem (calc-stem (reduce max numbers)) baby-plant (new-plant max-stem) plant (->> (map (juxt calc-stem calc-leaf) numbers) (reduce sprout-leaves baby-plant) (sort))] (doseq [[stem leaves] plant] (print (format (str "%2s") stem)) (print " | ") (println (clojure.string/join " " (sort leaves)))))) (stem-and-leaf data)
#include <stdio.h> #include <stdlib.h> int icmp(const void *a, const void *b) { return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*)b; } void leaf_plot(int *x, int len) { int i, j, d; qsort(x, len, sizeof(int), icmp); i = x[0] / 10 - 1; for (j = 0; j < len; j++) { d = x[j] / 10; while (d > i) printf("%s%3d |", j ? "\n" : "", ++i); printf(" %d", x[j] % 10); } } int main() { int data[] = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; leaf_plot(data, sizeof(data)/sizeof(data[0])); return 0; }
Write a version of this Clojure function in C# with identical behavior.
(def data [12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 146 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116]) (defn calc-stem [number] (int (Math/floor (/ number 10)))) (defn calc-leaf [number] (mod number 10)) (defn new-plant "Returns a leafless plant, with `size` empty branches, i.e. a hash-map with integer keys (from 0 to `size` inclusive) mapped to empty vectors. (new-plant 2)  [size] (let [end (inc size)] (->> (repeat end []) (interleave (range end)) (apply hash-map)))) (defn sprout-leaves [plant [stem leaf]] (update plant stem conj leaf)) (defn stem-and-leaf [numbers] (let [max-stem (calc-stem (reduce max numbers)) baby-plant (new-plant max-stem) plant (->> (map (juxt calc-stem calc-leaf) numbers) (reduce sprout-leaves baby-plant) (sort))] (doseq [[stem leaves] plant] (print (format (str "%2s") stem)) (print " | ") (println (clojure.string/join " " (sort leaves)))))) (stem-and-leaf data)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { const string data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " + "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 " + "105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 " + "114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 " + "115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 " + "105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 " + "133 45 120 30 127 31 116 146"; int[] ints = data.Split(' ').Select(int.Parse).ToArray(); StemAndLeafPlot(ints); Console.ReadKey(); } public static void StemAndLeafPlot(int[] arr) { int stemMax = arr.Max() / 10; int stemMin = arr.Min() / 10; Array.Sort(arr); for (int i = stemMin; i <= stemMax; i++) { Console.Write("{0,3} | ", i); foreach (var t in arr) { if (t < 10 * i) continue; if (t >= 10 * (i + 1)) break; Console.Write("{0} ", t % 10); } Console.WriteLine(""); } } }
Port the following code from Clojure to C++ with equivalent syntax and logic.
(def data [12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 146 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116]) (defn calc-stem [number] (int (Math/floor (/ number 10)))) (defn calc-leaf [number] (mod number 10)) (defn new-plant "Returns a leafless plant, with `size` empty branches, i.e. a hash-map with integer keys (from 0 to `size` inclusive) mapped to empty vectors. (new-plant 2)  [size] (let [end (inc size)] (->> (repeat end []) (interleave (range end)) (apply hash-map)))) (defn sprout-leaves [plant [stem leaf]] (update plant stem conj leaf)) (defn stem-and-leaf [numbers] (let [max-stem (calc-stem (reduce max numbers)) baby-plant (new-plant max-stem) plant (->> (map (juxt calc-stem calc-leaf) numbers) (reduce sprout-leaves baby-plant) (sort))] (doseq [[stem leaves] plant] (print (format (str "%2s") stem)) (print " | ") (println (clojure.string/join " " (sort leaves)))))) (stem-and-leaf data)
#include <algorithm> #include <iomanip> #include <iostream> #include <vector> const int dataset[] = { 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115,105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125, 32, 61, 37,127, 29,113, 121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116, 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117, 116,111, 40,119, 47,105, 57,122,109,124,115, 43,120, 43, 27, 27, 18, 28, 48,125,107,114, 34,133, 45,120, 30,127, 31,116,146 }; const int datasize = sizeof(dataset) / sizeof(dataset[0]); int main() { typedef std::pair<int,int> StemLeaf; std::vector<StemLeaf> stemplot; for (int i = 0; i < datasize; ++i) { stemplot.push_back(StemLeaf(dataset[i] / 10, dataset[i] % 10)); } std::sort(stemplot.begin(), stemplot.end()); int lo = stemplot.front().first; int hi = stemplot.back().first; for (std::vector<StemLeaf>::iterator itr = stemplot.begin(); lo <= hi; ++lo) { std::cout << std::setw(2) << lo << " |"; for ( ; itr != stemplot.end() && itr->first == lo; ++itr) { std::cout << " " << itr->second; } std::cout << std::endl; } }
Port the following code from Clojure to Java with equivalent syntax and logic.
(def data [12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 146 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116]) (defn calc-stem [number] (int (Math/floor (/ number 10)))) (defn calc-leaf [number] (mod number 10)) (defn new-plant "Returns a leafless plant, with `size` empty branches, i.e. a hash-map with integer keys (from 0 to `size` inclusive) mapped to empty vectors. (new-plant 2)  [size] (let [end (inc size)] (->> (repeat end []) (interleave (range end)) (apply hash-map)))) (defn sprout-leaves [plant [stem leaf]] (update plant stem conj leaf)) (defn stem-and-leaf [numbers] (let [max-stem (calc-stem (reduce max numbers)) baby-plant (new-plant max-stem) plant (->> (map (juxt calc-stem calc-leaf) numbers) (reduce sprout-leaves baby-plant) (sort))] (doseq [[stem leaves] plant] (print (format (str "%2s") stem)) (print " | ") (println (clojure.string/join " " (sort leaves)))))) (stem-and-leaf data)
import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class StemAndLeaf { private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; public static Map<Integer, List<Integer>> createPlot(int... data){ Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>(); int highestStem = -1; for(int datum:data){ int leaf = datum % 10; int stem = datum / 10; if(stem > highestStem){ highestStem = stem; } if(plot.containsKey(stem)){ plot.get(stem).add(leaf); }else{ LinkedList<Integer> list = new LinkedList<Integer>(); list.add(leaf); plot.put(stem, list); } } if(plot.keySet().size() < highestStem + 1 ){ for(int i = 0; i <= highestStem; i++){ if(!plot.containsKey(i)){ LinkedList<Integer> list = new LinkedList<Integer>(); plot.put(i, list); } } } return plot; } public static void printPlot(Map<Integer, List<Integer>> plot){ for(Map.Entry<Integer, List<Integer>> line : plot.entrySet()){ Collections.sort(line.getValue()); System.out.println(line.getKey() + " | " + line.getValue()); } } public static void main(String[] args){ Map<Integer, List<Integer>> plot = createPlot(data); printPlot(plot); } }
Convert the following code from Clojure to Python, ensuring the logic remains intact.
(def data [12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 146 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116]) (defn calc-stem [number] (int (Math/floor (/ number 10)))) (defn calc-leaf [number] (mod number 10)) (defn new-plant "Returns a leafless plant, with `size` empty branches, i.e. a hash-map with integer keys (from 0 to `size` inclusive) mapped to empty vectors. (new-plant 2)  [size] (let [end (inc size)] (->> (repeat end []) (interleave (range end)) (apply hash-map)))) (defn sprout-leaves [plant [stem leaf]] (update plant stem conj leaf)) (defn stem-and-leaf [numbers] (let [max-stem (calc-stem (reduce max numbers)) baby-plant (new-plant max-stem) plant (->> (map (juxt calc-stem calc-leaf) numbers) (reduce sprout-leaves baby-plant) (sort))] (doseq [[stem leaves] plant] (print (format (str "%2s") stem)) (print " | ") (println (clojure.string/join " " (sort leaves)))))) (stem-and-leaf data)
from collections import namedtuple from pprint import pprint as pp from math import floor Stem = namedtuple('Stem', 'data, leafdigits') data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146), 1.0) def stemplot(stem): d = [] interval = int(10**int(stem.leafdigits)) for data in sorted(stem.data): data = int(floor(data)) stm, lf = divmod(data,interval) d.append( (int(stm), int(lf)) ) stems, leafs = list(zip(*d)) stemwidth = max(len(str(x)) for x in stems) leafwidth = max(len(str(x)) for x in leafs) laststem, out = min(stems) - 1, [] for s,l in d: while laststem < s: laststem += 1 out.append('\n%*i |' % ( stemwidth, laststem)) out.append(' %0*i' % (leafwidth, l)) out.append('\n\nKey:\n Stem multiplier: %i\n X | Y => %i*X+Y\n' % (interval, interval)) return ''.join(out) if __name__ == '__main__': print( stemplot(data0) )
Translate the given Clojure code snippet into Go without altering its behavior.
(def data [12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 146 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116]) (defn calc-stem [number] (int (Math/floor (/ number 10)))) (defn calc-leaf [number] (mod number 10)) (defn new-plant "Returns a leafless plant, with `size` empty branches, i.e. a hash-map with integer keys (from 0 to `size` inclusive) mapped to empty vectors. (new-plant 2)  [size] (let [end (inc size)] (->> (repeat end []) (interleave (range end)) (apply hash-map)))) (defn sprout-leaves [plant [stem leaf]] (update plant stem conj leaf)) (defn stem-and-leaf [numbers] (let [max-stem (calc-stem (reduce max numbers)) baby-plant (new-plant max-stem) plant (->> (map (juxt calc-stem calc-leaf) numbers) (reduce sprout-leaves baby-plant) (sort))] (doseq [[stem leaves] plant] (print (format (str "%2s") stem)) (print " | ") (println (clojure.string/join " " (sort leaves)))))) (stem-and-leaf data)
package main import ( "fmt" "sort" "strconv" "strings" ) var data = `12 127 28 42` func main() { m := make(map[int][]string) for _, s := range strings.Fields(data) { if len(s) == 1 { m[0] = append(m[0], s) } else if i, err := strconv.Atoi(s[:len(s)-1]); err == nil { m[i] = append(m[i], s[len(s)-1:]) } else { panic("non numeric data") } } s := make([]int, len(m)) var i int for k := range m { s[i] = k i++ } sort.Ints(s) for k := s[0]; ; k++ { v := m[k] sort.Strings(v) fmt.Printf("%2d | %s\n", k, strings.Join(v, " ")) if k == s[len(s)-1] { break } } }
Produce a functionally identical C code for the snippet given in Common_Lisp.
(defun insert (x xs) (cond ((endp xs) (list x)) ((> x (first xs)) (cons (first xs) (insert x (rest xs)))) (t (cons x xs)))) (defun isort (xs) (if (endp xs) nil (insert (first xs) (isort (rest xs))))) (defun stem-and-leaf-bins (xs bin curr) (cond ((endp xs) (list curr)) ((= (floor (first xs) 10) bin) (stem-and-leaf-bins (rest xs) bin (cons (first xs) curr))) (t (cons curr (stem-and-leaf-bins (rest xs) (floor (first xs) 10) (list (first xs))))))) (defun print-bin (bin) (if (endp bin) nil (progn$ (cw " ~x0" (mod (first bin) 10)) (print-bin (rest bin))))) (defun stem-and-leaf-plot-r (bins) (if (or (endp bins) (endp (first bins))) nil (progn$ (cw "~x0 |" (floor (first (first bins)) 10)) (print-bin (first bins)) (cw "~%") (stem-and-leaf-plot-r (rest bins))))) (defun stem-and-leaf-plot (xs) (stem-and-leaf-plot-r (reverse (stem-and-leaf-bins (reverse (isort xs)) 0 nil))))
#include <stdio.h> #include <stdlib.h> int icmp(const void *a, const void *b) { return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*)b; } void leaf_plot(int *x, int len) { int i, j, d; qsort(x, len, sizeof(int), icmp); i = x[0] / 10 - 1; for (j = 0; j < len; j++) { d = x[j] / 10; while (d > i) printf("%s%3d |", j ? "\n" : "", ++i); printf(" %d", x[j] % 10); } } int main() { int data[] = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; leaf_plot(data, sizeof(data)/sizeof(data[0])); return 0; }
Write the same algorithm in C# as shown in this Common_Lisp implementation.
(defun insert (x xs) (cond ((endp xs) (list x)) ((> x (first xs)) (cons (first xs) (insert x (rest xs)))) (t (cons x xs)))) (defun isort (xs) (if (endp xs) nil (insert (first xs) (isort (rest xs))))) (defun stem-and-leaf-bins (xs bin curr) (cond ((endp xs) (list curr)) ((= (floor (first xs) 10) bin) (stem-and-leaf-bins (rest xs) bin (cons (first xs) curr))) (t (cons curr (stem-and-leaf-bins (rest xs) (floor (first xs) 10) (list (first xs))))))) (defun print-bin (bin) (if (endp bin) nil (progn$ (cw " ~x0" (mod (first bin) 10)) (print-bin (rest bin))))) (defun stem-and-leaf-plot-r (bins) (if (or (endp bins) (endp (first bins))) nil (progn$ (cw "~x0 |" (floor (first (first bins)) 10)) (print-bin (first bins)) (cw "~%") (stem-and-leaf-plot-r (rest bins))))) (defun stem-and-leaf-plot (xs) (stem-and-leaf-plot-r (reverse (stem-and-leaf-bins (reverse (isort xs)) 0 nil))))
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { const string data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " + "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 " + "105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 " + "114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 " + "115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 " + "105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 " + "133 45 120 30 127 31 116 146"; int[] ints = data.Split(' ').Select(int.Parse).ToArray(); StemAndLeafPlot(ints); Console.ReadKey(); } public static void StemAndLeafPlot(int[] arr) { int stemMax = arr.Max() / 10; int stemMin = arr.Min() / 10; Array.Sort(arr); for (int i = stemMin; i <= stemMax; i++) { Console.Write("{0,3} | ", i); foreach (var t in arr) { if (t < 10 * i) continue; if (t >= 10 * (i + 1)) break; Console.Write("{0} ", t % 10); } Console.WriteLine(""); } } }
Can you help me rewrite this code in C++ instead of Common_Lisp, keeping it the same logically?
(defun insert (x xs) (cond ((endp xs) (list x)) ((> x (first xs)) (cons (first xs) (insert x (rest xs)))) (t (cons x xs)))) (defun isort (xs) (if (endp xs) nil (insert (first xs) (isort (rest xs))))) (defun stem-and-leaf-bins (xs bin curr) (cond ((endp xs) (list curr)) ((= (floor (first xs) 10) bin) (stem-and-leaf-bins (rest xs) bin (cons (first xs) curr))) (t (cons curr (stem-and-leaf-bins (rest xs) (floor (first xs) 10) (list (first xs))))))) (defun print-bin (bin) (if (endp bin) nil (progn$ (cw " ~x0" (mod (first bin) 10)) (print-bin (rest bin))))) (defun stem-and-leaf-plot-r (bins) (if (or (endp bins) (endp (first bins))) nil (progn$ (cw "~x0 |" (floor (first (first bins)) 10)) (print-bin (first bins)) (cw "~%") (stem-and-leaf-plot-r (rest bins))))) (defun stem-and-leaf-plot (xs) (stem-and-leaf-plot-r (reverse (stem-and-leaf-bins (reverse (isort xs)) 0 nil))))
#include <algorithm> #include <iomanip> #include <iostream> #include <vector> const int dataset[] = { 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115,105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125, 32, 61, 37,127, 29,113, 121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116, 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117, 116,111, 40,119, 47,105, 57,122,109,124,115, 43,120, 43, 27, 27, 18, 28, 48,125,107,114, 34,133, 45,120, 30,127, 31,116,146 }; const int datasize = sizeof(dataset) / sizeof(dataset[0]); int main() { typedef std::pair<int,int> StemLeaf; std::vector<StemLeaf> stemplot; for (int i = 0; i < datasize; ++i) { stemplot.push_back(StemLeaf(dataset[i] / 10, dataset[i] % 10)); } std::sort(stemplot.begin(), stemplot.end()); int lo = stemplot.front().first; int hi = stemplot.back().first; for (std::vector<StemLeaf>::iterator itr = stemplot.begin(); lo <= hi; ++lo) { std::cout << std::setw(2) << lo << " |"; for ( ; itr != stemplot.end() && itr->first == lo; ++itr) { std::cout << " " << itr->second; } std::cout << std::endl; } }
Maintain the same structure and functionality when rewriting this code in Java.
(defun insert (x xs) (cond ((endp xs) (list x)) ((> x (first xs)) (cons (first xs) (insert x (rest xs)))) (t (cons x xs)))) (defun isort (xs) (if (endp xs) nil (insert (first xs) (isort (rest xs))))) (defun stem-and-leaf-bins (xs bin curr) (cond ((endp xs) (list curr)) ((= (floor (first xs) 10) bin) (stem-and-leaf-bins (rest xs) bin (cons (first xs) curr))) (t (cons curr (stem-and-leaf-bins (rest xs) (floor (first xs) 10) (list (first xs))))))) (defun print-bin (bin) (if (endp bin) nil (progn$ (cw " ~x0" (mod (first bin) 10)) (print-bin (rest bin))))) (defun stem-and-leaf-plot-r (bins) (if (or (endp bins) (endp (first bins))) nil (progn$ (cw "~x0 |" (floor (first (first bins)) 10)) (print-bin (first bins)) (cw "~%") (stem-and-leaf-plot-r (rest bins))))) (defun stem-and-leaf-plot (xs) (stem-and-leaf-plot-r (reverse (stem-and-leaf-bins (reverse (isort xs)) 0 nil))))
import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class StemAndLeaf { private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; public static Map<Integer, List<Integer>> createPlot(int... data){ Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>(); int highestStem = -1; for(int datum:data){ int leaf = datum % 10; int stem = datum / 10; if(stem > highestStem){ highestStem = stem; } if(plot.containsKey(stem)){ plot.get(stem).add(leaf); }else{ LinkedList<Integer> list = new LinkedList<Integer>(); list.add(leaf); plot.put(stem, list); } } if(plot.keySet().size() < highestStem + 1 ){ for(int i = 0; i <= highestStem; i++){ if(!plot.containsKey(i)){ LinkedList<Integer> list = new LinkedList<Integer>(); plot.put(i, list); } } } return plot; } public static void printPlot(Map<Integer, List<Integer>> plot){ for(Map.Entry<Integer, List<Integer>> line : plot.entrySet()){ Collections.sort(line.getValue()); System.out.println(line.getKey() + " | " + line.getValue()); } } public static void main(String[] args){ Map<Integer, List<Integer>> plot = createPlot(data); printPlot(plot); } }
Ensure the translated Python code behaves exactly like the original Common_Lisp snippet.
(defun insert (x xs) (cond ((endp xs) (list x)) ((> x (first xs)) (cons (first xs) (insert x (rest xs)))) (t (cons x xs)))) (defun isort (xs) (if (endp xs) nil (insert (first xs) (isort (rest xs))))) (defun stem-and-leaf-bins (xs bin curr) (cond ((endp xs) (list curr)) ((= (floor (first xs) 10) bin) (stem-and-leaf-bins (rest xs) bin (cons (first xs) curr))) (t (cons curr (stem-and-leaf-bins (rest xs) (floor (first xs) 10) (list (first xs))))))) (defun print-bin (bin) (if (endp bin) nil (progn$ (cw " ~x0" (mod (first bin) 10)) (print-bin (rest bin))))) (defun stem-and-leaf-plot-r (bins) (if (or (endp bins) (endp (first bins))) nil (progn$ (cw "~x0 |" (floor (first (first bins)) 10)) (print-bin (first bins)) (cw "~%") (stem-and-leaf-plot-r (rest bins))))) (defun stem-and-leaf-plot (xs) (stem-and-leaf-plot-r (reverse (stem-and-leaf-bins (reverse (isort xs)) 0 nil))))
from collections import namedtuple from pprint import pprint as pp from math import floor Stem = namedtuple('Stem', 'data, leafdigits') data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146), 1.0) def stemplot(stem): d = [] interval = int(10**int(stem.leafdigits)) for data in sorted(stem.data): data = int(floor(data)) stm, lf = divmod(data,interval) d.append( (int(stm), int(lf)) ) stems, leafs = list(zip(*d)) stemwidth = max(len(str(x)) for x in stems) leafwidth = max(len(str(x)) for x in leafs) laststem, out = min(stems) - 1, [] for s,l in d: while laststem < s: laststem += 1 out.append('\n%*i |' % ( stemwidth, laststem)) out.append(' %0*i' % (leafwidth, l)) out.append('\n\nKey:\n Stem multiplier: %i\n X | Y => %i*X+Y\n' % (interval, interval)) return ''.join(out) if __name__ == '__main__': print( stemplot(data0) )
Write the same code in C as shown below in D.
import std.stdio, std.algorithm; void main() { enum data = [12,127,28,42,39,113,42,18,44,118,44,37,113,124,37,48, 127,36,29,31,125,139,131,115,105,132,104,123,35,113,122,42,117, 119,58,109,23,105,63,27,44,105,99,41,128,121,116,125,32,61,37, 127,29,113,121,58,114,126,53,114,96,25,109,7,31,141,46,13,27, 43,117,116,27,7,68,40,31,115,124,42,128,52,71,118,117,38,27, 106,33,117,116,111,40,119,47,105,57,122,109,124,115,43,120,43, 27,27,18,28,48,125,107,114,34,133,45,120,30,127,31,116,146]; int[][int] histo; foreach (x; data) histo[x / 10] ~= x % 10; immutable loHi = data.reduce!(min, max); foreach (i; loHi[0]/10 .. loHi[1]/10 + 1) writefln("%2d | %(%d %) ", i, histo.get(i, []).sort()); }
#include <stdio.h> #include <stdlib.h> int icmp(const void *a, const void *b) { return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*)b; } void leaf_plot(int *x, int len) { int i, j, d; qsort(x, len, sizeof(int), icmp); i = x[0] / 10 - 1; for (j = 0; j < len; j++) { d = x[j] / 10; while (d > i) printf("%s%3d |", j ? "\n" : "", ++i); printf(" %d", x[j] % 10); } } int main() { int data[] = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; leaf_plot(data, sizeof(data)/sizeof(data[0])); return 0; }
Convert the following code from D to C#, ensuring the logic remains intact.
import std.stdio, std.algorithm; void main() { enum data = [12,127,28,42,39,113,42,18,44,118,44,37,113,124,37,48, 127,36,29,31,125,139,131,115,105,132,104,123,35,113,122,42,117, 119,58,109,23,105,63,27,44,105,99,41,128,121,116,125,32,61,37, 127,29,113,121,58,114,126,53,114,96,25,109,7,31,141,46,13,27, 43,117,116,27,7,68,40,31,115,124,42,128,52,71,118,117,38,27, 106,33,117,116,111,40,119,47,105,57,122,109,124,115,43,120,43, 27,27,18,28,48,125,107,114,34,133,45,120,30,127,31,116,146]; int[][int] histo; foreach (x; data) histo[x / 10] ~= x % 10; immutable loHi = data.reduce!(min, max); foreach (i; loHi[0]/10 .. loHi[1]/10 + 1) writefln("%2d | %(%d %) ", i, histo.get(i, []).sort()); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { const string data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " + "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 " + "105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 " + "114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 " + "115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 " + "105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 " + "133 45 120 30 127 31 116 146"; int[] ints = data.Split(' ').Select(int.Parse).ToArray(); StemAndLeafPlot(ints); Console.ReadKey(); } public static void StemAndLeafPlot(int[] arr) { int stemMax = arr.Max() / 10; int stemMin = arr.Min() / 10; Array.Sort(arr); for (int i = stemMin; i <= stemMax; i++) { Console.Write("{0,3} | ", i); foreach (var t in arr) { if (t < 10 * i) continue; if (t >= 10 * (i + 1)) break; Console.Write("{0} ", t % 10); } Console.WriteLine(""); } } }
Change the following D code into C++ without altering its purpose.
import std.stdio, std.algorithm; void main() { enum data = [12,127,28,42,39,113,42,18,44,118,44,37,113,124,37,48, 127,36,29,31,125,139,131,115,105,132,104,123,35,113,122,42,117, 119,58,109,23,105,63,27,44,105,99,41,128,121,116,125,32,61,37, 127,29,113,121,58,114,126,53,114,96,25,109,7,31,141,46,13,27, 43,117,116,27,7,68,40,31,115,124,42,128,52,71,118,117,38,27, 106,33,117,116,111,40,119,47,105,57,122,109,124,115,43,120,43, 27,27,18,28,48,125,107,114,34,133,45,120,30,127,31,116,146]; int[][int] histo; foreach (x; data) histo[x / 10] ~= x % 10; immutable loHi = data.reduce!(min, max); foreach (i; loHi[0]/10 .. loHi[1]/10 + 1) writefln("%2d | %(%d %) ", i, histo.get(i, []).sort()); }
#include <algorithm> #include <iomanip> #include <iostream> #include <vector> const int dataset[] = { 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115,105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125, 32, 61, 37,127, 29,113, 121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116, 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117, 116,111, 40,119, 47,105, 57,122,109,124,115, 43,120, 43, 27, 27, 18, 28, 48,125,107,114, 34,133, 45,120, 30,127, 31,116,146 }; const int datasize = sizeof(dataset) / sizeof(dataset[0]); int main() { typedef std::pair<int,int> StemLeaf; std::vector<StemLeaf> stemplot; for (int i = 0; i < datasize; ++i) { stemplot.push_back(StemLeaf(dataset[i] / 10, dataset[i] % 10)); } std::sort(stemplot.begin(), stemplot.end()); int lo = stemplot.front().first; int hi = stemplot.back().first; for (std::vector<StemLeaf>::iterator itr = stemplot.begin(); lo <= hi; ++lo) { std::cout << std::setw(2) << lo << " |"; for ( ; itr != stemplot.end() && itr->first == lo; ++itr) { std::cout << " " << itr->second; } std::cout << std::endl; } }
Translate the given D code snippet into Java without altering its behavior.
import std.stdio, std.algorithm; void main() { enum data = [12,127,28,42,39,113,42,18,44,118,44,37,113,124,37,48, 127,36,29,31,125,139,131,115,105,132,104,123,35,113,122,42,117, 119,58,109,23,105,63,27,44,105,99,41,128,121,116,125,32,61,37, 127,29,113,121,58,114,126,53,114,96,25,109,7,31,141,46,13,27, 43,117,116,27,7,68,40,31,115,124,42,128,52,71,118,117,38,27, 106,33,117,116,111,40,119,47,105,57,122,109,124,115,43,120,43, 27,27,18,28,48,125,107,114,34,133,45,120,30,127,31,116,146]; int[][int] histo; foreach (x; data) histo[x / 10] ~= x % 10; immutable loHi = data.reduce!(min, max); foreach (i; loHi[0]/10 .. loHi[1]/10 + 1) writefln("%2d | %(%d %) ", i, histo.get(i, []).sort()); }
import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class StemAndLeaf { private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; public static Map<Integer, List<Integer>> createPlot(int... data){ Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>(); int highestStem = -1; for(int datum:data){ int leaf = datum % 10; int stem = datum / 10; if(stem > highestStem){ highestStem = stem; } if(plot.containsKey(stem)){ plot.get(stem).add(leaf); }else{ LinkedList<Integer> list = new LinkedList<Integer>(); list.add(leaf); plot.put(stem, list); } } if(plot.keySet().size() < highestStem + 1 ){ for(int i = 0; i <= highestStem; i++){ if(!plot.containsKey(i)){ LinkedList<Integer> list = new LinkedList<Integer>(); plot.put(i, list); } } } return plot; } public static void printPlot(Map<Integer, List<Integer>> plot){ for(Map.Entry<Integer, List<Integer>> line : plot.entrySet()){ Collections.sort(line.getValue()); System.out.println(line.getKey() + " | " + line.getValue()); } } public static void main(String[] args){ Map<Integer, List<Integer>> plot = createPlot(data); printPlot(plot); } }
Can you help me rewrite this code in Python instead of D, keeping it the same logically?
import std.stdio, std.algorithm; void main() { enum data = [12,127,28,42,39,113,42,18,44,118,44,37,113,124,37,48, 127,36,29,31,125,139,131,115,105,132,104,123,35,113,122,42,117, 119,58,109,23,105,63,27,44,105,99,41,128,121,116,125,32,61,37, 127,29,113,121,58,114,126,53,114,96,25,109,7,31,141,46,13,27, 43,117,116,27,7,68,40,31,115,124,42,128,52,71,118,117,38,27, 106,33,117,116,111,40,119,47,105,57,122,109,124,115,43,120,43, 27,27,18,28,48,125,107,114,34,133,45,120,30,127,31,116,146]; int[][int] histo; foreach (x; data) histo[x / 10] ~= x % 10; immutable loHi = data.reduce!(min, max); foreach (i; loHi[0]/10 .. loHi[1]/10 + 1) writefln("%2d | %(%d %) ", i, histo.get(i, []).sort()); }
from collections import namedtuple from pprint import pprint as pp from math import floor Stem = namedtuple('Stem', 'data, leafdigits') data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146), 1.0) def stemplot(stem): d = [] interval = int(10**int(stem.leafdigits)) for data in sorted(stem.data): data = int(floor(data)) stm, lf = divmod(data,interval) d.append( (int(stm), int(lf)) ) stems, leafs = list(zip(*d)) stemwidth = max(len(str(x)) for x in stems) leafwidth = max(len(str(x)) for x in leafs) laststem, out = min(stems) - 1, [] for s,l in d: while laststem < s: laststem += 1 out.append('\n%*i |' % ( stemwidth, laststem)) out.append(' %0*i' % (leafwidth, l)) out.append('\n\nKey:\n Stem multiplier: %i\n X | Y => %i*X+Y\n' % (interval, interval)) return ''.join(out) if __name__ == '__main__': print( stemplot(data0) )
Generate an equivalent Go version of this D code.
import std.stdio, std.algorithm; void main() { enum data = [12,127,28,42,39,113,42,18,44,118,44,37,113,124,37,48, 127,36,29,31,125,139,131,115,105,132,104,123,35,113,122,42,117, 119,58,109,23,105,63,27,44,105,99,41,128,121,116,125,32,61,37, 127,29,113,121,58,114,126,53,114,96,25,109,7,31,141,46,13,27, 43,117,116,27,7,68,40,31,115,124,42,128,52,71,118,117,38,27, 106,33,117,116,111,40,119,47,105,57,122,109,124,115,43,120,43, 27,27,18,28,48,125,107,114,34,133,45,120,30,127,31,116,146]; int[][int] histo; foreach (x; data) histo[x / 10] ~= x % 10; immutable loHi = data.reduce!(min, max); foreach (i; loHi[0]/10 .. loHi[1]/10 + 1) writefln("%2d | %(%d %) ", i, histo.get(i, []).sort()); }
package main import ( "fmt" "sort" "strconv" "strings" ) var data = `12 127 28 42` func main() { m := make(map[int][]string) for _, s := range strings.Fields(data) { if len(s) == 1 { m[0] = append(m[0], s) } else if i, err := strconv.Atoi(s[:len(s)-1]); err == nil { m[i] = append(m[i], s[len(s)-1:]) } else { panic("non numeric data") } } s := make([]int, len(m)) var i int for k := range m { s[i] = k i++ } sort.Ints(s) for k := s[0]; ; k++ { v := m[k] sort.Strings(v) fmt.Printf("%2d | %s\n", k, strings.Join(v, " ")) if k == s[len(s)-1] { break } } }
Convert this Elixir block to C, preserving its control flow and logic.
defmodule Stem_and_leaf do def plot(data, leaf_digits\\1) do multiplier = Enum.reduce(1..leaf_digits, 1, fn _,acc -> acc*10 end) Enum.group_by(data, fn x -> div(x, multiplier) end) |> Map.new(fn {k,v} -> {k, Enum.map(v, &rem(&1, multiplier)) |> Enum.sort} end) |> print(leaf_digits) end defp print(plot_data, leaf_digits) do {min, max} = Map.keys(plot_data) |> Enum.min_max stem_width = length(to_charlist(max)) fmt = "~ Enum.each(min..max, fn stem -> leaves = Enum.map_join(Map.get(plot_data, stem, []), " ", fn leaf -> to_string(leaf) |> String.pad_leading(leaf_digits) end) :io.format fmt, [stem, leaves] end) end end data = ~w(12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146) |> Enum.map(&String.to_integer(&1)) Stem_and_leaf.plot(data)
#include <stdio.h> #include <stdlib.h> int icmp(const void *a, const void *b) { return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*)b; } void leaf_plot(int *x, int len) { int i, j, d; qsort(x, len, sizeof(int), icmp); i = x[0] / 10 - 1; for (j = 0; j < len; j++) { d = x[j] / 10; while (d > i) printf("%s%3d |", j ? "\n" : "", ++i); printf(" %d", x[j] % 10); } } int main() { int data[] = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; leaf_plot(data, sizeof(data)/sizeof(data[0])); return 0; }
Produce a language-to-language conversion: from Elixir to C++, same semantics.
defmodule Stem_and_leaf do def plot(data, leaf_digits\\1) do multiplier = Enum.reduce(1..leaf_digits, 1, fn _,acc -> acc*10 end) Enum.group_by(data, fn x -> div(x, multiplier) end) |> Map.new(fn {k,v} -> {k, Enum.map(v, &rem(&1, multiplier)) |> Enum.sort} end) |> print(leaf_digits) end defp print(plot_data, leaf_digits) do {min, max} = Map.keys(plot_data) |> Enum.min_max stem_width = length(to_charlist(max)) fmt = "~ Enum.each(min..max, fn stem -> leaves = Enum.map_join(Map.get(plot_data, stem, []), " ", fn leaf -> to_string(leaf) |> String.pad_leading(leaf_digits) end) :io.format fmt, [stem, leaves] end) end end data = ~w(12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146) |> Enum.map(&String.to_integer(&1)) Stem_and_leaf.plot(data)
#include <algorithm> #include <iomanip> #include <iostream> #include <vector> const int dataset[] = { 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115,105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125, 32, 61, 37,127, 29,113, 121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116, 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117, 116,111, 40,119, 47,105, 57,122,109,124,115, 43,120, 43, 27, 27, 18, 28, 48,125,107,114, 34,133, 45,120, 30,127, 31,116,146 }; const int datasize = sizeof(dataset) / sizeof(dataset[0]); int main() { typedef std::pair<int,int> StemLeaf; std::vector<StemLeaf> stemplot; for (int i = 0; i < datasize; ++i) { stemplot.push_back(StemLeaf(dataset[i] / 10, dataset[i] % 10)); } std::sort(stemplot.begin(), stemplot.end()); int lo = stemplot.front().first; int hi = stemplot.back().first; for (std::vector<StemLeaf>::iterator itr = stemplot.begin(); lo <= hi; ++lo) { std::cout << std::setw(2) << lo << " |"; for ( ; itr != stemplot.end() && itr->first == lo; ++itr) { std::cout << " " << itr->second; } std::cout << std::endl; } }
Produce a language-to-language conversion: from Elixir to Java, same semantics.
defmodule Stem_and_leaf do def plot(data, leaf_digits\\1) do multiplier = Enum.reduce(1..leaf_digits, 1, fn _,acc -> acc*10 end) Enum.group_by(data, fn x -> div(x, multiplier) end) |> Map.new(fn {k,v} -> {k, Enum.map(v, &rem(&1, multiplier)) |> Enum.sort} end) |> print(leaf_digits) end defp print(plot_data, leaf_digits) do {min, max} = Map.keys(plot_data) |> Enum.min_max stem_width = length(to_charlist(max)) fmt = "~ Enum.each(min..max, fn stem -> leaves = Enum.map_join(Map.get(plot_data, stem, []), " ", fn leaf -> to_string(leaf) |> String.pad_leading(leaf_digits) end) :io.format fmt, [stem, leaves] end) end end data = ~w(12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146) |> Enum.map(&String.to_integer(&1)) Stem_and_leaf.plot(data)
import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class StemAndLeaf { private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; public static Map<Integer, List<Integer>> createPlot(int... data){ Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>(); int highestStem = -1; for(int datum:data){ int leaf = datum % 10; int stem = datum / 10; if(stem > highestStem){ highestStem = stem; } if(plot.containsKey(stem)){ plot.get(stem).add(leaf); }else{ LinkedList<Integer> list = new LinkedList<Integer>(); list.add(leaf); plot.put(stem, list); } } if(plot.keySet().size() < highestStem + 1 ){ for(int i = 0; i <= highestStem; i++){ if(!plot.containsKey(i)){ LinkedList<Integer> list = new LinkedList<Integer>(); plot.put(i, list); } } } return plot; } public static void printPlot(Map<Integer, List<Integer>> plot){ for(Map.Entry<Integer, List<Integer>> line : plot.entrySet()){ Collections.sort(line.getValue()); System.out.println(line.getKey() + " | " + line.getValue()); } } public static void main(String[] args){ Map<Integer, List<Integer>> plot = createPlot(data); printPlot(plot); } }
Preserve the algorithm and functionality while converting the code from Elixir to Python.
defmodule Stem_and_leaf do def plot(data, leaf_digits\\1) do multiplier = Enum.reduce(1..leaf_digits, 1, fn _,acc -> acc*10 end) Enum.group_by(data, fn x -> div(x, multiplier) end) |> Map.new(fn {k,v} -> {k, Enum.map(v, &rem(&1, multiplier)) |> Enum.sort} end) |> print(leaf_digits) end defp print(plot_data, leaf_digits) do {min, max} = Map.keys(plot_data) |> Enum.min_max stem_width = length(to_charlist(max)) fmt = "~ Enum.each(min..max, fn stem -> leaves = Enum.map_join(Map.get(plot_data, stem, []), " ", fn leaf -> to_string(leaf) |> String.pad_leading(leaf_digits) end) :io.format fmt, [stem, leaves] end) end end data = ~w(12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146) |> Enum.map(&String.to_integer(&1)) Stem_and_leaf.plot(data)
from collections import namedtuple from pprint import pprint as pp from math import floor Stem = namedtuple('Stem', 'data, leafdigits') data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146), 1.0) def stemplot(stem): d = [] interval = int(10**int(stem.leafdigits)) for data in sorted(stem.data): data = int(floor(data)) stm, lf = divmod(data,interval) d.append( (int(stm), int(lf)) ) stems, leafs = list(zip(*d)) stemwidth = max(len(str(x)) for x in stems) leafwidth = max(len(str(x)) for x in leafs) laststem, out = min(stems) - 1, [] for s,l in d: while laststem < s: laststem += 1 out.append('\n%*i |' % ( stemwidth, laststem)) out.append(' %0*i' % (leafwidth, l)) out.append('\n\nKey:\n Stem multiplier: %i\n X | Y => %i*X+Y\n' % (interval, interval)) return ''.join(out) if __name__ == '__main__': print( stemplot(data0) )
Produce a language-to-language conversion: from Elixir to Go, same semantics.
defmodule Stem_and_leaf do def plot(data, leaf_digits\\1) do multiplier = Enum.reduce(1..leaf_digits, 1, fn _,acc -> acc*10 end) Enum.group_by(data, fn x -> div(x, multiplier) end) |> Map.new(fn {k,v} -> {k, Enum.map(v, &rem(&1, multiplier)) |> Enum.sort} end) |> print(leaf_digits) end defp print(plot_data, leaf_digits) do {min, max} = Map.keys(plot_data) |> Enum.min_max stem_width = length(to_charlist(max)) fmt = "~ Enum.each(min..max, fn stem -> leaves = Enum.map_join(Map.get(plot_data, stem, []), " ", fn leaf -> to_string(leaf) |> String.pad_leading(leaf_digits) end) :io.format fmt, [stem, leaves] end) end end data = ~w(12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146) |> Enum.map(&String.to_integer(&1)) Stem_and_leaf.plot(data)
package main import ( "fmt" "sort" "strconv" "strings" ) var data = `12 127 28 42` func main() { m := make(map[int][]string) for _, s := range strings.Fields(data) { if len(s) == 1 { m[0] = append(m[0], s) } else if i, err := strconv.Atoi(s[:len(s)-1]); err == nil { m[i] = append(m[i], s[len(s)-1:]) } else { panic("non numeric data") } } s := make([]int, len(m)) var i int for k := range m { s[i] = k i++ } sort.Ints(s) for k := s[0]; ; k++ { v := m[k] sort.Strings(v) fmt.Printf("%2d | %s\n", k, strings.Join(v, " ")) if k == s[len(s)-1] { break } } }
Translate this program into C but keep the logic exactly as in F#.
open System let data = [ 12; 127; 28; 42; 39; 113; 42; 18; 44; 118; 44; 37; 113; 124; 37; 48; 127; 36; 29; 31; 125; 139; 131; 115; 105; 132; 104; 123; 35; 113; 122; 42; 117; 119; 58; 109; 23; 105; 63; 27; 44; 105; 99; 41; 128; 121; 116; 125; 32; 61; 37; 127; 29; 113; 121; 58; 114; 126; 53; 114; 96; 25; 109; 7; 31; 141; 46; 13; 27; 43; 117; 116; 27; 7; 68; 40; 31; 115; 124; 42; 128; 52; 71; 118; 117; 38; 27; 106; 33; 117; 116; 111; 40; 119; 47; 105; 57; 122; 109; 124; 115; 43; 120; 43; 27; 27; 18; 28; 48; 125; 107; 114; 34; 133; 45; 120; 30; 127; 31; 116; 146 ] let plotStemAndLeafs items = let groupedItems = items |> Seq.sort |> Seq.map (fun i -> i / 10, i % 10) |> Seq.groupBy fst let maxStem = groupedItems |> Seq.maxBy fst |> fst let stemLeafMap = Map.ofSeq groupedItems [0..maxStem] |> List.iter (fun stm -> printf " %2d | " stm match stemLeafMap.TryFind stm with | None -> () | Some items -> items |> Seq.iter (snd >> printf "%d ") printfn "") plotStemAndLeafs data
#include <stdio.h> #include <stdlib.h> int icmp(const void *a, const void *b) { return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*)b; } void leaf_plot(int *x, int len) { int i, j, d; qsort(x, len, sizeof(int), icmp); i = x[0] / 10 - 1; for (j = 0; j < len; j++) { d = x[j] / 10; while (d > i) printf("%s%3d |", j ? "\n" : "", ++i); printf(" %d", x[j] % 10); } } int main() { int data[] = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; leaf_plot(data, sizeof(data)/sizeof(data[0])); return 0; }
Generate a C# translation of this F# snippet without changing its computational steps.
open System let data = [ 12; 127; 28; 42; 39; 113; 42; 18; 44; 118; 44; 37; 113; 124; 37; 48; 127; 36; 29; 31; 125; 139; 131; 115; 105; 132; 104; 123; 35; 113; 122; 42; 117; 119; 58; 109; 23; 105; 63; 27; 44; 105; 99; 41; 128; 121; 116; 125; 32; 61; 37; 127; 29; 113; 121; 58; 114; 126; 53; 114; 96; 25; 109; 7; 31; 141; 46; 13; 27; 43; 117; 116; 27; 7; 68; 40; 31; 115; 124; 42; 128; 52; 71; 118; 117; 38; 27; 106; 33; 117; 116; 111; 40; 119; 47; 105; 57; 122; 109; 124; 115; 43; 120; 43; 27; 27; 18; 28; 48; 125; 107; 114; 34; 133; 45; 120; 30; 127; 31; 116; 146 ] let plotStemAndLeafs items = let groupedItems = items |> Seq.sort |> Seq.map (fun i -> i / 10, i % 10) |> Seq.groupBy fst let maxStem = groupedItems |> Seq.maxBy fst |> fst let stemLeafMap = Map.ofSeq groupedItems [0..maxStem] |> List.iter (fun stm -> printf " %2d | " stm match stemLeafMap.TryFind stm with | None -> () | Some items -> items |> Seq.iter (snd >> printf "%d ") printfn "") plotStemAndLeafs data
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { const string data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " + "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 " + "105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 " + "114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 " + "115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 " + "105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 " + "133 45 120 30 127 31 116 146"; int[] ints = data.Split(' ').Select(int.Parse).ToArray(); StemAndLeafPlot(ints); Console.ReadKey(); } public static void StemAndLeafPlot(int[] arr) { int stemMax = arr.Max() / 10; int stemMin = arr.Min() / 10; Array.Sort(arr); for (int i = stemMin; i <= stemMax; i++) { Console.Write("{0,3} | ", i); foreach (var t in arr) { if (t < 10 * i) continue; if (t >= 10 * (i + 1)) break; Console.Write("{0} ", t % 10); } Console.WriteLine(""); } } }
Write the same algorithm in C++ as shown in this F# implementation.
open System let data = [ 12; 127; 28; 42; 39; 113; 42; 18; 44; 118; 44; 37; 113; 124; 37; 48; 127; 36; 29; 31; 125; 139; 131; 115; 105; 132; 104; 123; 35; 113; 122; 42; 117; 119; 58; 109; 23; 105; 63; 27; 44; 105; 99; 41; 128; 121; 116; 125; 32; 61; 37; 127; 29; 113; 121; 58; 114; 126; 53; 114; 96; 25; 109; 7; 31; 141; 46; 13; 27; 43; 117; 116; 27; 7; 68; 40; 31; 115; 124; 42; 128; 52; 71; 118; 117; 38; 27; 106; 33; 117; 116; 111; 40; 119; 47; 105; 57; 122; 109; 124; 115; 43; 120; 43; 27; 27; 18; 28; 48; 125; 107; 114; 34; 133; 45; 120; 30; 127; 31; 116; 146 ] let plotStemAndLeafs items = let groupedItems = items |> Seq.sort |> Seq.map (fun i -> i / 10, i % 10) |> Seq.groupBy fst let maxStem = groupedItems |> Seq.maxBy fst |> fst let stemLeafMap = Map.ofSeq groupedItems [0..maxStem] |> List.iter (fun stm -> printf " %2d | " stm match stemLeafMap.TryFind stm with | None -> () | Some items -> items |> Seq.iter (snd >> printf "%d ") printfn "") plotStemAndLeafs data
#include <algorithm> #include <iomanip> #include <iostream> #include <vector> const int dataset[] = { 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115,105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125, 32, 61, 37,127, 29,113, 121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116, 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117, 116,111, 40,119, 47,105, 57,122,109,124,115, 43,120, 43, 27, 27, 18, 28, 48,125,107,114, 34,133, 45,120, 30,127, 31,116,146 }; const int datasize = sizeof(dataset) / sizeof(dataset[0]); int main() { typedef std::pair<int,int> StemLeaf; std::vector<StemLeaf> stemplot; for (int i = 0; i < datasize; ++i) { stemplot.push_back(StemLeaf(dataset[i] / 10, dataset[i] % 10)); } std::sort(stemplot.begin(), stemplot.end()); int lo = stemplot.front().first; int hi = stemplot.back().first; for (std::vector<StemLeaf>::iterator itr = stemplot.begin(); lo <= hi; ++lo) { std::cout << std::setw(2) << lo << " |"; for ( ; itr != stemplot.end() && itr->first == lo; ++itr) { std::cout << " " << itr->second; } std::cout << std::endl; } }
Can you help me rewrite this code in Java instead of F#, keeping it the same logically?
open System let data = [ 12; 127; 28; 42; 39; 113; 42; 18; 44; 118; 44; 37; 113; 124; 37; 48; 127; 36; 29; 31; 125; 139; 131; 115; 105; 132; 104; 123; 35; 113; 122; 42; 117; 119; 58; 109; 23; 105; 63; 27; 44; 105; 99; 41; 128; 121; 116; 125; 32; 61; 37; 127; 29; 113; 121; 58; 114; 126; 53; 114; 96; 25; 109; 7; 31; 141; 46; 13; 27; 43; 117; 116; 27; 7; 68; 40; 31; 115; 124; 42; 128; 52; 71; 118; 117; 38; 27; 106; 33; 117; 116; 111; 40; 119; 47; 105; 57; 122; 109; 124; 115; 43; 120; 43; 27; 27; 18; 28; 48; 125; 107; 114; 34; 133; 45; 120; 30; 127; 31; 116; 146 ] let plotStemAndLeafs items = let groupedItems = items |> Seq.sort |> Seq.map (fun i -> i / 10, i % 10) |> Seq.groupBy fst let maxStem = groupedItems |> Seq.maxBy fst |> fst let stemLeafMap = Map.ofSeq groupedItems [0..maxStem] |> List.iter (fun stm -> printf " %2d | " stm match stemLeafMap.TryFind stm with | None -> () | Some items -> items |> Seq.iter (snd >> printf "%d ") printfn "") plotStemAndLeafs data
import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class StemAndLeaf { private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; public static Map<Integer, List<Integer>> createPlot(int... data){ Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>(); int highestStem = -1; for(int datum:data){ int leaf = datum % 10; int stem = datum / 10; if(stem > highestStem){ highestStem = stem; } if(plot.containsKey(stem)){ plot.get(stem).add(leaf); }else{ LinkedList<Integer> list = new LinkedList<Integer>(); list.add(leaf); plot.put(stem, list); } } if(plot.keySet().size() < highestStem + 1 ){ for(int i = 0; i <= highestStem; i++){ if(!plot.containsKey(i)){ LinkedList<Integer> list = new LinkedList<Integer>(); plot.put(i, list); } } } return plot; } public static void printPlot(Map<Integer, List<Integer>> plot){ for(Map.Entry<Integer, List<Integer>> line : plot.entrySet()){ Collections.sort(line.getValue()); System.out.println(line.getKey() + " | " + line.getValue()); } } public static void main(String[] args){ Map<Integer, List<Integer>> plot = createPlot(data); printPlot(plot); } }
Produce a language-to-language conversion: from F# to Python, same semantics.
open System let data = [ 12; 127; 28; 42; 39; 113; 42; 18; 44; 118; 44; 37; 113; 124; 37; 48; 127; 36; 29; 31; 125; 139; 131; 115; 105; 132; 104; 123; 35; 113; 122; 42; 117; 119; 58; 109; 23; 105; 63; 27; 44; 105; 99; 41; 128; 121; 116; 125; 32; 61; 37; 127; 29; 113; 121; 58; 114; 126; 53; 114; 96; 25; 109; 7; 31; 141; 46; 13; 27; 43; 117; 116; 27; 7; 68; 40; 31; 115; 124; 42; 128; 52; 71; 118; 117; 38; 27; 106; 33; 117; 116; 111; 40; 119; 47; 105; 57; 122; 109; 124; 115; 43; 120; 43; 27; 27; 18; 28; 48; 125; 107; 114; 34; 133; 45; 120; 30; 127; 31; 116; 146 ] let plotStemAndLeafs items = let groupedItems = items |> Seq.sort |> Seq.map (fun i -> i / 10, i % 10) |> Seq.groupBy fst let maxStem = groupedItems |> Seq.maxBy fst |> fst let stemLeafMap = Map.ofSeq groupedItems [0..maxStem] |> List.iter (fun stm -> printf " %2d | " stm match stemLeafMap.TryFind stm with | None -> () | Some items -> items |> Seq.iter (snd >> printf "%d ") printfn "") plotStemAndLeafs data
from collections import namedtuple from pprint import pprint as pp from math import floor Stem = namedtuple('Stem', 'data, leafdigits') data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146), 1.0) def stemplot(stem): d = [] interval = int(10**int(stem.leafdigits)) for data in sorted(stem.data): data = int(floor(data)) stm, lf = divmod(data,interval) d.append( (int(stm), int(lf)) ) stems, leafs = list(zip(*d)) stemwidth = max(len(str(x)) for x in stems) leafwidth = max(len(str(x)) for x in leafs) laststem, out = min(stems) - 1, [] for s,l in d: while laststem < s: laststem += 1 out.append('\n%*i |' % ( stemwidth, laststem)) out.append(' %0*i' % (leafwidth, l)) out.append('\n\nKey:\n Stem multiplier: %i\n X | Y => %i*X+Y\n' % (interval, interval)) return ''.join(out) if __name__ == '__main__': print( stemplot(data0) )
Preserve the algorithm and functionality while converting the code from F# to Go.
open System let data = [ 12; 127; 28; 42; 39; 113; 42; 18; 44; 118; 44; 37; 113; 124; 37; 48; 127; 36; 29; 31; 125; 139; 131; 115; 105; 132; 104; 123; 35; 113; 122; 42; 117; 119; 58; 109; 23; 105; 63; 27; 44; 105; 99; 41; 128; 121; 116; 125; 32; 61; 37; 127; 29; 113; 121; 58; 114; 126; 53; 114; 96; 25; 109; 7; 31; 141; 46; 13; 27; 43; 117; 116; 27; 7; 68; 40; 31; 115; 124; 42; 128; 52; 71; 118; 117; 38; 27; 106; 33; 117; 116; 111; 40; 119; 47; 105; 57; 122; 109; 124; 115; 43; 120; 43; 27; 27; 18; 28; 48; 125; 107; 114; 34; 133; 45; 120; 30; 127; 31; 116; 146 ] let plotStemAndLeafs items = let groupedItems = items |> Seq.sort |> Seq.map (fun i -> i / 10, i % 10) |> Seq.groupBy fst let maxStem = groupedItems |> Seq.maxBy fst |> fst let stemLeafMap = Map.ofSeq groupedItems [0..maxStem] |> List.iter (fun stm -> printf " %2d | " stm match stemLeafMap.TryFind stm with | None -> () | Some items -> items |> Seq.iter (snd >> printf "%d ") printfn "") plotStemAndLeafs data
package main import ( "fmt" "sort" "strconv" "strings" ) var data = `12 127 28 42` func main() { m := make(map[int][]string) for _, s := range strings.Fields(data) { if len(s) == 1 { m[0] = append(m[0], s) } else if i, err := strconv.Atoi(s[:len(s)-1]); err == nil { m[i] = append(m[i], s[len(s)-1:]) } else { panic("non numeric data") } } s := make([]int, len(m)) var i int for k := range m { s[i] = k i++ } sort.Ints(s) for k := s[0]; ; k++ { v := m[k] sort.Strings(v) fmt.Printf("%2d | %s\n", k, strings.Join(v, " ")) if k == s[len(s)-1] { break } } }
Ensure the translated C code behaves exactly like the original Factor snippet.
USING: assocs formatting grouping.extras io kernel math prettyprint sequences sorting ; : leaf-plot ( seq -- ) natural-sort [ 10 /i ] group-by dup keys last 1 + [ dup "%2d | " printf of [ 10 mod pprint bl ] each nl ] with each-integer ; { 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 146 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 } leaf-plot
#include <stdio.h> #include <stdlib.h> int icmp(const void *a, const void *b) { return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*)b; } void leaf_plot(int *x, int len) { int i, j, d; qsort(x, len, sizeof(int), icmp); i = x[0] / 10 - 1; for (j = 0; j < len; j++) { d = x[j] / 10; while (d > i) printf("%s%3d |", j ? "\n" : "", ++i); printf(" %d", x[j] % 10); } } int main() { int data[] = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; leaf_plot(data, sizeof(data)/sizeof(data[0])); return 0; }
Keep all operations the same but rewrite the snippet in C#.
USING: assocs formatting grouping.extras io kernel math prettyprint sequences sorting ; : leaf-plot ( seq -- ) natural-sort [ 10 /i ] group-by dup keys last 1 + [ dup "%2d | " printf of [ 10 mod pprint bl ] each nl ] with each-integer ; { 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 146 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 } leaf-plot
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { const string data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " + "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 " + "105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 " + "114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 " + "115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 " + "105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 " + "133 45 120 30 127 31 116 146"; int[] ints = data.Split(' ').Select(int.Parse).ToArray(); StemAndLeafPlot(ints); Console.ReadKey(); } public static void StemAndLeafPlot(int[] arr) { int stemMax = arr.Max() / 10; int stemMin = arr.Min() / 10; Array.Sort(arr); for (int i = stemMin; i <= stemMax; i++) { Console.Write("{0,3} | ", i); foreach (var t in arr) { if (t < 10 * i) continue; if (t >= 10 * (i + 1)) break; Console.Write("{0} ", t % 10); } Console.WriteLine(""); } } }
Maintain the same structure and functionality when rewriting this code in C++.
USING: assocs formatting grouping.extras io kernel math prettyprint sequences sorting ; : leaf-plot ( seq -- ) natural-sort [ 10 /i ] group-by dup keys last 1 + [ dup "%2d | " printf of [ 10 mod pprint bl ] each nl ] with each-integer ; { 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 146 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 } leaf-plot
#include <algorithm> #include <iomanip> #include <iostream> #include <vector> const int dataset[] = { 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115,105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125, 32, 61, 37,127, 29,113, 121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116, 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117, 116,111, 40,119, 47,105, 57,122,109,124,115, 43,120, 43, 27, 27, 18, 28, 48,125,107,114, 34,133, 45,120, 30,127, 31,116,146 }; const int datasize = sizeof(dataset) / sizeof(dataset[0]); int main() { typedef std::pair<int,int> StemLeaf; std::vector<StemLeaf> stemplot; for (int i = 0; i < datasize; ++i) { stemplot.push_back(StemLeaf(dataset[i] / 10, dataset[i] % 10)); } std::sort(stemplot.begin(), stemplot.end()); int lo = stemplot.front().first; int hi = stemplot.back().first; for (std::vector<StemLeaf>::iterator itr = stemplot.begin(); lo <= hi; ++lo) { std::cout << std::setw(2) << lo << " |"; for ( ; itr != stemplot.end() && itr->first == lo; ++itr) { std::cout << " " << itr->second; } std::cout << std::endl; } }
Translate the given Factor code snippet into Java without altering its behavior.
USING: assocs formatting grouping.extras io kernel math prettyprint sequences sorting ; : leaf-plot ( seq -- ) natural-sort [ 10 /i ] group-by dup keys last 1 + [ dup "%2d | " printf of [ 10 mod pprint bl ] each nl ] with each-integer ; { 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 146 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 } leaf-plot
import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class StemAndLeaf { private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; public static Map<Integer, List<Integer>> createPlot(int... data){ Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>(); int highestStem = -1; for(int datum:data){ int leaf = datum % 10; int stem = datum / 10; if(stem > highestStem){ highestStem = stem; } if(plot.containsKey(stem)){ plot.get(stem).add(leaf); }else{ LinkedList<Integer> list = new LinkedList<Integer>(); list.add(leaf); plot.put(stem, list); } } if(plot.keySet().size() < highestStem + 1 ){ for(int i = 0; i <= highestStem; i++){ if(!plot.containsKey(i)){ LinkedList<Integer> list = new LinkedList<Integer>(); plot.put(i, list); } } } return plot; } public static void printPlot(Map<Integer, List<Integer>> plot){ for(Map.Entry<Integer, List<Integer>> line : plot.entrySet()){ Collections.sort(line.getValue()); System.out.println(line.getKey() + " | " + line.getValue()); } } public static void main(String[] args){ Map<Integer, List<Integer>> plot = createPlot(data); printPlot(plot); } }
Convert this Factor snippet to Python and keep its semantics consistent.
USING: assocs formatting grouping.extras io kernel math prettyprint sequences sorting ; : leaf-plot ( seq -- ) natural-sort [ 10 /i ] group-by dup keys last 1 + [ dup "%2d | " printf of [ 10 mod pprint bl ] each nl ] with each-integer ; { 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 146 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 } leaf-plot
from collections import namedtuple from pprint import pprint as pp from math import floor Stem = namedtuple('Stem', 'data, leafdigits') data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146), 1.0) def stemplot(stem): d = [] interval = int(10**int(stem.leafdigits)) for data in sorted(stem.data): data = int(floor(data)) stm, lf = divmod(data,interval) d.append( (int(stm), int(lf)) ) stems, leafs = list(zip(*d)) stemwidth = max(len(str(x)) for x in stems) leafwidth = max(len(str(x)) for x in leafs) laststem, out = min(stems) - 1, [] for s,l in d: while laststem < s: laststem += 1 out.append('\n%*i |' % ( stemwidth, laststem)) out.append(' %0*i' % (leafwidth, l)) out.append('\n\nKey:\n Stem multiplier: %i\n X | Y => %i*X+Y\n' % (interval, interval)) return ''.join(out) if __name__ == '__main__': print( stemplot(data0) )
Convert the following code from Factor to Go, ensuring the logic remains intact.
USING: assocs formatting grouping.extras io kernel math prettyprint sequences sorting ; : leaf-plot ( seq -- ) natural-sort [ 10 /i ] group-by dup keys last 1 + [ dup "%2d | " printf of [ 10 mod pprint bl ] each nl ] with each-integer ; { 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 146 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 } leaf-plot
package main import ( "fmt" "sort" "strconv" "strings" ) var data = `12 127 28 42` func main() { m := make(map[int][]string) for _, s := range strings.Fields(data) { if len(s) == 1 { m[0] = append(m[0], s) } else if i, err := strconv.Atoi(s[:len(s)-1]); err == nil { m[i] = append(m[i], s[len(s)-1:]) } else { panic("non numeric data") } } s := make([]int, len(m)) var i int for k := range m { s[i] = k i++ } sort.Ints(s) for k := s[0]; ; k++ { v := m[k] sort.Strings(v) fmt.Printf("%2d | %s\n", k, strings.Join(v, " ")) if k == s[len(s)-1] { break } } }
Generate a C translation of this Forth snippet without changing its computational steps.
create data 12 , 127 , 28 , 42 , 39 , 113 , 42 , 18 , 44 , 118 , 44 , 37 , 113 , 124 , 37 , 48 , 127 , 36 , 29 , 31 , 125 , 139 , 131 , 115 , 105 , 132 , 104 , 123 , 35 , 113 , 122 , 42 , 117 , 119 , 58 , 109 , 23 , 105 , 63 , 27 , 44 , 105 , 99 , 41 , 128 , 121 , 116 , 125 , 32 , 61 , 37 , 127 , 29 , 113 , 121 , 58 , 114 , 126 , 53 , 114 , 96 , 25 , 109 , 7 , 31 , 141 , 46 , 13 , 27 , 43 , 117 , 116 , 27 , 7 , 68 , 40 , 31 , 115 , 124 , 42 , 128 , 52 , 71 , 118 , 117 , 38 , 27 , 106 , 33 , 117 , 116 , 111 , 40 , 119 , 47 , 105 , 57 , 122 , 109 , 124 , 115 , 43 , 120 , 43 , 27 , 27 , 18 , 28 , 48 , 125 , 107 , 114 , 34 , 133 , 45 , 120 , 30 , 127 , 31 , 116 , 146 , here constant data-end : sort over cell - swap do dup i cell+ do i @ j @ < if i @ j @ i ! j ! then cell +loop cell +loop drop ; : plot data-end data sort data data-end cell - @ 10 / 1+ data @ 10 / do cr i 2 u.r ." | " begin dup @ 10 /mod i = while . cell+ dup data-end = until else drop then loop drop ; plot
#include <stdio.h> #include <stdlib.h> int icmp(const void *a, const void *b) { return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*)b; } void leaf_plot(int *x, int len) { int i, j, d; qsort(x, len, sizeof(int), icmp); i = x[0] / 10 - 1; for (j = 0; j < len; j++) { d = x[j] / 10; while (d > i) printf("%s%3d |", j ? "\n" : "", ++i); printf(" %d", x[j] % 10); } } int main() { int data[] = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; leaf_plot(data, sizeof(data)/sizeof(data[0])); return 0; }
Rewrite the snippet below in C# so it works the same as the original Forth code.
create data 12 , 127 , 28 , 42 , 39 , 113 , 42 , 18 , 44 , 118 , 44 , 37 , 113 , 124 , 37 , 48 , 127 , 36 , 29 , 31 , 125 , 139 , 131 , 115 , 105 , 132 , 104 , 123 , 35 , 113 , 122 , 42 , 117 , 119 , 58 , 109 , 23 , 105 , 63 , 27 , 44 , 105 , 99 , 41 , 128 , 121 , 116 , 125 , 32 , 61 , 37 , 127 , 29 , 113 , 121 , 58 , 114 , 126 , 53 , 114 , 96 , 25 , 109 , 7 , 31 , 141 , 46 , 13 , 27 , 43 , 117 , 116 , 27 , 7 , 68 , 40 , 31 , 115 , 124 , 42 , 128 , 52 , 71 , 118 , 117 , 38 , 27 , 106 , 33 , 117 , 116 , 111 , 40 , 119 , 47 , 105 , 57 , 122 , 109 , 124 , 115 , 43 , 120 , 43 , 27 , 27 , 18 , 28 , 48 , 125 , 107 , 114 , 34 , 133 , 45 , 120 , 30 , 127 , 31 , 116 , 146 , here constant data-end : sort over cell - swap do dup i cell+ do i @ j @ < if i @ j @ i ! j ! then cell +loop cell +loop drop ; : plot data-end data sort data data-end cell - @ 10 / 1+ data @ 10 / do cr i 2 u.r ." | " begin dup @ 10 /mod i = while . cell+ dup data-end = until else drop then loop drop ; plot
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { const string data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " + "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 " + "105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 " + "114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 " + "115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 " + "105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 " + "133 45 120 30 127 31 116 146"; int[] ints = data.Split(' ').Select(int.Parse).ToArray(); StemAndLeafPlot(ints); Console.ReadKey(); } public static void StemAndLeafPlot(int[] arr) { int stemMax = arr.Max() / 10; int stemMin = arr.Min() / 10; Array.Sort(arr); for (int i = stemMin; i <= stemMax; i++) { Console.Write("{0,3} | ", i); foreach (var t in arr) { if (t < 10 * i) continue; if (t >= 10 * (i + 1)) break; Console.Write("{0} ", t % 10); } Console.WriteLine(""); } } }
Translate the given Forth code snippet into C++ without altering its behavior.
create data 12 , 127 , 28 , 42 , 39 , 113 , 42 , 18 , 44 , 118 , 44 , 37 , 113 , 124 , 37 , 48 , 127 , 36 , 29 , 31 , 125 , 139 , 131 , 115 , 105 , 132 , 104 , 123 , 35 , 113 , 122 , 42 , 117 , 119 , 58 , 109 , 23 , 105 , 63 , 27 , 44 , 105 , 99 , 41 , 128 , 121 , 116 , 125 , 32 , 61 , 37 , 127 , 29 , 113 , 121 , 58 , 114 , 126 , 53 , 114 , 96 , 25 , 109 , 7 , 31 , 141 , 46 , 13 , 27 , 43 , 117 , 116 , 27 , 7 , 68 , 40 , 31 , 115 , 124 , 42 , 128 , 52 , 71 , 118 , 117 , 38 , 27 , 106 , 33 , 117 , 116 , 111 , 40 , 119 , 47 , 105 , 57 , 122 , 109 , 124 , 115 , 43 , 120 , 43 , 27 , 27 , 18 , 28 , 48 , 125 , 107 , 114 , 34 , 133 , 45 , 120 , 30 , 127 , 31 , 116 , 146 , here constant data-end : sort over cell - swap do dup i cell+ do i @ j @ < if i @ j @ i ! j ! then cell +loop cell +loop drop ; : plot data-end data sort data data-end cell - @ 10 / 1+ data @ 10 / do cr i 2 u.r ." | " begin dup @ 10 /mod i = while . cell+ dup data-end = until else drop then loop drop ; plot
#include <algorithm> #include <iomanip> #include <iostream> #include <vector> const int dataset[] = { 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115,105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125, 32, 61, 37,127, 29,113, 121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116, 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117, 116,111, 40,119, 47,105, 57,122,109,124,115, 43,120, 43, 27, 27, 18, 28, 48,125,107,114, 34,133, 45,120, 30,127, 31,116,146 }; const int datasize = sizeof(dataset) / sizeof(dataset[0]); int main() { typedef std::pair<int,int> StemLeaf; std::vector<StemLeaf> stemplot; for (int i = 0; i < datasize; ++i) { stemplot.push_back(StemLeaf(dataset[i] / 10, dataset[i] % 10)); } std::sort(stemplot.begin(), stemplot.end()); int lo = stemplot.front().first; int hi = stemplot.back().first; for (std::vector<StemLeaf>::iterator itr = stemplot.begin(); lo <= hi; ++lo) { std::cout << std::setw(2) << lo << " |"; for ( ; itr != stemplot.end() && itr->first == lo; ++itr) { std::cout << " " << itr->second; } std::cout << std::endl; } }
Port the provided Forth code into Java while preserving the original functionality.
create data 12 , 127 , 28 , 42 , 39 , 113 , 42 , 18 , 44 , 118 , 44 , 37 , 113 , 124 , 37 , 48 , 127 , 36 , 29 , 31 , 125 , 139 , 131 , 115 , 105 , 132 , 104 , 123 , 35 , 113 , 122 , 42 , 117 , 119 , 58 , 109 , 23 , 105 , 63 , 27 , 44 , 105 , 99 , 41 , 128 , 121 , 116 , 125 , 32 , 61 , 37 , 127 , 29 , 113 , 121 , 58 , 114 , 126 , 53 , 114 , 96 , 25 , 109 , 7 , 31 , 141 , 46 , 13 , 27 , 43 , 117 , 116 , 27 , 7 , 68 , 40 , 31 , 115 , 124 , 42 , 128 , 52 , 71 , 118 , 117 , 38 , 27 , 106 , 33 , 117 , 116 , 111 , 40 , 119 , 47 , 105 , 57 , 122 , 109 , 124 , 115 , 43 , 120 , 43 , 27 , 27 , 18 , 28 , 48 , 125 , 107 , 114 , 34 , 133 , 45 , 120 , 30 , 127 , 31 , 116 , 146 , here constant data-end : sort over cell - swap do dup i cell+ do i @ j @ < if i @ j @ i ! j ! then cell +loop cell +loop drop ; : plot data-end data sort data data-end cell - @ 10 / 1+ data @ 10 / do cr i 2 u.r ." | " begin dup @ 10 /mod i = while . cell+ dup data-end = until else drop then loop drop ; plot
import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class StemAndLeaf { private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; public static Map<Integer, List<Integer>> createPlot(int... data){ Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>(); int highestStem = -1; for(int datum:data){ int leaf = datum % 10; int stem = datum / 10; if(stem > highestStem){ highestStem = stem; } if(plot.containsKey(stem)){ plot.get(stem).add(leaf); }else{ LinkedList<Integer> list = new LinkedList<Integer>(); list.add(leaf); plot.put(stem, list); } } if(plot.keySet().size() < highestStem + 1 ){ for(int i = 0; i <= highestStem; i++){ if(!plot.containsKey(i)){ LinkedList<Integer> list = new LinkedList<Integer>(); plot.put(i, list); } } } return plot; } public static void printPlot(Map<Integer, List<Integer>> plot){ for(Map.Entry<Integer, List<Integer>> line : plot.entrySet()){ Collections.sort(line.getValue()); System.out.println(line.getKey() + " | " + line.getValue()); } } public static void main(String[] args){ Map<Integer, List<Integer>> plot = createPlot(data); printPlot(plot); } }
Rewrite the snippet below in Python so it works the same as the original Forth code.
create data 12 , 127 , 28 , 42 , 39 , 113 , 42 , 18 , 44 , 118 , 44 , 37 , 113 , 124 , 37 , 48 , 127 , 36 , 29 , 31 , 125 , 139 , 131 , 115 , 105 , 132 , 104 , 123 , 35 , 113 , 122 , 42 , 117 , 119 , 58 , 109 , 23 , 105 , 63 , 27 , 44 , 105 , 99 , 41 , 128 , 121 , 116 , 125 , 32 , 61 , 37 , 127 , 29 , 113 , 121 , 58 , 114 , 126 , 53 , 114 , 96 , 25 , 109 , 7 , 31 , 141 , 46 , 13 , 27 , 43 , 117 , 116 , 27 , 7 , 68 , 40 , 31 , 115 , 124 , 42 , 128 , 52 , 71 , 118 , 117 , 38 , 27 , 106 , 33 , 117 , 116 , 111 , 40 , 119 , 47 , 105 , 57 , 122 , 109 , 124 , 115 , 43 , 120 , 43 , 27 , 27 , 18 , 28 , 48 , 125 , 107 , 114 , 34 , 133 , 45 , 120 , 30 , 127 , 31 , 116 , 146 , here constant data-end : sort over cell - swap do dup i cell+ do i @ j @ < if i @ j @ i ! j ! then cell +loop cell +loop drop ; : plot data-end data sort data data-end cell - @ 10 / 1+ data @ 10 / do cr i 2 u.r ." | " begin dup @ 10 /mod i = while . cell+ dup data-end = until else drop then loop drop ; plot
from collections import namedtuple from pprint import pprint as pp from math import floor Stem = namedtuple('Stem', 'data, leafdigits') data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146), 1.0) def stemplot(stem): d = [] interval = int(10**int(stem.leafdigits)) for data in sorted(stem.data): data = int(floor(data)) stm, lf = divmod(data,interval) d.append( (int(stm), int(lf)) ) stems, leafs = list(zip(*d)) stemwidth = max(len(str(x)) for x in stems) leafwidth = max(len(str(x)) for x in leafs) laststem, out = min(stems) - 1, [] for s,l in d: while laststem < s: laststem += 1 out.append('\n%*i |' % ( stemwidth, laststem)) out.append(' %0*i' % (leafwidth, l)) out.append('\n\nKey:\n Stem multiplier: %i\n X | Y => %i*X+Y\n' % (interval, interval)) return ''.join(out) if __name__ == '__main__': print( stemplot(data0) )
Maintain the same structure and functionality when rewriting this code in Go.
create data 12 , 127 , 28 , 42 , 39 , 113 , 42 , 18 , 44 , 118 , 44 , 37 , 113 , 124 , 37 , 48 , 127 , 36 , 29 , 31 , 125 , 139 , 131 , 115 , 105 , 132 , 104 , 123 , 35 , 113 , 122 , 42 , 117 , 119 , 58 , 109 , 23 , 105 , 63 , 27 , 44 , 105 , 99 , 41 , 128 , 121 , 116 , 125 , 32 , 61 , 37 , 127 , 29 , 113 , 121 , 58 , 114 , 126 , 53 , 114 , 96 , 25 , 109 , 7 , 31 , 141 , 46 , 13 , 27 , 43 , 117 , 116 , 27 , 7 , 68 , 40 , 31 , 115 , 124 , 42 , 128 , 52 , 71 , 118 , 117 , 38 , 27 , 106 , 33 , 117 , 116 , 111 , 40 , 119 , 47 , 105 , 57 , 122 , 109 , 124 , 115 , 43 , 120 , 43 , 27 , 27 , 18 , 28 , 48 , 125 , 107 , 114 , 34 , 133 , 45 , 120 , 30 , 127 , 31 , 116 , 146 , here constant data-end : sort over cell - swap do dup i cell+ do i @ j @ < if i @ j @ i ! j ! then cell +loop cell +loop drop ; : plot data-end data sort data data-end cell - @ 10 / 1+ data @ 10 / do cr i 2 u.r ." | " begin dup @ 10 /mod i = while . cell+ dup data-end = until else drop then loop drop ; plot
package main import ( "fmt" "sort" "strconv" "strings" ) var data = `12 127 28 42` func main() { m := make(map[int][]string) for _, s := range strings.Fields(data) { if len(s) == 1 { m[0] = append(m[0], s) } else if i, err := strconv.Atoi(s[:len(s)-1]); err == nil { m[i] = append(m[i], s[len(s)-1:]) } else { panic("non numeric data") } } s := make([]int, len(m)) var i int for k := range m { s[i] = k i++ } sort.Ints(s) for k := s[0]; ; k++ { v := m[k] sort.Strings(v) fmt.Printf("%2d | %s\n", k, strings.Join(v, " ")) if k == s[len(s)-1] { break } } }
Generate a C# translation of this Fortran snippet without changing its computational steps.
SUBROUTINE COMBSORT(A,N) INTEGER A(*) INTEGER N INTEGER H,T LOGICAL CURSE H = N - 1 1 H = MAX(1,H*10/13) IF (H.EQ.9 .OR. H.EQ.10) H = 11 CURSE = .FALSE. DO I = N - H,1,-1 IF (A(I) .GT. A(I + H)) THEN T=A(I); A(I)=A(I+H); A(I+H)=T CURSE = .TRUE. END IF END DO IF (CURSE .OR. H.GT.1) GO TO 1 END SUBROUTINE COMBSORT SUBROUTINE TOPIARY(A,N) INTEGER A(*) INTEGER N INTEGER CLIP PARAMETER (CLIP = 10) INTEGER I1,I2,STEM CALL COMBSORT(A,N) STEM = A(1)/CLIP I1 = 1 I2 = I1 10 I2 = I2 + 1 IF (I2 .GT. N) GO TO 11 IF (A(I2)/CLIP .EQ.STEM) GO TO 10 Cast forth a STEM line, corresponding to elements I1:I2 - 1. 11 WRITE (6,12) STEM,ABS(MOD(A(I1:I2 - 1),CLIP)) 12 FORMAT (I4,"|",(100I1)) IF (I2 .GT. N) RETURN I1 = I2 Chug along to the next STEM value. 13 STEM = STEM + 1 IF (A(I2)/CLIP.GT.STEM) GO TO 11 GO TO 10 END SUBROUTINE TOPIARY PROGRAM TEST INTEGER VALUES(121) DATA VALUES/ o 12,127, 28, 42, 39,113, 42, 18, 44,118, 1 44, 37,113,124, 37, 48,127, 36, 29, 31, 2 125,139,131,115,105,132,104,123, 35,113, 3 122, 42,117,119, 58,109, 23,105, 63, 27, 4 44,105, 99, 41,128,121,116,125, 32, 61, 5 37,127, 29,113,121, 58,114,126, 53,114, 6 96, 25,109, 7, 31,141, 46, 13, 27, 43, 7 117,116, 27, 7, 68, 40, 31,115,124, 42, 8 128, 52, 71,118,117, 38, 27,106, 33,117, 9 116,111, 40,119, 47,105, 57,122,109,124, o 115, 43,120, 43, 27, 27, 18, 28, 48,125, 1 107,114, 34,133, 45,120, 30,127, 31,116, 2 146/ CALL TOPIARY(VALUES,121) END
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { const string data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " + "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 " + "105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 " + "114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 " + "115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 " + "105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 " + "133 45 120 30 127 31 116 146"; int[] ints = data.Split(' ').Select(int.Parse).ToArray(); StemAndLeafPlot(ints); Console.ReadKey(); } public static void StemAndLeafPlot(int[] arr) { int stemMax = arr.Max() / 10; int stemMin = arr.Min() / 10; Array.Sort(arr); for (int i = stemMin; i <= stemMax; i++) { Console.Write("{0,3} | ", i); foreach (var t in arr) { if (t < 10 * i) continue; if (t >= 10 * (i + 1)) break; Console.Write("{0} ", t % 10); } Console.WriteLine(""); } } }
Convert this Fortran block to C++, preserving its control flow and logic.
SUBROUTINE COMBSORT(A,N) INTEGER A(*) INTEGER N INTEGER H,T LOGICAL CURSE H = N - 1 1 H = MAX(1,H*10/13) IF (H.EQ.9 .OR. H.EQ.10) H = 11 CURSE = .FALSE. DO I = N - H,1,-1 IF (A(I) .GT. A(I + H)) THEN T=A(I); A(I)=A(I+H); A(I+H)=T CURSE = .TRUE. END IF END DO IF (CURSE .OR. H.GT.1) GO TO 1 END SUBROUTINE COMBSORT SUBROUTINE TOPIARY(A,N) INTEGER A(*) INTEGER N INTEGER CLIP PARAMETER (CLIP = 10) INTEGER I1,I2,STEM CALL COMBSORT(A,N) STEM = A(1)/CLIP I1 = 1 I2 = I1 10 I2 = I2 + 1 IF (I2 .GT. N) GO TO 11 IF (A(I2)/CLIP .EQ.STEM) GO TO 10 Cast forth a STEM line, corresponding to elements I1:I2 - 1. 11 WRITE (6,12) STEM,ABS(MOD(A(I1:I2 - 1),CLIP)) 12 FORMAT (I4,"|",(100I1)) IF (I2 .GT. N) RETURN I1 = I2 Chug along to the next STEM value. 13 STEM = STEM + 1 IF (A(I2)/CLIP.GT.STEM) GO TO 11 GO TO 10 END SUBROUTINE TOPIARY PROGRAM TEST INTEGER VALUES(121) DATA VALUES/ o 12,127, 28, 42, 39,113, 42, 18, 44,118, 1 44, 37,113,124, 37, 48,127, 36, 29, 31, 2 125,139,131,115,105,132,104,123, 35,113, 3 122, 42,117,119, 58,109, 23,105, 63, 27, 4 44,105, 99, 41,128,121,116,125, 32, 61, 5 37,127, 29,113,121, 58,114,126, 53,114, 6 96, 25,109, 7, 31,141, 46, 13, 27, 43, 7 117,116, 27, 7, 68, 40, 31,115,124, 42, 8 128, 52, 71,118,117, 38, 27,106, 33,117, 9 116,111, 40,119, 47,105, 57,122,109,124, o 115, 43,120, 43, 27, 27, 18, 28, 48,125, 1 107,114, 34,133, 45,120, 30,127, 31,116, 2 146/ CALL TOPIARY(VALUES,121) END
#include <algorithm> #include <iomanip> #include <iostream> #include <vector> const int dataset[] = { 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115,105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125, 32, 61, 37,127, 29,113, 121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116, 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117, 116,111, 40,119, 47,105, 57,122,109,124,115, 43,120, 43, 27, 27, 18, 28, 48,125,107,114, 34,133, 45,120, 30,127, 31,116,146 }; const int datasize = sizeof(dataset) / sizeof(dataset[0]); int main() { typedef std::pair<int,int> StemLeaf; std::vector<StemLeaf> stemplot; for (int i = 0; i < datasize; ++i) { stemplot.push_back(StemLeaf(dataset[i] / 10, dataset[i] % 10)); } std::sort(stemplot.begin(), stemplot.end()); int lo = stemplot.front().first; int hi = stemplot.back().first; for (std::vector<StemLeaf>::iterator itr = stemplot.begin(); lo <= hi; ++lo) { std::cout << std::setw(2) << lo << " |"; for ( ; itr != stemplot.end() && itr->first == lo; ++itr) { std::cout << " " << itr->second; } std::cout << std::endl; } }
Can you help me rewrite this code in C instead of Fortran, keeping it the same logically?
SUBROUTINE COMBSORT(A,N) INTEGER A(*) INTEGER N INTEGER H,T LOGICAL CURSE H = N - 1 1 H = MAX(1,H*10/13) IF (H.EQ.9 .OR. H.EQ.10) H = 11 CURSE = .FALSE. DO I = N - H,1,-1 IF (A(I) .GT. A(I + H)) THEN T=A(I); A(I)=A(I+H); A(I+H)=T CURSE = .TRUE. END IF END DO IF (CURSE .OR. H.GT.1) GO TO 1 END SUBROUTINE COMBSORT SUBROUTINE TOPIARY(A,N) INTEGER A(*) INTEGER N INTEGER CLIP PARAMETER (CLIP = 10) INTEGER I1,I2,STEM CALL COMBSORT(A,N) STEM = A(1)/CLIP I1 = 1 I2 = I1 10 I2 = I2 + 1 IF (I2 .GT. N) GO TO 11 IF (A(I2)/CLIP .EQ.STEM) GO TO 10 Cast forth a STEM line, corresponding to elements I1:I2 - 1. 11 WRITE (6,12) STEM,ABS(MOD(A(I1:I2 - 1),CLIP)) 12 FORMAT (I4,"|",(100I1)) IF (I2 .GT. N) RETURN I1 = I2 Chug along to the next STEM value. 13 STEM = STEM + 1 IF (A(I2)/CLIP.GT.STEM) GO TO 11 GO TO 10 END SUBROUTINE TOPIARY PROGRAM TEST INTEGER VALUES(121) DATA VALUES/ o 12,127, 28, 42, 39,113, 42, 18, 44,118, 1 44, 37,113,124, 37, 48,127, 36, 29, 31, 2 125,139,131,115,105,132,104,123, 35,113, 3 122, 42,117,119, 58,109, 23,105, 63, 27, 4 44,105, 99, 41,128,121,116,125, 32, 61, 5 37,127, 29,113,121, 58,114,126, 53,114, 6 96, 25,109, 7, 31,141, 46, 13, 27, 43, 7 117,116, 27, 7, 68, 40, 31,115,124, 42, 8 128, 52, 71,118,117, 38, 27,106, 33,117, 9 116,111, 40,119, 47,105, 57,122,109,124, o 115, 43,120, 43, 27, 27, 18, 28, 48,125, 1 107,114, 34,133, 45,120, 30,127, 31,116, 2 146/ CALL TOPIARY(VALUES,121) END
#include <stdio.h> #include <stdlib.h> int icmp(const void *a, const void *b) { return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*)b; } void leaf_plot(int *x, int len) { int i, j, d; qsort(x, len, sizeof(int), icmp); i = x[0] / 10 - 1; for (j = 0; j < len; j++) { d = x[j] / 10; while (d > i) printf("%s%3d |", j ? "\n" : "", ++i); printf(" %d", x[j] % 10); } } int main() { int data[] = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; leaf_plot(data, sizeof(data)/sizeof(data[0])); return 0; }
Convert the following code from Fortran to Java, ensuring the logic remains intact.
SUBROUTINE COMBSORT(A,N) INTEGER A(*) INTEGER N INTEGER H,T LOGICAL CURSE H = N - 1 1 H = MAX(1,H*10/13) IF (H.EQ.9 .OR. H.EQ.10) H = 11 CURSE = .FALSE. DO I = N - H,1,-1 IF (A(I) .GT. A(I + H)) THEN T=A(I); A(I)=A(I+H); A(I+H)=T CURSE = .TRUE. END IF END DO IF (CURSE .OR. H.GT.1) GO TO 1 END SUBROUTINE COMBSORT SUBROUTINE TOPIARY(A,N) INTEGER A(*) INTEGER N INTEGER CLIP PARAMETER (CLIP = 10) INTEGER I1,I2,STEM CALL COMBSORT(A,N) STEM = A(1)/CLIP I1 = 1 I2 = I1 10 I2 = I2 + 1 IF (I2 .GT. N) GO TO 11 IF (A(I2)/CLIP .EQ.STEM) GO TO 10 Cast forth a STEM line, corresponding to elements I1:I2 - 1. 11 WRITE (6,12) STEM,ABS(MOD(A(I1:I2 - 1),CLIP)) 12 FORMAT (I4,"|",(100I1)) IF (I2 .GT. N) RETURN I1 = I2 Chug along to the next STEM value. 13 STEM = STEM + 1 IF (A(I2)/CLIP.GT.STEM) GO TO 11 GO TO 10 END SUBROUTINE TOPIARY PROGRAM TEST INTEGER VALUES(121) DATA VALUES/ o 12,127, 28, 42, 39,113, 42, 18, 44,118, 1 44, 37,113,124, 37, 48,127, 36, 29, 31, 2 125,139,131,115,105,132,104,123, 35,113, 3 122, 42,117,119, 58,109, 23,105, 63, 27, 4 44,105, 99, 41,128,121,116,125, 32, 61, 5 37,127, 29,113,121, 58,114,126, 53,114, 6 96, 25,109, 7, 31,141, 46, 13, 27, 43, 7 117,116, 27, 7, 68, 40, 31,115,124, 42, 8 128, 52, 71,118,117, 38, 27,106, 33,117, 9 116,111, 40,119, 47,105, 57,122,109,124, o 115, 43,120, 43, 27, 27, 18, 28, 48,125, 1 107,114, 34,133, 45,120, 30,127, 31,116, 2 146/ CALL TOPIARY(VALUES,121) END
import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class StemAndLeaf { private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; public static Map<Integer, List<Integer>> createPlot(int... data){ Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>(); int highestStem = -1; for(int datum:data){ int leaf = datum % 10; int stem = datum / 10; if(stem > highestStem){ highestStem = stem; } if(plot.containsKey(stem)){ plot.get(stem).add(leaf); }else{ LinkedList<Integer> list = new LinkedList<Integer>(); list.add(leaf); plot.put(stem, list); } } if(plot.keySet().size() < highestStem + 1 ){ for(int i = 0; i <= highestStem; i++){ if(!plot.containsKey(i)){ LinkedList<Integer> list = new LinkedList<Integer>(); plot.put(i, list); } } } return plot; } public static void printPlot(Map<Integer, List<Integer>> plot){ for(Map.Entry<Integer, List<Integer>> line : plot.entrySet()){ Collections.sort(line.getValue()); System.out.println(line.getKey() + " | " + line.getValue()); } } public static void main(String[] args){ Map<Integer, List<Integer>> plot = createPlot(data); printPlot(plot); } }
Write the same algorithm in Python as shown in this Fortran implementation.
SUBROUTINE COMBSORT(A,N) INTEGER A(*) INTEGER N INTEGER H,T LOGICAL CURSE H = N - 1 1 H = MAX(1,H*10/13) IF (H.EQ.9 .OR. H.EQ.10) H = 11 CURSE = .FALSE. DO I = N - H,1,-1 IF (A(I) .GT. A(I + H)) THEN T=A(I); A(I)=A(I+H); A(I+H)=T CURSE = .TRUE. END IF END DO IF (CURSE .OR. H.GT.1) GO TO 1 END SUBROUTINE COMBSORT SUBROUTINE TOPIARY(A,N) INTEGER A(*) INTEGER N INTEGER CLIP PARAMETER (CLIP = 10) INTEGER I1,I2,STEM CALL COMBSORT(A,N) STEM = A(1)/CLIP I1 = 1 I2 = I1 10 I2 = I2 + 1 IF (I2 .GT. N) GO TO 11 IF (A(I2)/CLIP .EQ.STEM) GO TO 10 Cast forth a STEM line, corresponding to elements I1:I2 - 1. 11 WRITE (6,12) STEM,ABS(MOD(A(I1:I2 - 1),CLIP)) 12 FORMAT (I4,"|",(100I1)) IF (I2 .GT. N) RETURN I1 = I2 Chug along to the next STEM value. 13 STEM = STEM + 1 IF (A(I2)/CLIP.GT.STEM) GO TO 11 GO TO 10 END SUBROUTINE TOPIARY PROGRAM TEST INTEGER VALUES(121) DATA VALUES/ o 12,127, 28, 42, 39,113, 42, 18, 44,118, 1 44, 37,113,124, 37, 48,127, 36, 29, 31, 2 125,139,131,115,105,132,104,123, 35,113, 3 122, 42,117,119, 58,109, 23,105, 63, 27, 4 44,105, 99, 41,128,121,116,125, 32, 61, 5 37,127, 29,113,121, 58,114,126, 53,114, 6 96, 25,109, 7, 31,141, 46, 13, 27, 43, 7 117,116, 27, 7, 68, 40, 31,115,124, 42, 8 128, 52, 71,118,117, 38, 27,106, 33,117, 9 116,111, 40,119, 47,105, 57,122,109,124, o 115, 43,120, 43, 27, 27, 18, 28, 48,125, 1 107,114, 34,133, 45,120, 30,127, 31,116, 2 146/ CALL TOPIARY(VALUES,121) END
from collections import namedtuple from pprint import pprint as pp from math import floor Stem = namedtuple('Stem', 'data, leafdigits') data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146), 1.0) def stemplot(stem): d = [] interval = int(10**int(stem.leafdigits)) for data in sorted(stem.data): data = int(floor(data)) stm, lf = divmod(data,interval) d.append( (int(stm), int(lf)) ) stems, leafs = list(zip(*d)) stemwidth = max(len(str(x)) for x in stems) leafwidth = max(len(str(x)) for x in leafs) laststem, out = min(stems) - 1, [] for s,l in d: while laststem < s: laststem += 1 out.append('\n%*i |' % ( stemwidth, laststem)) out.append(' %0*i' % (leafwidth, l)) out.append('\n\nKey:\n Stem multiplier: %i\n X | Y => %i*X+Y\n' % (interval, interval)) return ''.join(out) if __name__ == '__main__': print( stemplot(data0) )
Port the provided Haskell code into C while preserving the original functionality.
import Data.List import Control.Arrow import Control.Monad nlsRaw = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31" ++ " 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63" ++ " 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53" ++ " 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128" ++ " 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115" ++ " 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146" nls :: [Int] nls = map read $ words nlsRaw groupWith f = takeWhile(not.null). unfoldr(Just. (partition =<< (. f). (==). f. head)) justifyR = foldl ((. return) . (++) . tail) . flip replicate ' ' task ds = mapM_ (putStrLn. showStemLeaves justifyR fb. (head *** sort.concat). unzip) $ groupWith fst $ stems ++ map (second return) stemLeaf where stemLeaf = map (`quotRem` 10) ds stems = map (flip(,)[]) $ uncurry enumFromTo $ minimum &&& maximum $ fst $ unzip stemLeaf showStemLeaves f w (a,b) = f w (show a) ++ " |" ++ concatMap (f w. show) b fb = length $ show $ maximum $ map abs ds
#include <stdio.h> #include <stdlib.h> int icmp(const void *a, const void *b) { return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*)b; } void leaf_plot(int *x, int len) { int i, j, d; qsort(x, len, sizeof(int), icmp); i = x[0] / 10 - 1; for (j = 0; j < len; j++) { d = x[j] / 10; while (d > i) printf("%s%3d |", j ? "\n" : "", ++i); printf(" %d", x[j] % 10); } } int main() { int data[] = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; leaf_plot(data, sizeof(data)/sizeof(data[0])); return 0; }
Convert the following code from Haskell to C#, ensuring the logic remains intact.
import Data.List import Control.Arrow import Control.Monad nlsRaw = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31" ++ " 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63" ++ " 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53" ++ " 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128" ++ " 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115" ++ " 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146" nls :: [Int] nls = map read $ words nlsRaw groupWith f = takeWhile(not.null). unfoldr(Just. (partition =<< (. f). (==). f. head)) justifyR = foldl ((. return) . (++) . tail) . flip replicate ' ' task ds = mapM_ (putStrLn. showStemLeaves justifyR fb. (head *** sort.concat). unzip) $ groupWith fst $ stems ++ map (second return) stemLeaf where stemLeaf = map (`quotRem` 10) ds stems = map (flip(,)[]) $ uncurry enumFromTo $ minimum &&& maximum $ fst $ unzip stemLeaf showStemLeaves f w (a,b) = f w (show a) ++ " |" ++ concatMap (f w. show) b fb = length $ show $ maximum $ map abs ds
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { const string data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " + "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 " + "105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 " + "114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 " + "115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 " + "105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 " + "133 45 120 30 127 31 116 146"; int[] ints = data.Split(' ').Select(int.Parse).ToArray(); StemAndLeafPlot(ints); Console.ReadKey(); } public static void StemAndLeafPlot(int[] arr) { int stemMax = arr.Max() / 10; int stemMin = arr.Min() / 10; Array.Sort(arr); for (int i = stemMin; i <= stemMax; i++) { Console.Write("{0,3} | ", i); foreach (var t in arr) { if (t < 10 * i) continue; if (t >= 10 * (i + 1)) break; Console.Write("{0} ", t % 10); } Console.WriteLine(""); } } }
Rewrite the snippet below in C++ so it works the same as the original Haskell code.
import Data.List import Control.Arrow import Control.Monad nlsRaw = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31" ++ " 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63" ++ " 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53" ++ " 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128" ++ " 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115" ++ " 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146" nls :: [Int] nls = map read $ words nlsRaw groupWith f = takeWhile(not.null). unfoldr(Just. (partition =<< (. f). (==). f. head)) justifyR = foldl ((. return) . (++) . tail) . flip replicate ' ' task ds = mapM_ (putStrLn. showStemLeaves justifyR fb. (head *** sort.concat). unzip) $ groupWith fst $ stems ++ map (second return) stemLeaf where stemLeaf = map (`quotRem` 10) ds stems = map (flip(,)[]) $ uncurry enumFromTo $ minimum &&& maximum $ fst $ unzip stemLeaf showStemLeaves f w (a,b) = f w (show a) ++ " |" ++ concatMap (f w. show) b fb = length $ show $ maximum $ map abs ds
#include <algorithm> #include <iomanip> #include <iostream> #include <vector> const int dataset[] = { 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115,105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125, 32, 61, 37,127, 29,113, 121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116, 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117, 116,111, 40,119, 47,105, 57,122,109,124,115, 43,120, 43, 27, 27, 18, 28, 48,125,107,114, 34,133, 45,120, 30,127, 31,116,146 }; const int datasize = sizeof(dataset) / sizeof(dataset[0]); int main() { typedef std::pair<int,int> StemLeaf; std::vector<StemLeaf> stemplot; for (int i = 0; i < datasize; ++i) { stemplot.push_back(StemLeaf(dataset[i] / 10, dataset[i] % 10)); } std::sort(stemplot.begin(), stemplot.end()); int lo = stemplot.front().first; int hi = stemplot.back().first; for (std::vector<StemLeaf>::iterator itr = stemplot.begin(); lo <= hi; ++lo) { std::cout << std::setw(2) << lo << " |"; for ( ; itr != stemplot.end() && itr->first == lo; ++itr) { std::cout << " " << itr->second; } std::cout << std::endl; } }
Port the following code from Haskell to Java with equivalent syntax and logic.
import Data.List import Control.Arrow import Control.Monad nlsRaw = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31" ++ " 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63" ++ " 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53" ++ " 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128" ++ " 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115" ++ " 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146" nls :: [Int] nls = map read $ words nlsRaw groupWith f = takeWhile(not.null). unfoldr(Just. (partition =<< (. f). (==). f. head)) justifyR = foldl ((. return) . (++) . tail) . flip replicate ' ' task ds = mapM_ (putStrLn. showStemLeaves justifyR fb. (head *** sort.concat). unzip) $ groupWith fst $ stems ++ map (second return) stemLeaf where stemLeaf = map (`quotRem` 10) ds stems = map (flip(,)[]) $ uncurry enumFromTo $ minimum &&& maximum $ fst $ unzip stemLeaf showStemLeaves f w (a,b) = f w (show a) ++ " |" ++ concatMap (f w. show) b fb = length $ show $ maximum $ map abs ds
import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class StemAndLeaf { private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; public static Map<Integer, List<Integer>> createPlot(int... data){ Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>(); int highestStem = -1; for(int datum:data){ int leaf = datum % 10; int stem = datum / 10; if(stem > highestStem){ highestStem = stem; } if(plot.containsKey(stem)){ plot.get(stem).add(leaf); }else{ LinkedList<Integer> list = new LinkedList<Integer>(); list.add(leaf); plot.put(stem, list); } } if(plot.keySet().size() < highestStem + 1 ){ for(int i = 0; i <= highestStem; i++){ if(!plot.containsKey(i)){ LinkedList<Integer> list = new LinkedList<Integer>(); plot.put(i, list); } } } return plot; } public static void printPlot(Map<Integer, List<Integer>> plot){ for(Map.Entry<Integer, List<Integer>> line : plot.entrySet()){ Collections.sort(line.getValue()); System.out.println(line.getKey() + " | " + line.getValue()); } } public static void main(String[] args){ Map<Integer, List<Integer>> plot = createPlot(data); printPlot(plot); } }
Translate the given Haskell code snippet into Python without altering its behavior.
import Data.List import Control.Arrow import Control.Monad nlsRaw = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31" ++ " 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63" ++ " 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53" ++ " 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128" ++ " 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115" ++ " 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146" nls :: [Int] nls = map read $ words nlsRaw groupWith f = takeWhile(not.null). unfoldr(Just. (partition =<< (. f). (==). f. head)) justifyR = foldl ((. return) . (++) . tail) . flip replicate ' ' task ds = mapM_ (putStrLn. showStemLeaves justifyR fb. (head *** sort.concat). unzip) $ groupWith fst $ stems ++ map (second return) stemLeaf where stemLeaf = map (`quotRem` 10) ds stems = map (flip(,)[]) $ uncurry enumFromTo $ minimum &&& maximum $ fst $ unzip stemLeaf showStemLeaves f w (a,b) = f w (show a) ++ " |" ++ concatMap (f w. show) b fb = length $ show $ maximum $ map abs ds
from collections import namedtuple from pprint import pprint as pp from math import floor Stem = namedtuple('Stem', 'data, leafdigits') data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146), 1.0) def stemplot(stem): d = [] interval = int(10**int(stem.leafdigits)) for data in sorted(stem.data): data = int(floor(data)) stm, lf = divmod(data,interval) d.append( (int(stm), int(lf)) ) stems, leafs = list(zip(*d)) stemwidth = max(len(str(x)) for x in stems) leafwidth = max(len(str(x)) for x in leafs) laststem, out = min(stems) - 1, [] for s,l in d: while laststem < s: laststem += 1 out.append('\n%*i |' % ( stemwidth, laststem)) out.append(' %0*i' % (leafwidth, l)) out.append('\n\nKey:\n Stem multiplier: %i\n X | Y => %i*X+Y\n' % (interval, interval)) return ''.join(out) if __name__ == '__main__': print( stemplot(data0) )
Port the provided Haskell code into Go while preserving the original functionality.
import Data.List import Control.Arrow import Control.Monad nlsRaw = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31" ++ " 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63" ++ " 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53" ++ " 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128" ++ " 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115" ++ " 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146" nls :: [Int] nls = map read $ words nlsRaw groupWith f = takeWhile(not.null). unfoldr(Just. (partition =<< (. f). (==). f. head)) justifyR = foldl ((. return) . (++) . tail) . flip replicate ' ' task ds = mapM_ (putStrLn. showStemLeaves justifyR fb. (head *** sort.concat). unzip) $ groupWith fst $ stems ++ map (second return) stemLeaf where stemLeaf = map (`quotRem` 10) ds stems = map (flip(,)[]) $ uncurry enumFromTo $ minimum &&& maximum $ fst $ unzip stemLeaf showStemLeaves f w (a,b) = f w (show a) ++ " |" ++ concatMap (f w. show) b fb = length $ show $ maximum $ map abs ds
package main import ( "fmt" "sort" "strconv" "strings" ) var data = `12 127 28 42` func main() { m := make(map[int][]string) for _, s := range strings.Fields(data) { if len(s) == 1 { m[0] = append(m[0], s) } else if i, err := strconv.Atoi(s[:len(s)-1]); err == nil { m[i] = append(m[i], s[len(s)-1:]) } else { panic("non numeric data") } } s := make([]int, len(m)) var i int for k := range m { s[i] = k i++ } sort.Ints(s) for k := s[0]; ; k++ { v := m[k] sort.Strings(v) fmt.Printf("%2d | %s\n", k, strings.Join(v, " ")) if k == s[len(s)-1] { break } } }
Produce a language-to-language conversion: from J to C, same semantics.
stem =: <.@(%&10) leaf =: 10&| stemleaf =: (stem@{. ; leaf)/.~ stem expandStems =: <./ ([ + i.@>:@-~) >./ expandLeaves=: (expandStems e. ])@[ #inv ] showStemLeaf=: (":@,.@expandStems@[ ; ":&>@expandLeaves)&>/@(>@{. ; <@{:)@|:@stemleaf@/:~
#include <stdio.h> #include <stdlib.h> int icmp(const void *a, const void *b) { return *(const int*)a < *(const int*)b ? -1 : *(const int*)a > *(const int*)b; } void leaf_plot(int *x, int len) { int i, j, d; qsort(x, len, sizeof(int), icmp); i = x[0] / 10 - 1; for (j = 0; j < len; j++) { d = x[j] / 10; while (d > i) printf("%s%3d |", j ? "\n" : "", ++i); printf(" %d", x[j] % 10); } } int main() { int data[] = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; leaf_plot(data, sizeof(data)/sizeof(data[0])); return 0; }
Translate the given J code snippet into C# without altering its behavior.
stem =: <.@(%&10) leaf =: 10&| stemleaf =: (stem@{. ; leaf)/.~ stem expandStems =: <./ ([ + i.@>:@-~) >./ expandLeaves=: (expandStems e. ])@[ #inv ] showStemLeaf=: (":@,.@expandStems@[ ; ":&>@expandLeaves)&>/@(>@{. ; <@{:)@|:@stemleaf@/:~
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { const string data = "12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 " + "125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 " + "105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 " + "114 126 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 " + "115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 " + "105 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 " + "133 45 120 30 127 31 116 146"; int[] ints = data.Split(' ').Select(int.Parse).ToArray(); StemAndLeafPlot(ints); Console.ReadKey(); } public static void StemAndLeafPlot(int[] arr) { int stemMax = arr.Max() / 10; int stemMin = arr.Min() / 10; Array.Sort(arr); for (int i = stemMin; i <= stemMax; i++) { Console.Write("{0,3} | ", i); foreach (var t in arr) { if (t < 10 * i) continue; if (t >= 10 * (i + 1)) break; Console.Write("{0} ", t % 10); } Console.WriteLine(""); } } }
Port the following code from J to C++ with equivalent syntax and logic.
stem =: <.@(%&10) leaf =: 10&| stemleaf =: (stem@{. ; leaf)/.~ stem expandStems =: <./ ([ + i.@>:@-~) >./ expandLeaves=: (expandStems e. ])@[ #inv ] showStemLeaf=: (":@,.@expandStems@[ ; ":&>@expandLeaves)&>/@(>@{. ; <@{:)@|:@stemleaf@/:~
#include <algorithm> #include <iomanip> #include <iostream> #include <vector> const int dataset[] = { 12,127, 28, 42, 39,113, 42, 18, 44,118, 44, 37,113,124, 37, 48,127, 36, 29, 31,125,139,131,115,105,132,104,123, 35,113,122, 42,117,119, 58,109, 23,105, 63, 27, 44,105, 99, 41,128,121,116,125, 32, 61, 37,127, 29,113, 121, 58,114,126, 53,114, 96, 25,109, 7, 31,141, 46, 13, 27, 43,117,116, 27, 7, 68, 40, 31,115,124, 42,128, 52, 71,118,117, 38, 27,106, 33,117, 116,111, 40,119, 47,105, 57,122,109,124,115, 43,120, 43, 27, 27, 18, 28, 48,125,107,114, 34,133, 45,120, 30,127, 31,116,146 }; const int datasize = sizeof(dataset) / sizeof(dataset[0]); int main() { typedef std::pair<int,int> StemLeaf; std::vector<StemLeaf> stemplot; for (int i = 0; i < datasize; ++i) { stemplot.push_back(StemLeaf(dataset[i] / 10, dataset[i] % 10)); } std::sort(stemplot.begin(), stemplot.end()); int lo = stemplot.front().first; int hi = stemplot.back().first; for (std::vector<StemLeaf>::iterator itr = stemplot.begin(); lo <= hi; ++lo) { std::cout << std::setw(2) << lo << " |"; for ( ; itr != stemplot.end() && itr->first == lo; ++itr) { std::cout << " " << itr->second; } std::cout << std::endl; } }
Produce a language-to-language conversion: from J to Java, same semantics.
stem =: <.@(%&10) leaf =: 10&| stemleaf =: (stem@{. ; leaf)/.~ stem expandStems =: <./ ([ + i.@>:@-~) >./ expandLeaves=: (expandStems e. ])@[ #inv ] showStemLeaf=: (":@,.@expandStems@[ ; ":&>@expandLeaves)&>/@(>@{. ; <@{:)@|:@stemleaf@/:~
import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; public class StemAndLeaf { private static int[] data = { 12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146 }; public static Map<Integer, List<Integer>> createPlot(int... data){ Map<Integer, List<Integer>> plot = new TreeMap<Integer, List<Integer>>(); int highestStem = -1; for(int datum:data){ int leaf = datum % 10; int stem = datum / 10; if(stem > highestStem){ highestStem = stem; } if(plot.containsKey(stem)){ plot.get(stem).add(leaf); }else{ LinkedList<Integer> list = new LinkedList<Integer>(); list.add(leaf); plot.put(stem, list); } } if(plot.keySet().size() < highestStem + 1 ){ for(int i = 0; i <= highestStem; i++){ if(!plot.containsKey(i)){ LinkedList<Integer> list = new LinkedList<Integer>(); plot.put(i, list); } } } return plot; } public static void printPlot(Map<Integer, List<Integer>> plot){ for(Map.Entry<Integer, List<Integer>> line : plot.entrySet()){ Collections.sort(line.getValue()); System.out.println(line.getKey() + " | " + line.getValue()); } } public static void main(String[] args){ Map<Integer, List<Integer>> plot = createPlot(data); printPlot(plot); } }
Maintain the same structure and functionality when rewriting this code in Python.
stem =: <.@(%&10) leaf =: 10&| stemleaf =: (stem@{. ; leaf)/.~ stem expandStems =: <./ ([ + i.@>:@-~) >./ expandLeaves=: (expandStems e. ])@[ #inv ] showStemLeaf=: (":@,.@expandStems@[ ; ":&>@expandLeaves)&>/@(>@{. ; <@{:)@|:@stemleaf@/:~
from collections import namedtuple from pprint import pprint as pp from math import floor Stem = namedtuple('Stem', 'data, leafdigits') data0 = Stem((12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, 43, 117, 116, 27, 7, 68, 40, 31, 115, 124, 42, 128, 52, 71, 118, 117, 38, 27, 106, 33, 117, 116, 111, 40, 119, 47, 105, 57, 122, 109, 124, 115, 43, 120, 43, 27, 27, 18, 28, 48, 125, 107, 114, 34, 133, 45, 120, 30, 127, 31, 116, 146), 1.0) def stemplot(stem): d = [] interval = int(10**int(stem.leafdigits)) for data in sorted(stem.data): data = int(floor(data)) stm, lf = divmod(data,interval) d.append( (int(stm), int(lf)) ) stems, leafs = list(zip(*d)) stemwidth = max(len(str(x)) for x in stems) leafwidth = max(len(str(x)) for x in leafs) laststem, out = min(stems) - 1, [] for s,l in d: while laststem < s: laststem += 1 out.append('\n%*i |' % ( stemwidth, laststem)) out.append(' %0*i' % (leafwidth, l)) out.append('\n\nKey:\n Stem multiplier: %i\n X | Y => %i*X+Y\n' % (interval, interval)) return ''.join(out) if __name__ == '__main__': print( stemplot(data0) )