Quadratic Formula in Multiple Languages

Concepts

Math functions:  square root, power

Printing two (and only two) decimal places when possible

Constraints

Doesn’t handle imaginary numbers

Limited to languages with compilers and interpreters available in Ubuntu Software Center

bash script

# vi quadratic.sh

#!/bin/bash

function quadraticFormula {
  a=$1
  b=$2
  c=$3

  fDiscriminant=$((  (b ** 2) - (4 * a * c)  ))
  fRoot1=`echo "scale=2;(-($b) + sqrt($fDiscriminant)) / (2 * $a)" | bc -l`
  fRoot2=`echo "scale=2;(-($b) - sqrt($fDiscriminant)) / (2 * $a)" | bc -l`

  echo "x=$fRoot1, x=$fRoot2"
}

quadraticFormula 1 -3 -4
quadraticFormula 1 0 -4
quadraticFormula 6 11 -35
quadraticFormula 1 -7 0

# chmod u+x quadratic.sh
# ./quadratic.sh

Note:  Doesn’t round up last decimal;  Doesn’t print decimal point for zero

C

# vi quadratic.c

#include <stdio.h>
#include <math.h>

void quadraticFormula(int a, int b, int c) {
  double fRoot1;
  double fRoot2;

  fRoot1 = (-b + sqrt(pow(b, 2) - (4 * a * c)) ) / (2 * a);
  fRoot2 = (-b - sqrt(pow(b, 2) - (4 * a * c)) ) / (2 * a);

  printf("x=%.2f, x=%.2f\n", fRoot1, fRoot2);
}

int main(void) {
  quadraticFormula(1, -3, -4);
  quadraticFormula(1, 0, -4);
  quadraticFormula(6, 11, -35);
  quadraticFormula(1, -7, 0);

  return 0;
}

# gcc quadratic.c -lm -o quadratic
# ./quadratic

C++

# vi quadratic.cpp

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

void quadraticFormula(int a, int b, int c) {
  float fRoot1;
  float fRoot2;

  fRoot1 = (-b + sqrt(pow(b, 2) - (4 * a * c)) ) / (2 * a);
  fRoot2 = (-b - sqrt(pow(b, 2) - (4 * a * c)) ) / (2 * a);

  cout << fixed << setprecision(2);
  cout << "x=" << fRoot1 << ", x=" << fRoot2 << endl;

}

int main(void) {
  quadraticFormula(1, -3, -4);
  quadraticFormula(1, 0, -4);
  quadraticFormula(6, 11, -35);
  quadraticFormula(1, -7, 0);

  return 0;
}

# g++ quadratic.cpp -o quadratic
# ./quadratic

C Sharp

# vi Quadratic.cs

using System;

public class Quadratic {

  void quadraticFormula(int a, int b, int c) {
    float fRoot1;
    float fRoot2;

    fRoot1 = (float) (-b + Math.Sqrt((Math.Pow(b, 2)) - (4 * a * c)))
                   / (2 * a);
    fRoot2 = (float) (-b - Math.Sqrt((Math.Pow(b, 2)) - (4 * a * c)))
                   / (2 * a);

    System.Console.WriteLine("x=" + fRoot1.ToString("0.00") + ", x=" +
                  fRoot2.ToString("0.00"));
  }

  public static void Main() {
    Quadratic q = new Quadratic();
    q.quadraticFormula(1, -3, -4);
    q.quadraticFormula(1, 0, -4);
    q.quadraticFormula(6, 11, -35);
    q.quadraticFormula(1, -7, 0);
  }
}

# gmcs Quadratic.cs
# mono Quadratic.exe

Forth

# vi quadratic.f

variable a
variable b
variable c

variable fDiscriminant

variable fRoot1
variable fRoot2

: quadraticFormula
4e a f@ f* c f@ f* -1e f* fDiscriminant f!
b f@ 2e f** fDiscriminant f@ f+ fDiscriminant f! 

b f@ -1e f*  fDiscriminant f@ fsqrt f+  fRoot1 f!
fRoot1 f@ 2e a f@ f* f/ fRoot1 f!

b f@ -1e f*  fDiscriminant f@ fsqrt f-  fRoot2 f!
fRoot2 f@ 2e a f@ f* f/ fRoot2 f!

." x="
fRoot1 f@ f.

." , x="
fRoot2 f@ f.

;

1e a f!
-3e b f!
-4e c f!
quadraticFormula cr

1e a f!
0e b f!
-4e c f!
quadraticFormula cr

6e a f!
11e b f!
-35e c f!
quadraticFormula cr

1e a f!
-7e b f!
0e c f!
quadraticFormula cr

# gforth quadratic.f

Note:  Doesn’t format to two decimal places

FORTRAN 77

# vi quadratic.f

      program quadratic
      call quadraticFormula(1.0, -3.0, -4.0)
      call quadraticFormula(1.0, 0.0, -4.0)
      call quadraticFormula(6.0, 11.0, -35.0)
      call quadraticFormula(1.0, -7.0, 0.0)
      stop
      end

      subroutine quadraticFormula(a, b, c)
      real a, b, c
      real fRoot1, fRoot2

      fRoot1 = (-b + sqrt((b ** 2) - (4 * a * c)) ) / (2 * a)
      fRoot2 = (-b - sqrt((b ** 2) - (4 * a * c)) ) / (2 * a) 

      write(*,100) fRoot1, fRoot2
 100  format ('x=', F0.2, ', x=', F0.2)

      end

# gfortran quadratic.f -o quadratic
# ./quadratic

Java

# vi Quadratic.java

import java.text.DecimalFormat;

public class Quadratic {

  public Quadratic() {

  }

  public void quadraticFormula(int a, int b, int c) {
    float fRoot1;
    float fRoot2;

    fRoot1 = (float) (-b + Math.sqrt( Math.pow(b, 2) - (4 * a * c)) ) /
                     (2 * a);
    fRoot2 = (float) (-b - Math.sqrt( Math.pow(b, 2) - (4 * a * c)) ) /
                     (2 * a);

    DecimalFormat df = new DecimalFormat("0.00");
    System.out.println("x=" + df.format(fRoot1) + ", x=" + 
      df.format(fRoot2));
  }

  public static void main(String args[]) {
    Quadratic q = new Quadratic();

    q.quadraticFormula(1, -3, -4);
    q.quadraticFormula(1, 0, -4);
    q.quadraticFormula(6, 11, -35);
    q.quadraticFormula(1, -7, 0);
  }
}

# javac Quadratic.java
# java Quadratic

Javascript (Rhino)

# vi quadratic.js

function quadraticFormula(a, b, c) {
  var fRoot1
  var fRoot2

  fRoot1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a)
  fRoot2 = (-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a)
  print("x=" + fRoot1.toFixed(2) + ", x=" + fRoot2.toFixed(2))
}

quadraticFormula(1, -3, -4)
quadraticFormula(1, 0, -4)
quadraticFormula(6, 11, -35)
quadraticFormula(1, -7, 0)

# js -f quadratic.js

Common Lisp (GNU)

# vi quadratic.lisp

(defun quadraticFormula(a b c)
  (let (
         (fRoot1 (/
                    (+ (* -1 b)
                      (sqrt
                        (- (expt b 2) (* 4 a c ) )
                      )
                    )
                    (* 2 a)
                 )
         )
         (fRoot2 (/
                    (- (* -1 b)
                      (sqrt
                        (- (expt b 2) (* 4 a c ) )
                      )
                    )
                    (* 2 a)
                 )
         )
       )
    (format t "x=~,2f" fRoot1)
    (format t ", x=~,2f~%" fRoot2)
  )
)

(quadraticFormula 1 -3 -4)
(quadraticFormula 1 0 -4)
(quadraticFormula 6 11 -35)
(quadraticFormula 1 -7 0)

# gcl -load quadratic.lisp

Lua

# vi quadratic.lua

function quadraticFormula(a, b, c)
  fRoot1 = (-b + math.sqrt(math.pow(b, 2) - (4 * a * c))) / (2 * a)
  fRoot2 = (-b - math.sqrt(math.pow(b, 2) - (4 * a * c))) / (2 * a)

  print(string.format("x=%.2f, x=%.2f", fRoot1, fRoot2))
end

quadraticFormula(1, -3, -4)
quadraticFormula(1, 0, -4)
quadraticFormula(6, 11, -35)
quadraticFormula(1, -7, 0)

# lua quadratic.lua

Objective C

# vi Quadratic.m

#import <objc/objc.h>
#import <objc/Object.h>
#import <stdio.h>
#import <math.h>

@interface Quadratic : Object {
}

-(void) quadraticFormula:(int)a  val:(int)b val:(int)c;
@end

@implementation Quadratic : Object

-(void) quadraticFormula:(int)a  val:(int)b val:(int)c {
  double fRoot1;
  double fRoot2;

  fRoot1 = (-b + sqrt(pow(b, 2) - (4 * a * c)) ) / (2 * a);
  fRoot2 = (-b - sqrt(pow(b, 2) - (4 * a * c)) ) / (2 * a);

  printf("x=%.2f, x=%.2f\n", fRoot1, fRoot2);
}

@end

int main(int argc, const char *argv[] ) {
  Quadratic *q = [Quadratic new];

  [q quadraticFormula:1 val:-3 val:-4];
  [q quadraticFormula:1 val:0 val:-4];
  [q quadraticFormula:6 val:11 val:-35];
  [q quadraticFormula:1 val:-7 val:0];
  return 0;
}

# gcc -x objective-c -o quadratic Quadratic.m -lobjc -lm
# ./quadratic

Perl

# vi quadratic.pl

sub quadraticFormula {
  $a = $_[0];
  $b = $_[1];
  $c = $_[2];

  $fRoot1 = (-$b + sqrt(($b ** 2) - (4 * $a * $c)) ) / (2 * $a);
  $fRoot2 = (-$b - sqrt(($b ** 2) - (4 * $a * $c)) ) / (2 * $a);

  printf "x=%.2f, x=%.2f\n", $fRoot1, $fRoot2;

}

quadraticFormula(1, -3, -4);
quadraticFormula(1, 0, -4);
quadraticFormula(6, 11, -35);
quadraticFormula(1, -7, 0);

#perl quadratic.pl

PHP

# vi quadratic.php

<?php

  function quadraticFormula($a, $b, $c) {
    $fRoot1 = (-$b + sqrt( pow($b, 2) - (4 * $a * $c))) / (2 * $a);
    $fRoot2 = (-$b - sqrt( pow($b, 2) - (4 * $a * $c))) / (2 * $a);

    echo "x=" . number_format($fRoot1, 2) . ", x=" .
      number_format($fRoot2, 2) . "\n";
  }

  quadraticFormula(1, -3, -4);
  quadraticFormula(1, 0, -4);
  quadraticFormula(6, 11, -35);
  quadraticFormula(1, -7, 0);

?>

# php quadratic.php

Python

# vi quadratic.py

import math

def quadraticFormula(a, b, c):
  fRoot1 = (-b + math.sqrt((b ** 2) - (4 * a * c)) ) / (2 * a)
  fRoot2 = (-b - math.sqrt((b ** 2) - (4 * a * c)) ) / (2 * a)

  print "x=" + ("%.2f" % fRoot1) + ", x=" + ("%.2f" % fRoot2)

quadraticFormula(1, -3, -4)
quadraticFormula(1, 0, -4)
quadraticFormula(6, 11, -35)
quadraticFormula(1, -7, 0)

# python quadratic.py

Ruby

# vi quadratic.rb

def quadraticFormula(a, b, c)
  fRoot1 = nil
  fRoot2 = nil

  fRoot1 = (-b + Math.sqrt((b ** 2) - (4 * a * c)) ) / (2 * a)
  fRoot2 = (-b - Math.sqrt((b ** 2) - (4 * a * c)) ) / (2 * a)

  printf("x=%.2f, x=%.2f\n", fRoot1, fRoot2)

end

quadraticFormula(1, -3, -4)
quadraticFormula(1, 0, -4)
quadraticFormula(6, 11, -35)
quadraticFormula(1, -7, 0)

# ruby quadratic.rb

Scala

# vi Quadratic.scala

object Quadratic {

  def quadraticFormula(a: Int, b: Int, c: Int) = {
    var fRoot1 = (-b + Math.sqrt( Math.pow(b, 2) - (4 * a * c) ) ) / (2 * a)
    var fRoot2 = (-b - Math.sqrt( Math.pow(b, 2) - (4 * a * c) ) ) / (2 * a)
    printf("x=%.2f, x=%.2f\n", fRoot1, fRoot2)
  }

  def main(args: Array[String]) {
    this.quadraticFormula(1, -3, -4)
    this.quadraticFormula(1, 0, -4)
    this.quadraticFormula(6, 11, -35)
    this.quadraticFormula(1, -7, 0)
  }
}

# scalac Quadratic.scala
# scala Quadratic

Scheme (MIT/GNU)

#vi quadratic.scm

(define fRoot1)
(define fRoot2)
(define fDiscriminant)

(newline)
(define (quadraticFormula a b c)

  (set! fDiscriminant (expt b 2)  )
  (set! fDiscriminant (- fDiscriminant (* 4 a c) ) )

  (set! fRoot1 (* -1 b) )
  (set! fRoot1 (+ fRoot1 (sqrt fDiscriminant) ) )
  (set! fRoot1 (/ fRoot1 (* 2 a)) )
  (display "x=")
  (display fRoot1)

  (set! fRoot2 (* -1 b) )
  (set! fRoot2 (- fRoot2 (sqrt fDiscriminant) ) )
  (set! fRoot2 (/ fRoot2 (* 2 a)) )
  (display ", x=")(display fRoot2)(newline)

)

(quadraticFormula 1 -3 -4)
(quadraticFormula 1 0 -4)
(quadraticFormula 6 11 -35)
(quadraticFormula 1 -7 0)

(exit)

# scheme –load quadratic.scm

Note: This code could probably be written more efficiently

SmallTalk (Squeak)

| q |
q := Quadratic new.
q quadraticFormula: 1 and: -3 and: -4.
q quadraticFormula: 1 and: 0 and: -4.
q quadraticFormula: 6 and: 11 and: -35.
q quadraticFormula: 1 and: -7 and: 0.

quadraticFormula: a and: b and: c
  | fRoot1 fRoot2 |

  fRoot1 := ( (-1 * b) + ( (b raisedTo: 2) - (4 * a * c) ) sqrt) / (2 * a).
  fRoot2 := ( (-1 * b) - ( (b raisedTo: 2) - (4 * a * c) ) sqrt) / (2 * a).

  Transcript show: 'x='.
  Transcript show: (fRoot1 roundTo: 0.01).
  Transcript show: ', x='.
  Transcript show: (fRoot2 roundTo: 0.01).
  Transcript cr.

Note:  Must be entered and run (Do It / Alt-D) through the Squeak environment

Tcl

# vi quadratic.tcl

proc quadraticFormula {a b c} {
  set fRoot1 [expr {(-$b + sqrt(pow($b, 2) - (4 * $a * $c))) / (2 * $a)}]
  set fRoot2 [expr {(-$b - sqrt(pow($b, 2) - (4 * $a * $c))) / (2 * $a)}]

  puts [format "x=%.2f, x=%.2f" $fRoot1 $fRoot2]
}

quadraticFormula 1 -3 -4
quadraticFormula 1 0 -4
quadraticFormula 6 11 -35
quadraticFormula 1 -7 0

# tclsh quadratic.tcl

Output

x=4.00, x=-1.00
x=2.00, x=-2.00
x=1.67, x=-3.50
x=7.00, x=0.00

Caesar Cipher in Twelve Languages

Caesar Cipher in Twelve Languages

Concepts

String functions: string length, character at index, uppercase conversion

Adding/Subtracting ASCII values of characters

Method creation

Constraints

Lowercase letters are converted to uppercase

All non-alpha characters are converted to space

Shifts outside of 0 through 25 are modded by 26; Languages that return negative values modulo of a negative number are converted to positive value

Use string “append” methods instead of creating new string objects when possible

C

# vi caesar.c

#include <stdio.h>
#include <string.h>

void caesarCipher(char *strText, int iShiftValue) {
  int i;
  char c;
  int iShift;
  char strCipherText[strlen(strText) + 1];

  iShift = iShiftValue % 26;
  if (iShift < 0) {
    iShift += 26;
  }

  i = 0;
  while (i < strlen(strText)) {
    c = toupper(strText[i]);
    if ( (c >= 'A') && (c <= 'Z')) {
      if ( (c + iShift) > 'Z') {
        strCipherText[i] = c + iShift - 26;
      } else {
        strCipherText[i] = c + iShift;
      }
    } else {
      strCipherText[i] = ' ';
    }
    i++;
  }
  strCipherText[i] = '';

  printf("%s\n", strCipherText);

}

int main(void) {
  caesarCipher("the quick brown fox jumps over the lazy dog", 3); 

  return 0;
}

# gcc caesar.c -o caesar

# ./caesar

C++

# vi caesar.cpp

#include <iostream>
#include <string>

using namespace std;

void caesarCipher(string strText, int iShiftValue) {
  int i;
  char c;
  int iShift;
  string strCipherText;

  strCipherText = "";

  iShift = iShiftValue % 26;
  if (iShift < 0) {
    iShift += 26;
  }

  i = 0;
  while (i < strText.size()) {
    c = toupper(strText.at(i));
    if ( (c >= 'A') && (c <= 'Z') ) {
      if ( (c + iShift) > 'Z') {
        strCipherText.push_back(c + iShift - 26);
      } else {
        strCipherText.push_back(c + iShift);
      }
    } else {
      strCipherText.push_back(' ');
    }
    i++;
  }

  cout << "CipherText: " << strCipherText << endl;
}

int main(void) {
  caesarCipher("the quick brown fox jumps over the lazy dog", 3);

  return 0;
}

# g++ caesar.cpp -o caesar

# ./caesar

Java

# vi Caesar.java

public class Caesar {

  public Caesar() {
    caesarCipher("the quick brown fox jumps over the lazy dog", 3);
  }

  private void caesarCipher(String strText, int iShiftValue) {
    int i;
    char c;
    int iShift;
    StringBuffer sb;
    String strCipherText;

    sb = new StringBuffer();
    strCipherText = "";

    iShift = iShiftValue % 26;
    if (iShift < 0) {
      iShift += 26;
    }

    i = 0;
    while (i < strText.length()) {
      c = Character.toUpperCase(strText.charAt(i));
      if ( (c >= 'A') && (c <= 'Z') ) {
        if ( (c + iShift) > 'Z') {
          sb.append((char) (c + iShift - 26));
        } else {
          sb.append((char) (c + iShift));
        }
      } else {
        sb.append(' ');
      }
      i++;
    }

    strCipherText = sb.toString();
    System.out.println(strCipherText);
  } 

  public static void main(String args[]) {
    new Caesar();
  }
}

# javac Caesar.java

# java Caesar

Ruby

#  vi caesar.rb

def caesarCipher(strText, iShiftValue)
  strCipherText = ""

  iShift = iShiftValue % 26
  if (iShift < 0)
    iShift += 26
  end

  i = 0
  while (i < strText.length)
    c = strText[i].chr.upcase
    if ( (c >= 'A') && (c <= 'Z') )
      if ( (c[0] + iShift) > 'Z'[0])
        strCipherText << (c[0] + iShift - 26)
      else
        strCipherText << (c[0] + iShift)
      end
    else
      strCipherText << ' '
    end

    i += 1
  end

  puts "#{strCipherText}"

end

caesarCipher("the quick brown fox jumps over the lazy dog", 3)

# ruby caesar.rb

Perl

# vi caesar.pl

sub caesarCipher {
  $strText = $_[0];
  $iShiftValue = $_[1];

  $strCipherText = "";
  @strTextArray = split(//, $strText);

  $iShift = $iShiftValue % 26;
  if ($iShift < 0) {
    $iShift += 26;
  }

  $i = 0;
  while ($i < length($strText)) {
    $c = uc($strTextArray[$i]);
    if ( ($c ge 'A') && ($c le 'Z') ) {
      if ( chr(ord($c) + $iShift) gt 'Z') {
        $strCipherText .= chr(ord($c) + $iShift - 26);
      } else {
        $strCipherText .= chr(ord($c) + $iShift);
      }
    } else {
      $strCipherText .= " ";
    }

    $i++;
  }

  print $strCipherText . "\n";
}

caesarCipher("the quick brown fox jumps over the lazy dog", 3);

# perl caesar.pl

 

Smalltalk (Squeak)

# squeak

| i c strCipherText strText iShiftValue iShift |

strText := 'the quick brown fox jumps over the lazy dog'.
iShiftValue := 3.

strCipherText := ''.
iShift := iShiftValue \\ 26.

i := 1.
[ i <= (strText size) ]
whileTrue: [
  c := (strText at: i) asUppercase.

  ( ( c >= $A) & ( c <= $Z ) )
  ifTrue: [

    ((c asciiValue) + iShift > $Z asciiValue)
    ifTrue: [
      strCipherText := strCipherText, (((c asciiValue) + iShift - 26)
                          asCharacter asString).
    ]
    ifFalse: [
      strCipherText := strCipherText, (((c asciiValue) + iShift)
                          asCharacter asString).
    ].

  ]
  ifFalse: [
    strCipherText := strCipherText, ' '.
  ].

  i := i + 1.
].

Transcript show: strCipherText.
Transcript cr.

Highlight text in Transcript window, Alt-D (Do It)

Python

# vi caesar.py

def caesarCipher(strText, iShiftValue):
  strCipherText = ""

  iShift = iShiftValue % 26

  i = 0
  while (i < len(strText)):
    c = strText[i].upper()

    if ( (c >= 'A') & (c <= 'Z') ):
      if ( chr(ord(c) + iShift) > 'Z'):
        strCipherText += chr(ord(c) + iShift - 26)
      else:
        strCipherText += chr(ord(c) + iShift)
    else:
      strCipherText += ' ' 

    i += 1

  print strCipherText

caesarCipher("the quick brown fox jumps over the lazy dog", 3)

# python caesar.py

FORTRAN 77

# vi caesar.f

      program caesar
      call caesarCipher('the quick brown fox jumps over the lazy dog',
     +3)
      end

      subroutine caesarCipher(strText, iShiftValue)
      integer i, iShift, iShiftValue, iLen
      character strText*(*)
      character strCipherText(64)
      character c

      iShift = mod(iShiftValue, 26)
      if (iShift < 0) then
        iShift = iShift + 26
      end if

      i = 1
 10   if (i .LE. LEN(strText)) then
        c = strText(i:i)
        if ( (c .GE. 'a') .AND. (c .LE. 'z')) then
          c = CHAR(ICHAR(c) - (ICHAR('a') - ICHAR('A')))

        end if

        if ( (c .GE. 'A') .AND. (c .LE. 'Z') ) then
          if (ICHAR(c) + iShift .GT. ICHAR('Z')) then
            strCipherText(i) = CHAR(ICHAR(c) + iShift - 26)
          else
            strCipherText(i) = CHAR(ICHAR(c) + iShift)
          end if
        else
          strCipherText(i) = ' '
        end if

        i = i + 1

        goto 10
      end if

      print *, strCipherText

      return
      end

# gfortran caesar.f -o caesar

# ./caesar

Note:  Limit of 64 characters of cipher text;  may print garbage characters after cipher text

Scheme (MIT/GNU)

# vi caesar.scm

    (define strText "the quick brown fox jumps over the lazy dog")
    (define iShiftValue 3)
    (define strCipherText "")
    (define iShift (modulo iShiftValue 26))
    (define c "")
    (display iShift) (newline)
    (let loop ((i 0))
      (if (< i (string-length strText))
        (begin
          (set! c (char-upcase (string-ref strText i)))
          (if (char-alphabetic? c)
            (begin

              (if (> (+ (char-code c) iShift) (char-code #\Z))
                (begin
                  (set! strCipherText (string-append strCipherText (char->name (
                    make-char (- (+ (char-code c) iShift) 26) 0))))
                )
              )
              (if (not (> (+ (char-code c) iShift) (char-code #\Z)))
                (begin
                  (set! strCipherText (string-append strCipherText (char->name (
                    make-char (+ (char-code c) iShift)  0))))
                )
              )

            )
          ) 

          (if (not (char-alphabetic? c))
            (begin
              (set! strCipherText (string-append strCipherText " "))
            )
          )

          (loop (+ i 1))
        )
      )
    )
    (display strCipherText)(newline)
    (exit)

# scheme –load caesar.scm

Note:  Prints extra loading and closing output

Scala

# vi Caesar.scala

object Caesar {

  def caesarCipher(strText: String, iShiftValue: Int) = {
    var strCipherText = ""
    var sb = new StringBuilder("") 

    var iShift = iShiftValue % 26
    if (iShift < 0) {
      iShift += 26
    }

    var i = 0
    while (i < strText.length) {
      var c = strText.charAt(i).toUpperCase
      if ( (c >= 'A') && (c <= 'Z') ) {
        if ( (c + iShift) > 'Z') {
          sb.append((c + iShift - 26).toChar)
        } else {
          sb.append((c + iShift).toChar)

        }
      } else {
        sb.append(' ');
      }
      i += 1
    }

    println(sb.toString())
  }

  def main(args: Array[String]) {
    this.caesarCipher("the quick brown fox jumps over the lazy dog", 3)
  }
}

# scalac Caesar.scala

# scala Caesar

PHP

# vi caesar.php

<?php

  function caesarCipher($strText, $iShiftValue) {
    $strCipherText = "";

    $iShift = $iShiftValue % 26;
    if ($iShift < 0) {
      $iShift += 26;
    }

    $i = 0;
    while ($i < strlen($strText)) {
      $c = strtoupper($strText{$i}); 

      if ( ($c >= "A") && ($c <= 'Z')) {
        if ( (ord($c) + $iShift) > ord("Z") ) {
           $strCipherText .= chr(ord($c) + $iShift - 26);
        } else {
          $strCipherText .= chr(ord($c) + $iShift);
        }
      } else {
        $strCipherText .= " ";
      }

      $i++;
    }

    echo $strCipherText . "\n";
  }

  caesarCipher("the quick brown fox jumps over the lazy dog", 3);

?>

# php caesar.ph

bash script

# vi caesar.sh

#!/bin/bash

function caesarCipher {
  strText=$1
  iShiftValue=$2

  strCipherText=""
  iShift=$(( iShiftValue % 26 ))

  if [ $iShift -lt 0 ]; then
    iShift=$(( iShift + 26 ))
  fi

  i=0
  while [ $i -lt ${#strText} ]
  do
    c="$(echo ${strText:i:1} | tr '[a-z]' '[A-Z]')"
    if [[ $c =~ [A-Z] ]]; then
      n=$(printf "%d" "'$c")
      n=$(( n + iShift ))

      if [[ $n>$(printf "%d" "'Z") ]]; then
        n=$(( n - 26 ))
        str=$(printf \\$(printf '%03o' $n))
        strCipherText="${strCipherText}${str}" 

      else

        str=$(printf \\$(printf '%03o' $n))
        strCipherText="${strCipherText}${str}"
      fi
    else
      strCipherText="${strCipherText} "
    fi

    (( i++ ))
  done

  echo $strCipherText

}

caesarCipher "the quick brown fox jumps over the lazy dog" 3

# chmod u+x caesar.sh

# ./caesar.sh

Output

WKH TXLFN EURZQ IRA MXPSV RYHU WKH ODCB GRJ

Number Guessing Game in Eleven Languages

Objective:  Create a number guessing game, where the user picks an integer (whole positive number) from 1 to 100.  If the user guesses incorrectly, then they will be told if the correct answer is higher or lower.  The user keeps guessing until they enter the correct answer.

Concepts covered:

  • User input from STDIN
  • IF/ELSE IF conditionals
  • WHILE loops
  • random integer generation

Constraints:  Only languages that are available in Ubuntu 11.04 or the Synaptic repository are included.

C

# vi guess.c

#include <stdio.h>
#include <time.h>

int main(void) {
  int iGuess;
  int iGuessCount;
  int iAnswer;

  srand(time(NULL));

  iGuess = -1;
  iGuessCount = 0;
  iAnswer = (rand() % 100) + 1; 

  while (iGuess != iAnswer) {
    printf("Guess the number\n");
    scanf("%d", &iGuess);
    iGuessCount++;

    if (iGuess > iAnswer) {
      printf("Lower\n");
    } else if (iGuess < iAnswer) {
      printf("Higher\n");
    } else if (iGuess == iAnswer) {
      printf("Correct: %d\n", iAnswer);
      printf("%d total guesses\n", iGuessCount);
    }

  }

  return 0;
}

# gcc guess.c -o guess

# ./guess

C++

# vi guess.cpp

#include <iostream>
#include <cstdlib>

using namespace std;

int main(void) {
  int iGuess;
  int iGuessCount;
  int iAnswer;

  srand(time(NULL));

  iGuess = -1;
  iGuessCount = 0;
  iAnswer = (rand() % 100) + 1;

  while (iGuess != iAnswer) {
    cout << "Guess the number" << endl;
    cin >> iGuess;

    iGuessCount++;

    if (iGuess > iAnswer) {
      cout << "Lower" << endl;
    } else if (iGuess < iAnswer) {
      cout << "Higher" << endl;
    } else if (iGuess == iAnswer) {
      cout << "Correct: " << iAnswer << endl;
      cout << iGuessCount << " total guesses" << endl;
    }

  }

  return 0;

}

# g++ guess.cpp -o guess

# ./guess

Java

# vi Guess.java

import java.util.Random;
import java.io.*;

public class Guess {

  public Guess() {
    int iGuess;
    int iGuessCount;
    int iAnswer;
    String strLine;

    iGuess = -1;
    iGuessCount = 0;
    iAnswer = (Math.abs((new Random()).nextInt()) % 100) + 1;

    try {

      BufferedReader in = new BufferedReader(
                            new InputStreamReader(System.in));
      while (iGuess != iAnswer) {
        System.out.println("Guess the number");
        strLine = in.readLine();

        try {
          iGuess = Integer.parseInt(strLine);
          iGuessCount++;

          if (iGuess > iAnswer) {
            System.out.println("Lower");
          } else if (iGuess < iAnswer) {
            System.out.println("Higher");
          } else if (iGuess == iAnswer) {
            System.out.println("Correct " + iAnswer);
            System.out.println(iGuessCount + " total guesses");
          }

        } catch (NumberFormatException e2) {
          System.out.println("Invalid Input");
        }
      }
    } catch (IOException e1) {
      e1.printStackTrace();
    }

  }

  public static void main(String args[]) {
    new Guess();
  }

}

# javac Guess.java

# java Guess

Ruby

# vi guess.rb

iGuess = -1
iGuessCount = 0
iAnswer = 1 + rand(100)

while (iGuess != iAnswer)
  puts "Guess the number"
  iGuess = gets().to_i
  iGuessCount += 1

  if (iGuess > iAnswer)
    puts "Lower"
  elsif (iGuess < iAnswer)
    puts "Higher"
  elsif (iGuess == iAnswer)
    puts "Correct: #{iAnswer}"
    puts "#{iGuessCount} total guesses"
  end

end

# ruby guess.rb

Perl

# vi guess.pl

$iGuess = -1;
$iGuessCount = 0;
$iAnswer = int(rand(100)) + 1;

while ($iGuess != $iAnswer) {
  print "Guess the number" . "\n";
  $iGuess = <STDIN>;
  $iGuessCount += 1;

  if ($iGuess > $iAnswer) {
    print "Lower" . "\n";
  } elsif ($iGuess < $iAnswer) {
    print "Higher" . "\n";
  } elsif ($iGuess == $iAnswer) {
    print "Correct: " . $iAnswer . "\n";
    print $iGuessCount . " total guesses" . "\n";
  }
}

# perl guess.pl

SmallTalk (Squeak)

| iGuess iGuessCount iAnswer |

iGuess := -1.
iGuessCount := 0.
iAnswer := (1 to: 100) atRandom.

[ (iGuess ~= iAnswer) ]
whileTrue: [

  iGuess := FillInTheBlankMorph request: 'Guess the number'.
  iGuess := iGuess asNumber.
  iGuessCount := iGuessCount + 1.

  (iGuess > iAnswer)
  ifTrue: [
    Transcript show: 'Lower'.
    Transcript cr.
  ].

  (iGuess < iAnswer)
  ifTrue: [
	Transcript show: 'Higher'.
	Transcript cr.
  ].

  (iGuess = iAnswer)
  ifTrue: [
    Transcript show: 'Correct: '.
    Transcript show: iAnswer.
    Transcript cr.
    Transcript show: iGuessCount.
    Transcript show: ' total guesses'.
    Transcript cr.
  ].
].

With code in a Transcript window, select text, then “Do It” (Alt-D)

Python

# vi guess.py

import random
import sys

iGuess = -1
iGuessCount = 0
iAnswer = random.randint(1, 100)

while iGuess != iAnswer:
  print "Guess the number"
  iGuess = input()
  iGuessCount += 1

  if iGuess > iAnswer:
    print "Lower"
  elif iGuess < iAnswer:
    print "Higher"
  elif iGuess == iAnswer:
    print("Correct: " + str(iAnswer))
    print(str(iGuessCount) + " total guesses")

# python guess.py

FORTRAN 77

# vi guess.f

       program guess
       integer iGuess, iGuessCount, iAnswer

       iGuess = -1
       iGuessCount = 0
       call srand(time())
       iAnswer = irand(0)
       iAnswer = mod(iAnswer, 100) + 1

10     if (iGuess.NE.iAnswer) then

         print *, 'Guess the number'
         read(*,*) iGuess
         iGuessCount = iGuessCount + 1

         if (iGuess.GT.iAnswer) then
           print *, 'Lower'
         end if

         if (iGuess.LT.iAnswer) then
           print *, 'Higher'
         end if

         if (iGuess.EQ.iAnswer) then
           print *, 'Correct: ', iGuess
           print *, iGuessCount, ' total guesses'
         end if

       goto 10
       endif

       stop
       end

# gfortran guess.f -o guess

# ./guess

Scala

# vi Guess.scala

import scala.util.Random

object Guess {

  def start() = {
    var iGuess = -1
    var iGuessCount = 0
    var iAnswer =  (new Random()).nextInt(100) + 1

    while (iGuess != iAnswer) {
      println("Guess the number")
      iGuess = readInt
      iGuessCount += 1

      if (iGuess > iAnswer) {
        println("Lower")
      } else if (iGuess < iAnswer) {
        println("Higher")
      } else if (iGuess == iAnswer) {
        println("Correct: " + iAnswer)
        println(iGuessCount + " total guesses")
      }
     }
  }

  def main(args: Array[String]) {
    this.start()
  }
}

# scalac Guess.scala

# scala Guess

PHP

# vi guess.php

<?php

  $iGuess = -1;
  $iGuessCount = 0;
  $iAnswer = rand(1, 100);

  while ($iGuess != $iAnswer) {
    echo "Guess the number\n";
    $iGuess = trim(fgets(STDIN));
    $iGuessCount++;

    if ($iGuess > $iAnswer) {
      echo "Lower\n";
    } elseif ($iGuess < $iAnswer) {
      echo "Higher\n";
    } elseif ($iGuess == $iAnswer) {
      echo "Correct: " . $iAnswer . "\n";
      echo $iGuessCount . " total guesses\n";
    } 

  }
?>

# php guess.php

bash script

# vi guess.sh

#!/bin/bash

iGuess=-1
iGuessCount=0
iAnswer=$(( ($RANDOM % 100) + 1))

while [ $iGuess -ne $iAnswer ]
do
  echo "Guess the number"
  read iGuess
  (( iGuessCount++ ))

  if [ $iGuess -gt $iAnswer ]; then
    echo "Lower"
  elif [ $iGuess -lt $iAnswer ]; then
    echo "Higher"
  elif [ $iGuess -eq $iAnswer ]; then
    echo "Correct: $iAnswer"
    echo "$iGuessCount total guesses"
  fi
done

# chmod u+x guess.sh

# ./guess.sh

Output

Guess the number
50
Higher
Guess the number
75
Lower
Guess the number
63
Lower
Guess the number
57
Higher
Guess the number
60
Correct: 60
5 total guesses