Cross Product and Normalization in Multiple Languages

Objective

Calculate the cross product (normal vector) of two vectors in 3D space by taking the cross product of those two vectors.  Vectors should be stored as an array type structure with index 0 holding the x component, index 1 holding the y component, and index 2 holding the z component.  Normalize this result so that it is a unit vector of length one.

Concepts

Passing arrays to methods

Math functions: square root, exponent

Print values to four decimal places

Constraints

Compiler or interpreter must be available in Ubuntu Software Center

bash script

# vi cross.sh

#!/bin/bash

function crossProduct {
  declare -a v1=("${!1}")
  declare -a v2=("${!2}") 

#Note:  Can't pass by reference, so the global variable must be used
  vectResult[0]=$(( (v1[1] * v2[2]) - (v1[2] * v2[1]) ))
  vectResult[1]=$(( - ((v1[0] * v2[2]) - (v1[2] * v2[0])) ))
  vectResult[2]=$(( (v1[0] * v2[1]) - (v1[1] * v2[0]) ))

}

function normalize {
  declare -a v1=("${!1}") 

  fMag=`echo "scale=4; sqrt( (${v1[0]}^2) + (${v1[1]}^2) + (${v1[2]}^2) )" | bc -l`

  vectNormal[0]=`echo "scale=4;${v1[0]} / $fMag" | bc -l`
  vectNormal[1]=`echo "scale=4;${v1[1]} / $fMag" | bc -l`
  vectNormal[2]=`echo "scale=4;${v1[2]} / $fMag" | bc -l`

}

vect1[0]=3
vect1[1]=-3
vect1[2]=1

vect2[0]=4
vect2[1]=9
vect2[2]=2

crossProduct vect1[@] vect2[@]
echo ${vectResult[0]} ${vectResult[1]} ${vectResult[2]}

normalize vectResult[@]
echo ${vectNormal[0]} ${vectNormal[1]} ${vectNormal[2]}

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

C

# vi cross.c

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

void crossProduct(float v1[], float v2[], float vR[]) {
  vR[0] =   ( (v1[1] * v2[2]) - (v1[2] * v2[1]) );
  vR[1] = - ( (v1[0] * v2[2]) - (v1[2] * v2[0]) );
  vR[2] =   ( (v1[0] * v2[1]) - (v1[1] * v2[0]) );
}

void normalize(float v1[], float vR[]) {
  float fMag;

  fMag = sqrt( pow(v1[0], 2) +
               pow(v1[1], 2) +
               pow(v1[2], 2)
             );

  vR[0] = v1[0] / fMag;
  vR[1] = v1[1] / fMag;
  vR[2] = v1[2] / fMag;
}

int main(void) {
  float vect1[3];
  float vect2[3];
  float vectResult[3];
  float vectNormal[3];

  vect1[0] = 3;
  vect1[1] = -3;
  vect1[2] = 1;

  vect2[0] = 4;
  vect2[1] = 9;
  vect2[2] = 2;

  crossProduct(vect1, vect2, vectResult);
  printf("x: %.4f, y: %.4f, z: %.4f\n",
         vectResult[0], vectResult[1], vectResult[2]); 

  normalize(vectResult, vectNormal);
  printf("x: %.4f, y: %.4f, z: %.4f\n",
         vectNormal[0], vectNormal[1], vectNormal[2]); 

  return 0;
}

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

C++

# vi cross.cpp

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

using namespace std;

class cross {
  public:
    void crossProduct(float v1[], float v2[], float vR[]);
    void normalize(float v1[], float vR[]);
};

void cross::crossProduct(float v1[], float v2[], float vR[]) {
  vR[0] =   ( (v1[1] * v2[2]) - (v1[2] * v2[1]) );
  vR[1] = - ( (v1[0] * v2[2]) - (v1[2] * v2[0]) );
  vR[2] =   ( (v1[0] * v2[1]) - (v1[1] * v2[0]) );
}

void cross::normalize(float v1[], float vR[]) {
  float fMag;

  fMag = sqrt( pow(v1[0], 2) +
               pow(v1[1], 2) +
               pow(v1[2], 2)
             );

  vR[0] = v1[0] / fMag;
  vR[1] = v1[1] / fMag;
  vR[2] = v1[2] / fMag;
}

int main(void) {
  float vect1[3];
  float vect2[3];
  float vectResult[3];
  float vectNormal[3];

  vect1[0] = 3;
  vect1[1] = -3;
  vect1[2] = 1;

  vect2[0] = 4;
  vect2[1] = 9;
  vect2[2] = 2;

  cross c;

  c.crossProduct(vect1, vect2, vectResult);

  cout << fixed << setprecision(4);

  cout << "x: " << vectResult[0]
       << ", y: " << vectResult[1]
       << ", z: " << vectResult[2]
       << endl; 

  c.normalize(vectResult, vectNormal);

  cout << "x: " << vectNormal[0]
       << ", y: " << vectNormal[1]
       << ", z: " << vectNormal[2]
       << endl; 

  return 0;
}

# g++ cross.cpp -o cross
# ./cross > out.txt

C Sharp

# vi Cross.cs

using System;

public class Cross {

  void crossProduct(float[] v1, float[] v2, float[] vR) {
    vR[0] =   ( (v1[1] * v2[2]) - (v1[2] * v2[1]) );
    vR[1] = - ( (v1[0] * v2[2]) - (v1[2] * v2[0]) );
    vR[2] =   ( (v1[0] * v2[1]) - (v1[1] * v2[0]) );
  }

  void normalize(float[] v1, float[] vR) {
    float fMag;

    fMag = (float) Math.Sqrt( Math.Pow(v1[0], 2) +
                              Math.Pow(v1[1], 2) +
                              Math.Pow(v1[2], 2)
                            );

    vR[0] = v1[0] / fMag;
    vR[1] = v1[1] / fMag;
    vR[2] = v1[2] / fMag;
  }

  public static void Main() {
    float[] vect1 = new float[3];
    float[] vect2 = new float[3];
    float[] vectResult = new float[3];
    float[] vectNormal = new float[3];

    vect1[0] = 3;
    vect1[1] = -3;
    vect1[2] = 1;

    vect2[0] = 4;
    vect2[1] = 9;
    vect2[2] = 2;

    Cross c = new Cross();

    c.crossProduct(vect1, vect2, vectResult);

    System.Console.WriteLine("x: " + vectResult[0].ToString("0.0000") +
                             ", y: " + vectResult[1].ToString("0.0000") +
                             ", z: " + vectResult[2].ToString("0.0000")
                            );

    c.normalize(vectResult, vectNormal);

    System.Console.WriteLine("x: " + vectNormal[0].ToString("0.0000") +
                             ", y: " + vectNormal[1].ToString("0.0000") +
                             ", z: " + vectNormal[2].ToString("0.0000")
                            );

  }
}

# gmcs Cross.cs
# mono Cross.exe

Forth

# vi cross.fth

fvariable vect1 3 cells allot
fvariable vect2 3 cells allot
fvariable vectResult 3 cells allot
fvariable vectNormal 3 cells allot
fvariable fMag

: crossProduct 

  vect1 1 cells + @
  vect2 2 cells + @
  *

  vect1 2 cells + @
  vect2 1 cells + @
  *
-
vectResult 0 cells + ! 

    vect1 0 cells + @
    vect2 2 cells + @
    *

    vect1 2 cells + @
    vect2 0 cells + @
    *
  -
-1
*
vectResult 1 cells + ! 

  vect1 0 cells + @
  vect2 1 cells + @
  *

  vect1 1 cells + @
  vect2 0 cells + @
  *
-
vectResult 2 cells + ! 

;

3 vect1 0 cells + !
-3 vect1 1 cells + !
1 vect1 2 cells + ! 

4 vect2 0 cells + !
9 vect2 1 cells + !
2 vect2 2 cells + ! 

crossProduct

." x: "
vectResult 0 cells + @ .
." , y: "
vectResult 1 cells + @ .
." , z: "
vectResult 2 cells + @ .
cr

# gforth cross.fth

Note:  Normalize not implemented, since crossProduct was implemented with integers and the square root function requires everything in floats

Fortran

# vi cross.f

      program cross

      real vect1(3)
      real vect2(3)
      real vectResult(3)
      real vectNormal(3) 

      vect1(1) = 3
      vect1(2) = -3
      vect1(3) = 1

      vect2(1) = 4
      vect2(2) = 9
      vect2(3) = 2

      call crossProduct(vect1, vect2, vectResult)

      write(*, 100) vectResult(1), vectResult(2), vectResult(3)

      call normalize(vectResult, vectNormal)

      write(*, 100) vectNormal(1), vectNormal(2), vectNormal(3)

 100  format('x: ', F0.4, ', y: ', F0.4, ', z: ', F0.4)

      stop
      end

      subroutine crossProduct(v1, v2, vR)
      real v1(3)
      real v2(3)
      real vR(3) 

      vR(1) =   ( (v1(2) * v2(3)) - (v1(3) * v2(2)) )
      vR(2) = - ( (v1(1) * v2(3)) - (v1(3) * v2(1)) )
      vR(3) =   ( (v1(1) * v2(2)) - (v1(2) * v2(1)) )  

      end  

      subroutine normalize(v1, vR)
      real v1(3)
      real vR(3) 

      real fMag

      fMag = sqrt( (v1(1) ** 2) + (v1(2) ** 2) + (v1(3) ** 2) )

      vR(1) = v1(1) / fMag
      vR(2) = v1(2) / fMag
      vR(3) = v1(3) / fMag 

      end

# gfortran cross.f -o cross
# ./cross

Java

# vi Cross.java

import java.text.DecimalFormat;

public class Cross {

  public Cross() {

  }

  public void crossProduct(float v1[], float v2[], float vR[]) {
    vR[0] =   ( (v1[1] * v2[2]) - (v1[2] * v2[1]) );
    vR[1] = - ( (v1[0] * v2[2]) - (v1[2] * v2[0]) );
    vR[2] =   ( (v1[0] * v2[1]) - (v1[1] * v2[0]) );
  }

  public void normalize(float v1[], float vR[]) {
    float fMag;

    fMag = (float) Math.sqrt( Math.pow(v1[0], 2) +
                              Math.pow(v1[1], 2) +
                              Math.pow(v1[2], 2)
                            ); 

    vR[0] = v1[0] / fMag;
    vR[1] = v1[1] / fMag;
    vR[2] = v1[2] / fMag;
  }

  public static void main(String args[]) {
    float[] vect1 = new float[3];
    float[] vect2 = new float[3];
    float[] vectResult = new float[3];
    float[] vectNormal = new float[3];

    vect1[0] = 3;
    vect1[1] = -3;
    vect1[2] = 1;

    vect2[0] = 4;
    vect2[1] = 9;
    vect2[2] = 2;

    Cross c = new Cross();

    c.crossProduct(vect1, vect2, vectResult);

    DecimalFormat df = new DecimalFormat("0.0000");
    System.out.println("x: " + df.format(vectResult[0]) +
                       ", y: " + df.format(vectResult[1]) +
                       ", z: " + df.format(vectResult[2]));

    c.normalize(vectResult, vectNormal);
    System.out.println("x: " + df.format(vectNormal[0]) +
                       ", y: " + df.format(vectNormal[1]) +
                       ", z: " + df.format(vectNormal[2]));

  }
}

# javac *.java
# java Cross

Javascript (Rhino)

# vi cross.js

function crossProduct(v1, v2, vR) {
  vR[0] =   ( (v1[1] * v2[2]) - (v1[2] * v2[1]) );
  vR[1] = - ( (v1[0] * v2[2]) - (v1[2] * v2[0]) );
  vR[2] =   ( (v1[0] * v2[1]) - (v1[1] * v2[0]) );
}

function normalize(v1, vR) {
  var fMag = Math.sqrt( Math.pow(v1[0], 2) +
                        Math.pow(v1[1], 2) +
                        Math.pow(v1[2], 2)
                      );

  vR[0] = v1[0] / fMag;
  vR[1] = v1[1] / fMag;
  vR[2] = v1[2] / fMag;

}

var vect1 = new Array(3);
var vect2 = new Array(3);
var vectResult = new Array(3);
var vectNormal = new Array(3);

vect1[0] = 3;
vect1[1] = -3;
vect1[2] = 1;

vect2[0] = 4;
vect2[1] = 9;
vect2[2] = 2;

crossProduct(vect1, vect2, vectResult);
print("x: " + vectResult[0].toFixed(4) +
      ", y: " + vectResult[1].toFixed(4) +
      ", z: " + vectResult[2].toFixed(4));

normalize(vectResult, vectNormal);
print("x: " + vectNormal[0].toFixed(4) +
      ", y: " + vectNormal[1].toFixed(4) +
      ", z: " + vectNormal[2].toFixed(4));

# js -f cross.js

LISP (GNU)

# vi cross.lisp

(defun crossProduct(v1 v2 vR)

  (setf (nth 0 vR)
    (-
      (* (nth 1 v1) (nth 2 v2))
      (* (nth 2 v1) (nth 1 v2))
    )
  )

  (setf (nth 1 vR)
    (*
      -1
      (-
        (* (nth 0 v1) (nth 2 v2))
        (* (nth 2 v1) (nth 0 v2))
      )
    )
  )

  (setf (nth 2 vR)
    (-
      (* (nth 0 v1) (nth 1 v2))
      (* (nth 1 v1) (nth 0 v2))
    )
  )

)

(defun normalize(v1 vR)
  (setf fMag
    (sqrt
      (+
        (expt (nth 0 v1) 2)
        (expt (nth 1 v1) 2)
        (expt (nth 2 v1) 2)
      )
    )
  )

  (setf (nth 0 vR)
    (/ (nth 0 v1) fMag)
  )

  (setf (nth 1 vR)
    (/ (nth 1 v1) fMag)
  )

  (setf (nth 2 vR)
    (/ (nth 2 v1) fMag)
  )

)

(set 'vect1 '(3 -3 1))
(set 'vect2 '(4 9 2))
(set 'vectResult '(nil nil nil))
(set 'vectNormal '(nil nil nil))

(crossProduct vect1 vect2 vectResult)
(format t "x: ~,4f, y: ~,4f, z: ~,4f~%"
          (nth 0 vectResult) (nth 1 vectResult) (nth 2 vectResult))

(normalize vectResult vectNormal)
(format t "x: ~,4f, y: ~,4f, z: ~,4f~%"
          (nth 0 vectNormal) (nth 1 vectNormal) (nth 2 vectNormal))

(quit)

# gcl -load cross.lisp

Lua

# vi cross.lua

function crossProduct(v1, v2, vR)
    vR[0] =   ( (v1[1] * v2[2]) - (v1[2] * v2[1]) )
    vR[1] = - ( (v1[0] * v2[2]) - (v1[2] * v2[0]) )
    vR[2] =   ( (v1[0] * v2[1]) - (v1[1] * v2[0]) )
end

function normalize(v1, vR)
    fMag = math.sqrt( math.pow(v1[0], 2) +
                      math.pow(v1[1], 2) +
                      math.pow(v1[2], 2)
                    )

    vR[0] = v1[0] / fMag
    vR[1] = v1[1] / fMag
    vR[2] = v1[2] / fMag

end

vect1 = {}
vect2 = {}
vectResult = {}
vectNormal = {}

vect1[0] = 3
vect1[1] = -3
vect1[2] = 1 

vect2[0] = 4
vect2[1] = 9
vect2[2] = 2 

crossProduct(vect1, vect2, vectResult)
print(string.format("x: %.4f, y: %.4f, z: %.4f",
                    vectResult[0], vectResult[1], vectResult[2]))

normalize(vectResult, vectNormal)
print(string.format("x: %.4f, y: %.4f, z: %.4f",
                    vectNormal[0], vectNormal[1], vectNormal[2]))

# lua cross.lua

Objective C

# vi Cross.m

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

@interface Cross : Object {
}

-(void) crossProduct:(float[3]) v1 and:(float[3]) v2 result:(float[3]) vR;
-(void) normalize:(float[3]) v1 result:(float[3]) vR;
@end

@implementation Cross : Object
-(void) crossProduct:(float[3]) v1 and:(float[3]) v2 result:(float[3]) vR {
  vR[0] =   ( (v1[1] * v2[2]) - (v1[2] * v2[1]) );
  vR[1] = - ( (v1[0] * v2[2]) - (v1[2] * v2[0]) );
  vR[2] =   ( (v1[0] * v2[1]) - (v1[1] * v2[0]) );

}

-(void) normalize:(float[3]) v1 result:(float[3]) vR {
  float fMag;

  fMag = sqrt( pow(v1[0], 2) +
               pow(v1[1], 2) +
               pow(v1[2], 2)
             );

  vR[0] = v1[0] / fMag;
  vR[1] = v1[1] / fMag;
  vR[2] = v1[2] / fMag;
}

@end

int main(void) {
  float vect1[3];
  float vect2[3];
  float vectResult[3];
  float vectNormal[3];

  vect1[0] = 3;
  vect1[1] = -3;
  vect1[2] = 1;

  vect2[0] = 4;
  vect2[1] = 9;
  vect2[2] = 2;

  Cross *c = [Cross new];

  [c crossProduct: vect1 and: vect2 result: vectResult];
  printf("x: %.4f, y: %.4f, z: %.4f\n",
         vectResult[0], vectResult[1], vectResult[2]);

  [c normalize: vectResult result: vectNormal];
  printf("x: %.4f, y: %.4f, z: %.4f\n",
         vectNormal[0], vectNormal[1], vectNormal[2]);

}

# gcc -x objective-c -o cross Cross.m -lobjc -lm
# ./cross

Perl

# vi cross.pl

sub crossProduct {
  ($v1, $v2, $vR) = @_;

  $$vR[0] =   ( ($$v1[1] * $$v2[2]) - ($$v1[2] * $$v2[1]) );
  $$vR[1] = - ( ($$v1[0] * $$v2[2]) - ($$v1[2] * $$v2[0]) );
  $$vR[2] =   ( ($$v1[0] * $$v2[1]) - ($$v1[1] * $$v2[0]) ); 

}

sub normalize {
  ($v1, $vR) = @_;

  $fMag = sqrt( ($$v1[0] ** 2) +
                ($$v1[1] ** 2) +
                ($$v1[2] ** 2)
              );

  $$vR[0] = $$v1[0] / $fMag;
  $$vR[1] = $$v1[1] / $fMag;
  $$vR[2] = $$v1[2] / $fMag;
} 

@vect1;
@vect2;
@vectResult;
@vectNormal;

$vect1[0] = 3;
$vect1[1] = -3;
$vect1[2] = 1;

$vect2[0] = 4;
$vect2[1] = 9;
$vect2[2] = 2;

crossProduct( \@vect1, \@vect2, \@vectResult);
printf("x: %.4f, y: %.4f, z: %.4f\n", $vectResult[0],
       $vectResult[1], $vectResult[2]); 

normalize( \@vectResult, \@vectNormal);
printf("x: %.4f, y: %.4f, z: %.4f\n", $vectNormal[0],
       $vectNormal[1], $vectNormal[2]);

# perl cross.pl

PHP

# vi cross.php

<?php

  function crossProduct(&$v1, &$v2, &$vR) {
    $vR[0] =   ( ($v1[1] * $v2[2]) - ($v1[2] * $v2[1]) );
    $vR[1] = - ( ($v1[0] * $v2[2]) - ($v1[2] * $v2[0]) );
    $vR[2] =   ( ($v1[0] * $v2[1]) - ($v1[1] * $v2[0]) );
  }

  function normalize(&$v1, &$vR) {
    $fMag = sqrt( (pow($v1[0], 2)) +
                  (pow($v1[1], 2)) +
                  (pow($v1[2], 2))
                );

    $vR[0] = $v1[0] / $fMag;
    $vR[1] = $v1[1] / $fMag;
    $vR[2] = $v1[2] / $fMag;

  }

  $vect1 = array(null, null, null);
  $vect2 = array(null, null, null);
  $vectResult = array(null, null, null);
  $vectNormal = array(null, null, null);

  $vect1[0] = 3;
  $vect1[1] = -3;
  $vect1[2] = 1;

  $vect2[0] = 4;
  $vect2[1] = 9;
  $vect2[2] = 2;

  crossProduct($vect1, $vect2, $vectResult);

  echo "x: " . number_format($vectResult[0], 4) .
       ", y: " . number_format($vectResult[1], 4) .
       ", z: " . number_format($vectResult[2], 4) .
       "\n";

  normalize($vectResult, $vectNormal);

  echo "x: " . number_format($vectNormal[0], 4) .
       ", y: " . number_format($vectNormal[1], 4) .
       ", z: " . number_format($vectNormal[2], 4) .
       "\n";

?>

# php cross.php

Python

# vi cross.py

import math

def crossProduct(v1, v2, vR):
  vR[0] =   ( (v1[1] * v2[2]) - (v1[2] * v2[1]) )
  vR[1] = - ( (v1[0] * v2[2]) - (v1[2] * v2[0]) )
  vR[2] =   ( (v1[0] * v2[1]) - (v1[1] * v2[0]) )

def normalize(v1, vR):
  fMag = math.sqrt( (v1[0] ** 2) + (v1[1] ** 2) + (v1[2] ** 2) )
  vR[0] = v1[0] / fMag
  vR[1] = v1[1] / fMag
  vR[2] = v1[2] / fMag

vect1 = [ None, None, None ]
vect2 = [ None, None, None ]
vectResult = [ None, None, None ]
vectNormal = [ None, None, None ]

vect1[0] = 3
vect1[1] = -3
vect1[2] = 1 

vect2[0] = 4
vect2[1] = 9
vect2[2] = 2

crossProduct(vect1, vect2, vectResult)

print "x: " + ("%.4f" % vectResult[0]) + \
      ", y: " + ("%.4f" % vectResult[1]) + \
      ", z: " + ("%.4f" % vectResult[2]) 

normalize(vectResult, vectNormal)

print "x: " + ("%.4f" % vectNormal[0]) + \
      ", y: " + ("%.4f" % vectNormal[1]) + \
      ", z: " + ("%.4f" % vectNormal[2])

# python cross.py

Ruby

# vi cross.rb

class Cross

  def crossProduct(v1, v2, vR)
    vR[0] =   ( (v1[1] * v2[2]) - (v1[2] * v2[1]) )
    vR[1] = - ( (v1[0] * v2[2]) - (v1[2] * v2[0]) )
    vR[2] =   ( (v1[0] * v2[1]) - (v1[1] * v2[0]) )
  end

  def normalize(v1, vR)
    fMag = Math.sqrt( (v1[0] ** 2) +
                      (v1[1] ** 2) +
                      (v1[2] ** 2)
                    )

    vR[0] = v1[0] / fMag
    vR[1] = v1[1] / fMag
    vR[2] = v1[2] / fMag
  end

end

vect1 = Array.new
vect2 = Array.new
vectResult = Array.new
vectNormal = Array.new

vect1[0] = 3
vect1[1] = -3
vect1[2] = 1 

vect2[0] = 4
vect2[1] = 9
vect2[2] = 2 

c = Cross.new()

c.crossProduct(vect1, vect2, vectResult)
printf("x: %.4f, y: %.4f, z: %.4f\n", vectResult[0],
       vectResult[1], vectResult[2]) 

c.normalize(vectResult, vectNormal)
printf("x: %.4f, y: %.4f, z: %.4f\n", vectNormal[0],
       vectNormal[1], vectNormal[2])

# ruby cross.rb

Scala

# vi Cross.scala

object Cross {

  def crossProduct(v1: Array[Float], v2: Array[Float], vR: Array[Float]) = {
    vR(0) =   ( (v1(1) * v2(2)) - (v1(2) * v2(1)) )
    vR(1) = - ( (v1(0) * v2(2)) - (v1(2) * v2(0)) )
    vR(2) =   ( (v1(0) * v2(1)) - (v1(1) * v2(0)) )
  }

  def normalize(v1: Array[Float], vR: Array[Float]) = {
    var fMag = (Math.sqrt( Math.pow(v1(0), 2) +
                          Math.pow(v1(1), 2) +
                          Math.pow(v1(2), 2)
                        )
               ).toFloat

    vR(0) = v1(0) / fMag
    vR(1) = v1(1) / fMag
    vR(2) = v1(2) / fMag
  }

  def main(args: Array[String]) {
    var vect1 = new Array[Float](3)
    var vect2 = new Array[Float](3)
    var vectResult = new Array[Float](3)
    var vectNormal = new Array[Float](3)

    vect1(0) = 3
    vect1(1) = -3
    vect1(2) =1 

    vect2(0) = 4
    vect2(1) = 9
    vect2(2) = 2 

    this.crossProduct(vect1, vect2, vectResult)
    printf("x: %.4f, y: %.4f, z: %.4f\n", vectResult(0),
           vectResult(1), vectResult(2));

    this.normalize(vectResult, vectNormal)
    printf("x: %.4f, y: %.4f, z: %.4f\n", vectNormal(0),
           vectNormal(1), vectNormal(2));
  }
}

# scalac Cross.scala
# scala Cross

Scheme (GNU/MIT)

# vi cross.scm

(define (crossProduct v1 v2 vR)

  (vector-set! vR 0
    (-
      (* (vector-ref v1 1) (vector-ref v2 2))
      (* (vector-ref v1 2) (vector-ref v2 1))
    )
  ) 

  (vector-set! vR 1
    (*
     -1
      (-
        (* (vector-ref v1 0) (vector-ref v2 2))
        (* (vector-ref v1 2) (vector-ref v2 0))
      )
    )
  ) 

  (vector-set! vR 2
    (-
      (* (vector-ref v1 0) (vector-ref v2 1))
      (* (vector-ref v1 1) (vector-ref v2 0))
    )
  ) 

)

(define (normalize v1 vR)
  (define fMag)
  (set! fMag
    (sqrt
      (+
        (expt (vector-ref v1 0) 2)
        (expt (vector-ref v1 1) 2)
        (expt (vector-ref v1 2) 2)
      )
    )
  )

  (vector-set! vR 0
    (/
      (vector-ref v1 0)
      fMag
    )
  ) 

  (vector-set! vR 1
    (/
      (vector-ref v1 1)
      fMag
    )
  ) 

  (vector-set! vR 2
    (/
      (vector-ref v1 2)
      fMag
    )
  ) 

)

(define vect1 #(3 -3 1))
(define vect2 #(4 9 2))
(define vectResult #(null null null))
(define vectNormal #(null null null))

(newline)

(crossProduct vect1 vect2 vectResult)
(display "x: ")(display (vector-ref vectResult 0))
(display ", y: ")(display (vector-ref vectResult 1))
(display ", z: ")(display (vector-ref vectResult 2))
(newline)

(normalize vectResult vectNormal)
(display "x: ")(display (vector-ref vectNormal 0))
(display ", y: ")(display (vector-ref vectNormal 1))
(display ", z: ")(display (vector-ref vectNormal 2))
(newline)

# scheme –load cross.scm

Smalltalk (Squeak)

crossProduct: v1 and: v2 result: vR

  vR at: 1 put: ( ((v1 at: 2) * (v2 at: 3)) - ((v1 at: 3) * (v2 at: 2)) ).
  vR at: 2 put: ( ((v1 at: 1) * (v2 at: 3)) - ((v1 at: 3) * (v2 at: 1)) ).
  vR at: 3 put: ( ((v1 at: 1) * (v2 at: 2)) - ((v1 at: 2) * (v2 at: 1)) ).

normalize: v1 result: vR
  | fMag |

  fMag := ( ((v1 at: 1) raisedTo: 2) +
              ((v1 at: 2) raisedTo: 2) +
              ((v1 at: 3) raisedTo: 2)
            ) sqrt.

  vR at: 1 put: ((v1 at: 1) / fMag).
  vR at: 2 put: ((v1 at: 2) / fMag).
  vR at: 3 put: ((v1 at: 3) / fMag).

| vect1 vect2 vectResult vectNormal c |

vect1 := Array new: 3.
vect2 := Array new: 3.
vectResult := Array new: 3.
vectNormal := Array new: 3.

vect1 at: 1 put: 3.
vect1 at: 2 put: -3.
vect1 at: 3 put: 1.

vect2 at: 1 put: 4.
vect2 at: 2 put: 9.
vect2 at: 3 put: 2.

c := Cross new.
c crossProduct: vect1 and: vect2 result: vectResult.

Transcript show: 'x: '.
Transcript show: ((vectResult at: 1) roundTo: 0.0001).
Transcript show: ', y: '.
Transcript show: ((vectResult at: 2) roundTo: 0.0001).
Transcript show: ', z: '.
Transcript show: ((vectResult at: 3) roundTo: 0.0001).
Transcript cr.

c normalize: vectResult result: vectNormal.

Transcript show: 'x: '.
Transcript show: ((vectNormal at: 1) roundTo: 0.0001).
Transcript show: ', y: '.
Transcript show: ((vectNormal at: 2) roundTo: 0.0001).
Transcript show: ', z: '.
Transcript show: ((vectNormal at: 3) roundTo: 0.0001).
Transcript cr.

Note:  Must be entered into the Squeak environment.  Add the two methods to a class, and then paste the commands in a Transcript windows, select the text, and then “Do-It”

Tcl

# vi cross.tcl

proc crossProduct { v1p v2p vRp } {
  upvar $v1p v1
  upvar $v2p v2
  upvar $vRp vR

  set vR(0) [expr {  ( ($v1(1) * $v2(2)) - ($v1(2) * $v2(1)) ) }]
  set vR(1) [expr { -( ($v1(0) * $v2(2)) - ($v1(2) * $v2(0)) ) }]
  set vR(2) [expr {  ( ($v1(0) * $v2(1)) - ($v1(1) * $v2(0)) ) }]
}

proc normalize { v1p vRp } {
  upvar $v1p v1
  upvar $vRp vR

  set fMag [expr { sqrt( pow($v1(0), 2) + pow($v1(1), 2) + pow($v1(2), 2) ) }]

  set vR(0) [expr { $v1(0) / $fMag }]
  set vR(1) [expr { $v1(1) / $fMag }]
  set vR(2) [expr { $v1(2) / $fMag }]
}

array set vect1 { }
array set vect2 { }
array set vectResult { }
array set vectNormal { }

set vect1(0) 3
set vect1(1) -3
set vect1(2) 1

set vect2(0) 4
set vect2(1) 9
set vect2(2) 2

crossProduct vect1 vect2 vectResult

puts [format "x: %.4f, y: %.4f, z: %.4f" \
      $vectResult(0) $vectResult(1) $vectResult(2) ]

normalize vectResult vectNormal

puts [format "x: %.4f, y: %.4f, z: %.4f" \
      $vectNormal(0) $vectNormal(1) $vectNormal(2) ]

# tclsh cross.tcl

Output

x: -15.0000, y: -2.0000, z: 39.0000
x: -0.3586, y: -0.0478, z: 0.9323
Advertisements

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

Fibonacci in Twelve Languages

Displaying the first 22 fibonacci numbers in twelve programming languages that are available in Ubuntu Linux 11.04.  This code is non-recursive.

C

# vi fib.c

#include <stdio.h>

int main(void) {
  int iCount;

  int a;
  int b;
  int c;

  iCount = 0;
  a = 0;
  b = 1;

  printf("%d\n", a);
  printf("%d\n", b);

  while (iCount < 20) {
    c = a + b;
    printf("%d\n", c);
    a = b;
    b = c;
    iCount++;
  }

  return 0;
}

# gcc fib.c -o fib

# ./fib

C++

# vi fib.cpp

#include <iostream>
using namespace std;

int main(void) {
  int iCount;
  int a;
  int b;
  int c;

  iCount = 0;
  a = 0;
  b = 1;

  cout << a << endl;
  cout << b << endl;

  while (iCount < 20) {
    c = a + b;
    cout << c << endl;
    a = b;
    b = c;
    iCount++;
  }

  return 0;
}

# g++ fib.cpp -o fib

# ./fib

Java

# vi Fib.java

public class Fib {

  public Fib() {
    int iCount;

    int a;
    int b;
    int c;

    iCount = 0;
    a = 0;
    b = 1;

    System.out.println(a + "");
    System.out.println(b + ""); 

    while (iCount < 20) {
      c = a + b;
      System.out.println(c + "");
      a = b;
      b = c;
      iCount++;
    }
  }

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

# javac Fib.java

# java Fib

Ruby

# vi fib.rb

a = 0
b = 1
iCount = 0

puts "#{a}"
puts "#{b}"

while (iCount < 20)
  c = a + b
  puts "#{c}"
  a = b;
  b = c;
  iCount += 1

end

# ruby fib.rb

Perl

# vi fib.pl

$a = 0;
$b = 1;
$iCount = 0;

print $a . "\n";
print $b . "\n";

while ($iCount < 20) {
  $c = $a + $b;
  print $c . "\n";
  $a = $b;
  $b = $c;
  $iCount++;
}

# perl fib.pl

SmallTalk (Squeak)

| a b c iCount |

a := 0.
b := 1.
iCount := 0.

Transcript show: a.
Transcript cr.
Transcript show: b.
Transcript cr.

[iCount < 20] whileTrue: [
  c := a + b.
  Transcript show: c.
  Transcript cr.
  a := b.
  b := c.
  iCount := iCount + 1.
]

Python

# vi fib.py

a = 0
b = 1
iCount = 0

print a
print b

while iCount < 20:
  c = a + b
  print c
  a = b
  b = c
  iCount += 1

# python fib.py

FORTRAN 77

# vi fib.f

      program fib
      integer a, b, c, iCount

      a = 0
      b = 1

      write(*, *) a
      write(*, *) b

      iCount = 0

      do iCount=1,20
        c = a + b
        write(*, *) c
        a = b
        b = c
      end do

      stop
      end

# f77 fib.f -o fib

# gfortran fib.f -o fib

# ./fib

Scheme

# vi fib.scm

(define a 0)
(define b 1)
(display a) (newline)
(display b) (newline)
(define c 0)
(let loop ((iCount 1))
  (if (<= iCount 20)
      (begin
        (set! c (+ a b))
        (display c) (newline)
        (set! a b)
        (set! b c)
        (loop (+ iCount 1)))))

# scheme –load fib.scm

Scala

# vi Fib.scala

object Fib {

  def display() = {
    var a = 0
    var b = 1
    var c = 0

    println(a)
    println(b)

    var iCount = 0

    while (iCount < 20){
      c = a + b
      println(c )
      a = b
      b = c
      iCount += 1
    }

  }

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

# scalac Fib.scala

# scala Fib

PHP

# vi fib.php

<?php
$a = 0;
$b = 1;

echo $a . "\n";
echo $b . "\n";

$iCount = 0;
while ($iCount < 20) {
  $c = $a + $b;
  echo $c . "\n";
  $a = $b;
  $b = $c;
  $iCount++;
}

?>

# php fib.php

bash script

# vi fib.sh

#!/bin/bash
a=0
b=1

echo $a
echo $b

iCount=0

while [ $iCount -lt 20 ]
do
  c=$(( b + a ))
  echo $c
  a=$(( b ))
  b=$(( c ))
  (( iCount++ ))

done

# chmod u+x fib.sh

# ./fib.sh

Output

0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946