This commit is contained in:
Ingy döt Net 2013-04-10 15:42:53 -07:00
parent 051504d65b
commit 0457928c3e
295 changed files with 3588 additions and 3 deletions

View file

@ -0,0 +1,11 @@
a=zeros(1,100);
for b=1:100;
for i=b:b:100;
if a(i)==1
a(i)=0;
else
a(i)=1;
end
end
end
a

View file

@ -0,0 +1,6 @@
for x=1:100;
if sqrt(x) == floor(sqrt(x))
a(i)=1;
end
end
a

View file

@ -0,0 +1,5 @@
a = zeros(100,1);
for counter = 1:sqrt(100);
a(counter^2) = 1;
end
a

View file

@ -0,0 +1,15 @@
function [doors,opened,closed] = hundredDoors()
%Initialize the doors, make them booleans for easy vectorization
doors = logical( (1:1:100) );
%Go through the flipping process, ignore the 1 case because the doors
%array is already initialized to all open
for initialPosition = (2:100)
doors(initialPosition:initialPosition:100) = not( doors(initialPosition:initialPosition:100) );
end
opened = find(doors); %Stores the numbers of the open doors
closed = find( not(doors) ); %Stores the numbers of the closed doors
end

View file

@ -0,0 +1,3 @@
doors((1:10).^2) = 1;
doors

View file

@ -0,0 +1,27 @@
function twentyfour()
N = 4;
n = ceil(rand(1,N)*9);
printf('Generate a equation with the numbers %i, %i, %i, %i and +, -, *, /, () operators ! \n',n);
s = input(': ','s');
t = s;
for k = 1:N,
[x,t] = strtok(t,'+-*/() \t');
if length(x)~=1,
error('invalid sign %s\n',x);
end;
y = x-'0';
if ~(0 < y & y < 10)
error('invalid sign %s\n',x);
end;
z(1,k) = y;
end;
if any(sort(z)-sort(n))
error('numbers do not match.\n');
end;
val = eval(s);
if val==24,
fprintf('expression "%s" results in %i.\n',s,val);
else
fprintf('expression "%s" does not result in 24 but %i.\n',s,val);
end;

View file

@ -0,0 +1,11 @@
function ninetyNineBottlesOfBeer()
disp( [ sprintf(['%d bottles of beer on the wall, %d bottles of beer.\n'...
'Take one down, pass it around...\n'],[(99:-1:2);(99:-1:2)])...
sprintf(['1 bottle of beer on the wall, 1 bottle of beer.\nTake'...
'one down, pass it around;\nNo more bottles of beer on the wall.']) ] );
%The end of this song makes me sad. The shelf should always have more
%beer...like college.
end

8
Task/A+B/MATLAB/a+b.m Normal file
View file

@ -0,0 +1,8 @@
function sumOfInputs = APlusB()
inputStream = input('Enter two numbers, separated by a space: ', 's');
numbers = str2num(inputStream); %#ok<ST2NM>
if any(numbers < -1000 | numbers > 1000)
warning('APlusB:OutOfRange', 'Some numbers are outside the range');
end
sumOfInputs = sum(numbers);
end

View file

@ -0,0 +1,9 @@
function A = ackermannFunction(m,n)
if m == 0
A = n+1;
elseif (m > 0) && (n == 0)
A = ackermannFunction(m-1,1);
else
A = ackermannFunction( m-1,ackermannFunction(m,n-1) );
end
end

View file

@ -0,0 +1,3 @@
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a [[wp:Pendulum|simple gravity pendulum]].
For this task, create a simple physical model of a pendulum and animate it.

View file

@ -0,0 +1,4 @@
---
note: Temporal media
requires:
- Graphics

View file

@ -0,0 +1,19 @@
generic
type Float_Type is digits <>;
Gravitation : Float_Type;
package Pendulums is
type Pendulum is private;
function New_Pendulum (Length : Float_Type;
Theta0 : Float_Type) return Pendulum;
function Get_X (From : Pendulum) return Float_Type;
function Get_Y (From : Pendulum) return Float_Type;
procedure Update_Pendulum (Item : in out Pendulum; Time : in Duration);
private
type Pendulum is record
Length : Float_Type;
Theta : Float_Type;
X : Float_Type;
Y : Float_Type;
Velocity : Float_Type;
end record;
end Pendulums;

View file

@ -0,0 +1,38 @@
with Ada.Numerics.Generic_Elementary_Functions;
package body Pendulums is
package Math is new Ada.Numerics.Generic_Elementary_Functions (Float_Type);
function New_Pendulum (Length : Float_Type;
Theta0 : Float_Type) return Pendulum is
Result : Pendulum;
begin
Result.Length := Length;
Result.Theta := Theta0 / 180.0 * Ada.Numerics.Pi;
Result.X := Math.Sin (Theta0) * Length;
Result.Y := Math.Cos (Theta0) * Length;
Result.Velocity := 0.0;
return Result;
end New_Pendulum;
function Get_X (From : Pendulum) return Float_Type is
begin
return From.X;
end Get_X;
function Get_Y (From : Pendulum) return Float_Type is
begin
return From.Y;
end Get_Y;
procedure Update_Pendulum (Item : in out Pendulum; Time : in Duration) is
Acceleration : constant Float_Type := Gravitation / Item.Length *
Math.Sin (Item.Theta);
begin
Item.X := Math.Sin (Item.Theta) * Item.Length;
Item.Y := Math.Cos (Item.Theta) * Item.Length;
Item.Velocity := Item.Velocity +
Acceleration * Float_Type (Time);
Item.Theta := Item.Theta +
Item.Velocity * Float_Type (Time);
end Update_Pendulum;
end Pendulums;

View file

@ -0,0 +1,24 @@
with Ada.Text_IO;
with Ada.Calendar;
with Pendulums;
procedure Main is
package Float_Pendulum is new Pendulums (Float, -9.81);
use Float_Pendulum;
use type Ada.Calendar.Time;
My_Pendulum : Pendulum := New_Pendulum (10.0, 30.0);
Now, Before : Ada.Calendar.Time;
begin
Before := Ada.Calendar.Clock;
loop
Delay 0.1;
Now := Ada.Calendar.Clock;
Update_Pendulum (My_Pendulum, Now - Before);
Before := Now;
-- output positions relative to origin
-- replace with graphical output if wanted
Ada.Text_IO.Put_Line (" X: " & Float'Image (Get_X (My_Pendulum)) &
" Y: " & Float'Image (Get_Y (My_Pendulum)));
end loop;
end Main;

View file

@ -0,0 +1,77 @@
#include <stdlib.h>
#include <math.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <sys/time.h>
#define length 5
#define g 9.8
double alpha, accl, omega = 0, E;
struct timeval tv;
double elappsed() {
struct timeval now;
gettimeofday(&now, 0);
int ret = (now.tv_sec - tv.tv_sec) * 1000000
+ now.tv_usec - tv.tv_usec;
tv = now;
return ret / 1.e6;
}
void resize(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glOrtho(0, w, h, 0, -1, 1);
}
void render()
{
double x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);
resize(640, 320);
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINES);
glVertex2d(320, 0);
glVertex2d(x, y);
glEnd();
glFlush();
double us = elappsed();
alpha += (omega + us * accl / 2) * us;
omega += accl * us;
/* don't let precision error go out of hand */
if (length * g * (1 - cos(alpha)) >= E) {
alpha = (alpha < 0 ? -1 : 1) * acos(1 - E / length / g);
omega = 0;
}
accl = -g / length * sin(alpha);
}
void init_gfx(int *c, char **v)
{
glutInit(c, v);
glutInitDisplayMode(GLUT_RGB);
glutInitWindowSize(640, 320);
glutIdleFunc(render);
glutCreateWindow("Pendulum");
}
int main(int c, char **v)
{
alpha = 4 * atan2(1, 1) / 2.1;
E = length * g * (1 - cos(alpha));
accl = -g / length * sin(alpha);
omega = 0;
gettimeofday(&tv, 0);
init_gfx(&c, v);
glutMainLoop();
return 0;
}

View file

@ -0,0 +1,63 @@
(ns pendulum
(:import
(javax.swing JFrame)
(java.awt Canvas Graphics Color)))
(def length 200)
(def width (* 2 (+ 50 length)))
(def height (* 3 (/ length 2)))
(def dt 0.1)
(def g 9.812)
(def k (- (/ g length)))
(def anchor-x (/ width 2))
(def anchor-y (/ height 8))
(def angle (atom (/ (Math/PI) 2)))
(defn draw [#^Canvas canvas angle]
(let [buffer (.getBufferStrategy canvas)
g (.getDrawGraphics buffer)
ball-x (+ anchor-x (* (Math/sin angle) length))
ball-y (+ anchor-y (* (Math/cos angle) length))]
(try
(doto g
(.setColor Color/BLACK)
(.fillRect 0 0 width height)
(.setColor Color/RED)
(.drawLine anchor-x anchor-y ball-x ball-y)
(.setColor Color/YELLOW)
(.fillOval (- anchor-x 3) (- anchor-y 4) 7 7)
(.fillOval (- ball-x 7) (- ball-y 7) 14 14))
(finally (.dispose g)))
(if-not (.contentsLost buffer)
(.show buffer)) ))
(defn start-renderer [canvas]
(->>
(fn [] (draw canvas @angle) (recur))
(new Thread)
(.start)))
(defn -main [& args]
(let [frame (JFrame. "Pendulum")
canvas (Canvas.)]
(doto frame
(.setSize width height)
(.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
(.setResizable false)
(.add canvas)
(.setVisible true))
(doto canvas
(.createBufferStrategy 2)
(.setVisible true)
(.requestFocus))
(start-renderer canvas)
(loop [v 0]
(swap! angle #(+ % (* v dt)))
(Thread/sleep 15)
(recur (+ v (* k (Math/sin @angle) dt)))) ))
(-main)

View file

@ -0,0 +1,28 @@
import Graphics.HGL.Draw.Monad (Graphic, )
import Graphics.HGL.Draw.Picture
import Graphics.HGL.Utils
import Graphics.HGL.Window
import Graphics.HGL.Run
import Control.Exception (bracket, )
import Control.Arrow
toInt = fromIntegral.round
pendulum = runGraphics $
bracket
(openWindowEx "Pendulum animation task" Nothing (600,400) DoubleBuffered (Just 30))
closeWindow
(\w -> mapM_ ((\ g -> setGraphic w g >> getWindowTick w).
(\ (x, y) -> overGraphic (line (300, 0) (x, y))
(ellipse (x - 12, y + 12) (x + 12, y - 12)) )) pts)
where
dt = 1/30
t = - pi/4
l = 1
g = 9.812
nextAVT (a,v,t) = (a', v', t + v' * dt) where
a' = - (g / l) * sin t
v' = v + a' * dt
pts = map (\(_,t,_) -> (toInt.(300+).(300*).cos &&& toInt. (300*).sin) (pi/2+0.6*t) )
$ iterate nextAVT (- (g / l) * sin t, t, 0)

View file

@ -0,0 +1,52 @@
import java.awt.*;
import javax.swing.*;
public class Pendulum extends JPanel implements Runnable {
private double angle = Math.PI / 2;
private int length;
public Pendulum(int length) {
this.length = length;
setDoubleBuffered(true);
}
@Override
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
int anchorX = getWidth() / 2, anchorY = getHeight() / 4;
int ballX = anchorX + (int) (Math.sin(angle) * length);
int ballY = anchorY + (int) (Math.cos(angle) * length);
g.drawLine(anchorX, anchorY, ballX, ballY);
g.fillOval(anchorX - 3, anchorY - 4, 7, 7);
g.fillOval(ballX - 7, ballY - 7, 14, 14);
}
public void run() {
double angleAccel, angleVelocity = 0, dt = 0.1;
while (true) {
angleAccel = -9.81 / length * Math.sin(angle);
angleVelocity += angleAccel * dt;
angle += angleVelocity * dt;
repaint();
try { Thread.sleep(15); } catch (InterruptedException ex) {}
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(2 * length + 50, length / 2 * 3);
}
public static void main(String[] args) {
JFrame f = new JFrame("Pendulum");
Pendulum p = new Pendulum(200);
f.add(p);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
new Thread(p).start();
}
}

View file

@ -0,0 +1,58 @@
<html><head>
<title>Pendulum</title>
</head><body style="background: gray;">
<canvas id="canvas" width="600" height="600">
<p>Sorry, your browser does not support the &lt;canvas&gt; used to display the pendulum animation.</p>
</canvas>
<script>
function PendulumSim(length_m, gravity_mps2, initialAngle_rad, timestep_ms, callback) {
var velocity = 0;
var angle = initialAngle_rad;
var k = -gravity_mps2/length_m;
var timestep_s = timestep_ms / 1000;
return setInterval(function () {
var acceleration = k * Math.sin(angle);
velocity += acceleration * timestep_s;
angle += velocity * timestep_s;
callback(angle);
}, timestep_ms);
}
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var prev=0;
var sim = PendulumSim(1, 9.80665, Math.PI*99/100, 10, function (angle) {
var rPend = Math.min(canvas.width, canvas.height) * 0.47;
var rBall = Math.min(canvas.width, canvas.height) * 0.02;
var rBar = Math.min(canvas.width, canvas.height) * 0.005;
var ballX = Math.sin(angle) * rPend;
var ballY = Math.cos(angle) * rPend;
context.fillStyle = "rgba(255,255,255,0.51)";
context.globalCompositeOperation = "destination-out";
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "yellow";
context.strokeStyle = "rgba(0,0,0,"+Math.max(0,1-Math.abs(prev-angle)*10)+")";
context.globalCompositeOperation = "source-over";
context.save();
context.translate(canvas.width/2, canvas.height/2);
context.rotate(angle);
context.beginPath();
context.rect(-rBar, -rBar, rBar*2, rPend+rBar*2);
context.fill();
context.stroke();
context.beginPath();
context.arc(0, rPend, rBall, 0, Math.PI*2, false);
context.fill();
context.stroke();
context.restore();
prev=angle;
});
</script>
</body></html>

View file

@ -0,0 +1,66 @@
%This is a numerical simulation of a pendulum with a massless pivot arm.
%% User Defined Parameters
%Define external parameters
g = -9.8;
deltaTime = 1/50; %Decreasing this will increase simulation accuracy
endTime = 16;
%Define pendulum
rodPivotPoint = [2 2]; %rectangular coordinates
rodLength = 1;
mass = 1; %of the bob
radius = .2; %of the bob
theta = 45; %degrees, defines initial position of the bob
velocity = [0 0]; %cylindrical coordinates; first entry is radial velocity,
%second entry is angular velocity
%% Simulation
assert(radius < rodLength,'Pendulum bob radius must be less than the length of the rod.');
position = rodPivotPoint - (rodLength*[-sind(theta) cosd(theta)]); %in rectangular coordinates
%Generate graphics, render pendulum
figure;
axesHandle = gca;
xlim(axesHandle, [(rodPivotPoint(1) - rodLength - radius) (rodPivotPoint(1) + rodLength + radius)] );
ylim(axesHandle, [(rodPivotPoint(2) - rodLength - radius) (rodPivotPoint(2) + rodLength + radius)] );
rectHandle = rectangle('Position',[(position - radius/2) radius radius],...
'Curvature',[1,1],'FaceColor','g'); %Pendulum bob
hold on
plot(rodPivotPoint(1),rodPivotPoint(2),'^'); %pendulum pivot
lineHandle = line([rodPivotPoint(1) position(1)],...
[rodPivotPoint(2) position(2)]); %pendulum rod
hold off
%Run simulation, all calculations are performed in cylindrical coordinates
for time = (deltaTime:deltaTime:endTime)
drawnow; %Forces MATLAB to render the pendulum
%Find total force
gravitationalForceCylindrical = [mass*g*cosd(theta) mass*g*sind(theta)];
%This code is just incase you want to add more forces,e.g friction
totalForce = gravitationalForceCylindrical;
%If the rod isn't massless or is a spring, etc., modify this line
%accordingly
rodForce = [-totalForce(1) 0]; %cylindrical coordinates
totalForce = totalForce + rodForce;
acceleration = totalForce / mass; %F = ma
velocity = velocity + acceleration * deltaTime;
rodLength = rodLength + velocity(1) * deltaTime;
theta = theta + velocity(2) * deltaTime;
position = rodPivotPoint - (rodLength*[-sind(theta) cosd(theta)]);
%Update figure with new position info
set(rectHandle,'Position',[(position - radius/2) radius radius]);
set(lineHandle,'XData',[rodPivotPoint(1) position(1)],'YData',...
[rodPivotPoint(2) position(2)]);
end

View file

@ -0,0 +1,66 @@
use strict;
use warnings;
use Tk;
use Math::Trig qw/:pi/;
my $root = new MainWindow( -title => 'Pendulum Animation' );
my $canvas = $root->Canvas(-width => 320, -height => 200);
my $after_id;
for ($canvas) {
$_->createLine( 0, 25, 320, 25, -tags => [qw/plate/], -width => 2, -fill => 'grey50' );
$_->createOval( 155, 20, 165, 30, -tags => [qw/pivot outline/], -fill => 'grey50' );
$_->createLine( 1, 1, 1, 1, -tags => [qw/rod width/], -width => 3, -fill => 'black' );
$_->createOval( 1, 1, 2, 2, -tags => [qw/bob outline/], -fill => 'yellow' );
}
$canvas->raise('pivot');
$canvas->pack(-fill => 'both', -expand => 1);
my ($Theta, $dTheta, $length, $homeX, $homeY) =
(45, 0, 150, 160, 25);
sub show_pendulum {
my $angle = $Theta * pi() / 180;
my $x = $homeX + $length * sin($angle);
my $y = $homeY + $length * cos($angle);
$canvas->coords('rod', $homeX, $homeY, $x, $y);
$canvas->coords('bob', $x-15, $y-15, $x+15, $y+15);
}
sub recompute_angle {
my $scaling = 3000.0 / ($length ** 2);
# first estimate
my $firstDDTheta = -sin($Theta * pi / 180) * $scaling;
my $midDTheta = $dTheta + $firstDDTheta;
my $midTheta = $Theta + ($dTheta + $midDTheta)/2;
# second estimate
my $midDDTheta = -sin($midTheta * pi/ 180) * $scaling;
$midDTheta = $dTheta + ($firstDDTheta + $midDDTheta)/2;
$midTheta = $Theta + ($dTheta + $midDTheta)/2;
# again, first
$midDDTheta = -sin($midTheta * pi/ 180) * $scaling;
my $lastDTheta = $midDTheta + $midDDTheta;
my $lastTheta = $midTheta + ($midDTheta + $lastDTheta)/2;
# again, second
my $lastDDTheta = -sin($lastTheta * pi/180) * $scaling;
$lastDTheta = $midDTheta + ($midDDTheta + $lastDDTheta)/2;
$lastTheta = $midTheta + ($midDTheta + $lastDTheta)/2;
# Now put the values back in our globals
$dTheta = $lastDTheta;
$Theta = $lastTheta;
}
sub animate {
recompute_angle;
show_pendulum;
$after_id = $root->after(15 => sub {animate() });
}
show_pendulum;
$after_id = $root->after(500 => sub {animate});
$canvas->bind('<Destroy>' => sub {$after_id->cancel});
MainLoop;

View file

@ -0,0 +1,15 @@
(load "@lib/math.l")
(de pendulum (X Y Len)
(let (Angle pi/2 V 0)
(call 'clear)
(call 'tput "cup" Y X)
(prin '+)
(call 'tput "cup" 1 (+ X Len))
(until (key 25) # 25 ms
(let A (*/ (sin Angle) -9.81 1.0)
(inc 'V (*/ A 40)) # DT = 25 ms = 1/40 sec
(inc 'Angle (*/ V 40)) )
(call 'tput "cup"
(+ Y (*/ Len (cos Angle) 2.2)) # Compensate for aspect ratio
(+ X (*/ Len (sin Angle) 1.0)) ) ) ) )

View file

@ -0,0 +1 @@
(pendulum 40 1 36)

View file

@ -0,0 +1,80 @@
:- use_module(library(pce)).
pendulum :-
new(D, window('Pendulum')),
send(D, size, size(560, 300)),
new(Line, line(80, 50, 480, 50)),
send(D, display, Line),
new(Circle, circle(20)),
send(Circle, fill_pattern, colour(@default, 0, 0, 0)),
new(Boule, circle(60)),
send(Boule, fill_pattern, colour(@default, 0, 0, 0)),
send(D, display, Circle, point(270,40)),
send(Circle, handle, handle(h/2, w/2, in)),
send(Boule, handle, handle(h/2, w/2, out)),
send(Circle, connect, Boule, link(in, out, line(0,0,0,0,none))),
new(Anim, animation(D, 0.0, Boule, 200.0)),
send(D, done_message, and(message(Anim, free),
message(Boule, free),
message(Circle, free),
message(@receiver,destroy))),
send(Anim?mytimer, start),
send(D, open).
:- pce_begin_class(animation(window, angle, boule, len_pendulum), object).
variable(window, object, both, "Display window").
variable(boule, object, both, "bowl of the pendulum").
variable(len_pendulum, object, both, "len of the pendulum").
variable(angle, object, both, "angle with the horizontal").
variable(delta, object, both, "increment of the angle").
variable(mytimer, timer, both, "timer of the animation").
initialise(P, W:object, A:object, B : object, L:object) :->
"Creation of the object"::
send(P, window, W),
send(P, angle, A),
send(P, boule, B),
send(P, len_pendulum, L),
send(P, delta, 0.01),
send(P, mytimer, new(_, timer(0.01,message(P, anim_message)))).
% method called when the object is destroyed
% first the timer is stopped
% then all the resources are freed
unlink(P) :->
send(P?mytimer, stop),
send(P, send_super, unlink).
% message processed by the timer
anim_message(P) :->
get(P, angle, A),
get(P, len_pendulum, L),
calc(A, L, X, Y),
get(P, window, W),
get(P, boule, B),
send(W, display, B, point(X,Y)),
% computation of the next position
get(P, delta, D),
next_Angle(A, D, NA, ND),
send(P, angle, NA),
send(P, delta, ND).
:- pce_end_class.
% computation of the position of the bowl.
calc(Ang, Len, X, Y) :-
X is Len * cos(Ang)+ 250,
Y is Len * sin(Ang) + 20.
% computation of the next angle
% if we reach 0 or pi, delta change.
next_Angle(A, D, NA, ND) :-
NA is D + A,
(((D > 0, abs(pi-NA) < 0.01); (D < 0, abs(NA) < 0.01))->
ND = - D;
ND = D).

View file

@ -0,0 +1,82 @@
import pygame, sys
from pygame.locals import *
from math import sin, cos, radians
pygame.init()
WINDOWSIZE = 250
TIMETICK = 100
BOBSIZE = 15
window = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))
pygame.display.set_caption("Pendulum")
screen = pygame.display.get_surface()
screen.fill((255,255,255))
PIVOT = (WINDOWSIZE/2, WINDOWSIZE/10)
SWINGLENGTH = PIVOT[1]*4
class BobMass(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.theta = 45
self.dtheta = 0
self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),
PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),
1,1)
self.draw()
def recomputeAngle(self):
scaling = 3000.0/(SWINGLENGTH**2)
firstDDtheta = -sin(radians(self.theta))*scaling
midDtheta = self.dtheta + firstDDtheta
midtheta = self.theta + (self.dtheta + midDtheta)/2.0
midDDtheta = -sin(radians(midtheta))*scaling
midDtheta = self.dtheta + (firstDDtheta + midDDtheta)/2
midtheta = self.theta + (self.dtheta + midDtheta)/2
midDDtheta = -sin(radians(midtheta)) * scaling
lastDtheta = midDtheta + midDDtheta
lasttheta = midtheta + (midDtheta + lastDtheta)/2.0
lastDDtheta = -sin(radians(lasttheta)) * scaling
lastDtheta = midDtheta + (midDDtheta + lastDDtheta)/2.0
lasttheta = midtheta + (midDtheta + lastDtheta)/2.0
self.dtheta = lastDtheta
self.theta = lasttheta
self.rect = pygame.Rect(PIVOT[0]-
SWINGLENGTH*sin(radians(self.theta)),
PIVOT[1]+
SWINGLENGTH*cos(radians(self.theta)),1,1)
def draw(self):
pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)
pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)
pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)
pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))
def update(self):
self.recomputeAngle()
screen.fill((255,255,255))
self.draw()
bob = BobMass()
TICK = USEREVENT + 2
pygame.time.set_timer(TICK, TIMETICK)
def input(events):
for event in events:
if event.type == QUIT:
sys.exit(0)
elif event.type == TICK:
bob.update()
while True:
input(pygame.event.get())
pygame.display.flip()

View file

@ -0,0 +1,20 @@
#lang racket
(require 2htdp/image
2htdp/universe)
(define (pendulum)
(define (accel θ) (- (sin θ)))
(define θ (/ pi 2.5))
(define θ′ 0)
(define θ′′ (accel (/ pi 2.5)))
(define (x θ) (+ 200 (* 150 (sin θ))))
(define (y θ) (* 150 (cos θ)))
(λ (n)
(define p-image (underlay/xy (add-line (empty-scene 400 200) 200 0 (x θ) (y θ) "black")
(- (x θ) 5) (- (y θ) 5) (circle 5 "solid" "blue")))
(set! θ (+ θ (* θ′ 0.04)))
(set! θ′ (+ θ′ (* (accel θ) 0.04)))
p-image))
(animate (pendulum))

View file

@ -0,0 +1,63 @@
require 'tk'
$root = TkRoot.new("title" => "Pendulum Animation")
$canvas = TkCanvas.new($root) do
width 320
height 200
create TkcLine, 0,25,320,25, 'tags' => 'plate', 'width' => 2, 'fill' => 'grey50'
create TkcOval, 155,20,165,30, 'tags' => 'pivot', 'outline' => "", 'fill' => 'grey50'
create TkcLine, 1,1,1,1, 'tags' => 'rod', 'width' => 3, 'fill' => 'black'
create TkcOval, 1,1,2,2, 'tags' => 'bob', 'outline' => 'black', 'fill' => 'yellow'
end
$canvas.raise('pivot')
$canvas.pack('fill' => 'both', 'expand' => true)
$Theta = 45.0
$dTheta = 0.0
$length = 150
$homeX = 160
$homeY = 25
def show_pendulum
angle = $Theta * Math::PI / 180
x = $homeX + $length * Math.sin(angle)
y = $homeY + $length * Math.cos(angle)
$canvas.coords('rod', $homeX, $homeY, x, y)
$canvas.coords('bob', x-15, y-15, x+15, y+15)
end
def recompute_angle
scaling = 3000.0 / ($length ** 2)
# first estimate
firstDDTheta = -Math.sin($Theta * Math::PI / 180) * scaling
midDTheta = $dTheta + firstDDTheta
midTheta = $Theta + ($dTheta + midDTheta)/2
# second estimate
midDDTheta = -Math.sin(midTheta * Math::PI / 180) * scaling
midDTheta = $dTheta + (firstDDTheta + midDDTheta)/2
midTheta = $Theta + ($dTheta + midDTheta)/2
# again, first
midDDTheta = -Math.sin(midTheta * Math::PI / 180) * scaling
lastDTheta = midDTheta + midDDTheta
lastTheta = midTheta + (midDTheta + lastDTheta)/2
# again, second
lastDDTheta = -Math.sin(lastTheta * Math::PI/180) * scaling
lastDTheta = midDTheta + (midDDTheta + lastDDTheta)/2
lastTheta = midTheta + (midDTheta + lastDTheta)/2
# Now put the values back in our globals
$dTheta = lastDTheta
$Theta = lastTheta
end
def animate
recompute_angle
show_pendulum
$after_id = $root.after(15) {animate}
end
show_pendulum
$after_id = $root.after(500) {animate}
$canvas.bind('<Destroy>') {$root.after_cancel($after_id)}
Tk.mainloop

View file

@ -0,0 +1,57 @@
Shoes.app(:width => 320, :height => 200) do
@centerX = 160
@centerY = 25
@length = 150
@diameter = 15
@Theta = 45.0
@dTheta = 0.0
stroke gray
strokewidth 3
line 0,25,320,25
oval 155,20,10
stroke black
@rod = line(@centerX, @centerY, @centerX, @centerY + @length)
@bob = oval(@centerX - @diameter, @centerY + @length - @diameter, 2*@diameter)
animate(24) do |i|
recompute_angle
show_pendulum
end
def show_pendulum
angle = (90 + @Theta) * Math::PI / 180
x = @centerX + (Math.cos(angle) * @length).to_i
y = @centerY + (Math.sin(angle) * @length).to_i
@rod.remove
strokewidth 3
@rod = line(@centerX, @centerY, x, y)
@bob.move(x-@diameter, y-@diameter)
end
def recompute_angle
scaling = 3000.0 / (@length **2)
# first estimate
firstDDTheta = -Math.sin(@Theta * Math::PI / 180) * scaling
midDTheta = @dTheta + firstDDTheta
midTheta = @Theta + (@dTheta + midDTheta)/2
# second estimate
midDDTheta = -Math.sin(midTheta * Math::PI / 180) * scaling
midDTheta = @dTheta + (firstDDTheta + midDDTheta)/2
midTheta = @Theta + (@dTheta + midDTheta)/2
# again, first
midDDTheta = -Math.sin(midTheta * Math::PI / 180) * scaling
lastDTheta = midDTheta + midDDTheta
lastTheta = midTheta + (midDTheta + lastDTheta)/2
# again, second
lastDDTheta = -Math.sin(lastTheta * Math::PI/180) * scaling
lastDTheta = midDTheta + (midDDTheta + lastDDTheta)/2
lastTheta = midTheta + (midDTheta + lastDTheta)/2
# Now put the values back in our globals
@dTheta = lastDTheta
@Theta = lastTheta
end
end

View file

@ -0,0 +1,64 @@
import scala.swing._
import scala.swing.Swing._
import scala.actors._
import scala.actors.Actor._
import java.awt.{Color, Graphics}
object Pendulum extends SimpleSwingApplication {
val length = 100
val prefSizeX = 2*length+50
val prefSizeY = length/2*3
lazy val ui = new Panel {
import math._
background = Color.white
preferredSize = (prefSizeX, prefSizeY)
peer.setDoubleBuffered(true)
var angle: Double = Pi/2;
def pendular = new Actor {
var angleAccel, angleVelocity = 0.0;
var dt = 0.1
def act() {
while (true) {
angleAccel = -9.81 / length * sin(angle)
angleVelocity += angleAccel * dt
angle += angleVelocity * dt
repaint()
Thread.sleep(15)
}
}
}
override def paintComponent(g: Graphics2D) = {
super.paintComponent(g)
g.setColor(Color.white);
g.fillRect(0, 0, size.width, size.height);
val anchorX = size.width / 2
val anchorY = size.height / 4
val ballX = anchorX + (sin(angle) * length).toInt
val ballY = anchorY + (cos(angle) * length).toInt
g.setColor(Color.lightGray)
g.drawLine(anchorX-2*length, anchorY, anchorX+2*length, anchorY)
g.setColor(Color.black)
g.drawLine(anchorX, anchorY, ballX, ballY)
g.fillOval(anchorX - 3, anchorY - 4, 7, 7)
g.drawOval(ballX - 7, ballY - 7, 14, 14)
g.setColor(Color.yellow)
g.fillOval(ballX - 7, ballY - 7, 14, 14)
}
}
def top = new MainFrame {
title = "Rosetta Code >>> Task: Animate a pendulum | Language: Scala"
contents = ui
ui.pendular.start
}
}

View file

@ -0,0 +1,71 @@
#!r6rs
;;; R6RS implementation of Pendulum Animation
(import (rnrs)
(lib pstk main) ; change this for your pstk installation
)
(define PI 3.14159)
(define *conv-radians* (/ PI 180))
(define *theta* 45.0)
(define *d-theta* 0.0)
(define *length* 150)
(define *home-x* 160)
(define *home-y* 25)
;;; estimates new angle of pendulum
(define (recompute-angle)
(define (avg a b) (/ (+ a b) 2))
(let* ((scaling (/ 3000.0 (* *length* *length*)))
; first estimate
(first-dd-theta (- (* (sin (* *theta* *conv-radians*)) scaling)))
(mid-d-theta (+ *d-theta* first-dd-theta))
(mid-theta (+ *theta* (avg *d-theta* mid-d-theta)))
; second estimate
(mid-dd-theta (- (* (sin (* mid-theta *conv-radians*)) scaling)))
(mid-d-theta-2 (+ *d-theta* (avg first-dd-theta mid-dd-theta)))
(mid-theta-2 (+ *theta* (avg *d-theta* mid-d-theta-2)))
; again first
(mid-dd-theta-2 (- (* (sin (* mid-theta-2 *conv-radians*)) scaling)))
(last-d-theta (+ mid-d-theta-2 mid-dd-theta-2))
(last-theta (+ mid-theta-2 (avg mid-d-theta-2 last-d-theta)))
; again second
(last-dd-theta (- (* (sin (* last-theta *conv-radians*)) scaling)))
(last-d-theta-2 (+ mid-d-theta-2 (avg mid-dd-theta-2 last-dd-theta)))
(last-theta-2 (+ mid-theta-2 (avg mid-d-theta-2 last-d-theta-2))))
; put values back in globals
(set! *d-theta* last-d-theta-2)
(set! *theta* last-theta-2)))
;;; The main event loop and graphics context
(let ((tk (tk-start)))
(tk/wm 'title tk "Pendulum Animation")
(let ((canvas (tk 'create-widget 'canvas)))
;;; redraw the pendulum on canvas
;;; - uses angle and length to compute new (x,y) position of bob
(define (show-pendulum canvas)
(let* ((pendulum-angle (* *conv-radians* *theta*))
(x (+ *home-x* (* *length* (sin pendulum-angle))))
(y (+ *home-y* (* *length* (cos pendulum-angle)))))
(canvas 'coords 'rod *home-x* *home-y* x y)
(canvas 'coords 'bob (- x 15) (- y 15) (+ x 15) (+ y 15))))
;;; move the pendulum and repeat after 20ms
(define (animate)
(recompute-angle)
(show-pendulum canvas)
(tk/after 20 animate))
;; layout the canvas
(tk/grid canvas 'column: 0 'row: 0)
(canvas 'create 'line 0 25 320 25 'tags: 'plate 'width: 2 'fill: 'grey50)
(canvas 'create 'oval 155 20 165 30 'tags: 'pivot 'outline: "" 'fill: 'grey50)
(canvas 'create 'line 1 1 1 1 'tags: 'rod 'width: 3 'fill: 'black)
(canvas 'create 'oval 1 1 2 2 'tags: 'bob 'outline: 'black 'fill: 'yellow)
;; get everything started
(show-pendulum canvas)
(tk/after 500 animate)
(tk-event-loop tk)))

View file

@ -0,0 +1,80 @@
package require Tcl 8.5
package require Tk
# Make the graphical entities
pack [canvas .c -width 320 -height 200] -fill both -expand 1
.c create line 0 25 320 25 -width 2 -fill grey50 -tags plate
.c create line 1 1 1 1 -tags rod -width 3 -fill black
.c create oval 1 1 2 2 -tags bob -fill yellow -outline black
.c create oval 155 20 165 30 -fill grey50 -outline {} -tags pivot
# Set some vars
set points {}
set Theta 45.0
set dTheta 0.0
set pi 3.1415926535897933
set length 150
set homeX 160
# How to respond to a changing in size of the window
proc resized {width} {
global homeX
.c coords plate 0 25 $width 25
set homeX [expr {$width / 2}]
.c coords pivot [expr {$homeX-5}] 20 [expr {$homeX+5}] 30
showPendulum
}
# How to actually arrange the pendulum, mapping the model to the display
proc showPendulum {} {
global Theta dTheta pi length homeX
set angle [expr {$Theta * $pi/180}]
set x [expr {$homeX + $length*sin($angle)}]
set y [expr {25 + $length*cos($angle)}]
.c coords rod $homeX 25 $x $y
.c coords bob [expr {$x-15}] [expr {$y-15}] [expr {$x+15}] [expr {$y+15}]
}
# The dynamic part of the display
proc recomputeAngle {} {
global Theta dTheta pi length
set scaling [expr {3000.0/$length**2}]
# first estimate
set firstDDTheta [expr {-sin($Theta * $pi/180)*$scaling}]
set midDTheta [expr {$dTheta + $firstDDTheta}]
set midTheta [expr {$Theta + ($dTheta + $midDTheta)/2}]
# second estimate
set midDDTheta [expr {-sin($midTheta * $pi/180)*$scaling}]
set midDTheta [expr {$dTheta + ($firstDDTheta + $midDDTheta)/2}]
set midTheta [expr {$Theta + ($dTheta + $midDTheta)/2}]
# Now we do a double-estimate approach for getting the final value
# first estimate
set midDDTheta [expr {-sin($midTheta * $pi/180)*$scaling}]
set lastDTheta [expr {$midDTheta + $midDDTheta}]
set lastTheta [expr {$midTheta + ($midDTheta + $lastDTheta)/2}]
# second estimate
set lastDDTheta [expr {-sin($lastTheta * $pi/180)*$scaling}]
set lastDTheta [expr {$midDTheta + ($midDDTheta + $lastDDTheta)/2}]
set lastTheta [expr {$midTheta + ($midDTheta + $lastDTheta)/2}]
# Now put the values back in our globals
set dTheta $lastDTheta
set Theta $lastTheta
}
# Run the animation by updating the physical model then the display
proc animate {} {
global animation
recomputeAngle
showPendulum
# Reschedule
set animation [after 15 animate]
}
set animation [after 500 animate]; # Extra initial delay is visually pleasing
# Callback to handle resizing of the canvas
bind .c <Configure> {resized %w}
# Callback to stop the animation cleanly when the GUI goes away
bind .c <Destroy> {after cancel $animation}

View file

@ -0,0 +1,35 @@
>> array = [1 2 3 4 5]
array =
1 2 3 4 5
>> arrayfun(@sin,array)
ans =
Columns 1 through 4
0.841470984807897 0.909297426825682 0.141120008059867 -0.756802495307928
Column 5
-0.958924274663138
>> cellarray = {1,2,3,4,5}
cellarray =
[1] [2] [3] [4] [5]
>> cellfun(@tan,cellarray)
ans =
Columns 1 through 4
1.557407724654902 -2.185039863261519 -0.142546543074278 1.157821282349578
Column 5
-3.380515006246586

View file

@ -0,0 +1,13 @@
>> answer = vpi(5)^(vpi(4)^(vpi(3)^vpi(2)));
>> numDigits = order(answer) + 1
numDigits =
183231
>> [sprintf('%d',leadingdigit(answer,20)) '...' sprintf('%d',trailingdigit(answer,20))]
%First and Last 20 Digits
ans =
62060698786608744707...92256259918212890625

View file

@ -0,0 +1,59 @@
>> a = 1+i
a =
1.000000000000000 + 1.000000000000000i
>> b = 3+7i
b =
3.000000000000000 + 7.000000000000000i
>> a+b
ans =
4.000000000000000 + 8.000000000000000i
>> a-b
ans =
-2.000000000000000 - 6.000000000000000i
>> a*b
ans =
-4.000000000000000 +10.000000000000000i
>> a/b
ans =
0.172413793103448 - 0.068965517241379i
>> -a
ans =
-1.000000000000000 - 1.000000000000000i
>> a'
ans =
1.000000000000000 - 1.000000000000000i
>> a^b
ans =
0.000808197112874 - 0.011556516327187i
>> norm(a)
ans =
1.414213562373095

View file

@ -0,0 +1,13 @@
|~>|~#:end:>
<:61:x<:3d:=<:20:$==$~$=${~>%<:2c:~$<:20:~$
<:62:x<:3d:=<:20:$==$~$=${~>%<:a:~$$
<:61:x<:2b:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~+%<:a:~$
<:61:x<:2d:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~-%<:a:~$
<:61:x<:2a:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~*%<:a:~$
<:61:x<:2f:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~/%<:a:~$
<:61:x<:25:=<:20:$==$~$=$<:62:x<:3d:=<:20:$==$~$=${x{x~>~>~/=%<:a:~$
{~>>{x<:1:-^:u:
<:61:x<:5e:=<:20:$==$~$$=$<:62:x<:3D:=<:20:$==$~$=${{~%#:end:
}:u:=>{x{=>~*>{x<:2:-#:ter:
}:ml:x->{x{=>~*>{x<:1:-#:ter:^:ml:
}:ter:<:61:x<:5e:=<:20:$==$~$$=$<:62:x<:3D:=<:20:$==$~$=${{~%

View file

@ -0,0 +1,3 @@
{{basic data operation}}Get two integers from the user, and then output the sum, difference, product, integer quotient and remainder of those numbers. Don't include error handling. For quotient, indicate how it rounds (e.g. towards 0, towards negative infinity, etc.). For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
Also include the exponentiation operator if one exists.

View file

@ -0,0 +1,4 @@
---
category:
- Arithmetic operations
note: Basic language learning

View file

@ -0,0 +1,48 @@
Arithmetic: PHA ;push accumulator and X register onto stack
TXA
PHA
JSR GetUserInput ;routine not implemented
;two integers now in memory locations A and B
;addition
LDA A
CLC
ADC B
JSR DisplayAddition ;routine not implemented
;subtraction
LDA A
SEC
SBC B
JSR DisplaySubtraction ;routine not implemented
;multiplication - overflow not handled
LDA A
LDX B
Multiply: CLC
ADC A
DEX
BNE Multiply
JSR DisplayMultiply ;routine not implemented
;division - rounds up
LDA A
LDX #0
SEC
Divide: INX
SBC B
BCS Divide
TXA ;get result into accumulator
JSR DisplayDivide ;routine not implemented
;modulus
LDA A
SEC
Modulus: SBC B
BCS Modulus
ADC B
JSR DisplayModulus ;routine not implemented
PLA ;restore accumulator and X register from stack
TAX
PLA
RTS ;return from subroutine

View file

@ -0,0 +1,25 @@
report zz_arithmetic no standard page heading.
" Read in the two numbers from the user.
selection-screen begin of block input.
parameters: p_first type i,
p_second type i.
selection-screen end of block input.
" Set the text value that is displayed on input request.
at selection-screen output.
%_p_first_%_app_%-text = 'First Number: '.
%_p_second_%_app_%-text = 'Second Number: '.
end-of-selection.
data: lv_result type i.
lv_result = p_first + p_second.
write: / 'Addition:', lv_result.
lv_result = p_first - p_second.
write: / 'Substraction:', lv_result.
lv_result = p_first * p_second.
write: / 'Multiplication:', lv_result.
lv_result = p_first div p_second.
write: / 'Integer quotient:', lv_result. " Truncated towards zero.
lv_result = p_first mod p_second.
write: / 'Remainder:', lv_result.

View file

@ -0,0 +1,20 @@
:set-state-ok t
(defun get-two-nums (state)
(mv-let (_ a state)
(read-object *standard-oi* state)
(declare (ignore _))
(mv-let (_ b state)
(read-object *standard-oi* state)
(declare (ignore _))
(mv a b state))))
(defun integer-arithmetic (state)
(mv-let (a b state)
(get-two-nums state)
(mv state
(progn$ (cw "Sum: ~x0~%" (+ a b))
(cw "Difference: ~x0~%" (- a b))
(cw "Product: ~x0~%" (* a b))
(cw "Quotient: ~x0~%" (floor a b))
(cw "Remainder: ~x0~%" (mod a b))))))

View file

@ -0,0 +1,10 @@
main:(
LONG INT a=355, b=113;
printf(($"a+b = "gl$, a + b));
printf(($"a-b = "gl$, a - b));
printf(($"a*b = a×b = "gl$, a * b));
printf(($"a/b = "gl$, a / b));
printf(($"a OVER b = a%b = a÷b = "gl$, a % b));
printf(($"a MOD b = a%*b = a%×b = a÷×b = a÷*b = "gl$, a %* b));
printf(($"a UP b = a**b = a↑b = "gl$, a ** b))
)

View file

@ -0,0 +1,8 @@
/^[ \t]*-?[0-9]+[ \t]+-?[0-9]+[ \t]*$/ {
print "add:", $1 + $2
print "sub:", $1 - $2
print "mul:", $1 * $2
print "div:", int($1 / $2) # truncates toward zero
print "mod:", $1 % $2 # same sign as first operand
print "exp:", $1 ^ $2
exit }

View file

@ -0,0 +1,18 @@
with Ada.Text_Io;
with Ada.Integer_Text_IO;
procedure Integer_Arithmetic is
use Ada.Text_IO;
use Ada.Integer_Text_Io;
A, B : Integer;
begin
Get(A);
Get(B);
Put_Line("a+b = " & Integer'Image(A + B));
Put_Line("a-b = " & Integer'Image(A - B));
Put_Line("a*b = " & Integer'Image(A * B));
Put_Line("a/b = " & Integer'Image(A / B) & ", remainder " & Integer'Image(A mod B));
Put_Line("a**b = " & Integer'Image(A ** B));
end Integer_Arithmetic;

View file

@ -0,0 +1,10 @@
var a = 0
var b = 0
stdin -> a // read int from stdin
stdin -> b // read int from stdin
println ("a+b=" + (a + b))
println ("a-b=" + (a - b))
println ("a*b=" + (a * b))
println ("a/b=" + (a / b))
println ("a%b=" + (a % b))

View file

@ -0,0 +1,14 @@
PROC main()
DEF a, b, t
WriteF('A = ')
ReadStr(stdin, t)
a := Val(t)
WriteF('B = ')
ReadStr(stdin, t)
b := Val(t)
WriteF('A+B=\d\nA-B=\d\n', a+b, a-b)
WriteF('A*B=\d\nA/B=\d\n', a*b, a/b)
/* * and / are 16 bit ops; Mul and Div are 32bit ops */
WriteF('A*B=\d\nA/B=\d\n', Mul(a,b), Div(a,b))
WriteF('A mod B =\d\n', Mod(a,b))
ENDPROC

View file

@ -0,0 +1,19 @@
Gui, Add, Edit, va, 5
Gui, Add, Edit, vb, -3
Gui, Add, Button, Default, Compute
Gui, Show
Return
ButtonCompute:
Gui, Submit
MsgBox,%
(Join`s"`n"
a "+" b " = " a+b
a "-" b " = " a-b
a "*" b " = " a*b
a "//" b " = " a//b " remainder " Mod(a,b)
a "**" b " = " a**b
)
; fallthrough
GuiClose:
ExitApp

View file

@ -0,0 +1,7 @@
function math(a!, b!)
print a + b
print a - b
print a * b
print a / b
print a mod b
end function

View file

@ -0,0 +1,6 @@
&&00p"=A",,:."=B ",,,00g.55+,v
v,+55.+g00:,,,,"A+B="<
>"=B-A",,,,:00g-.55+,v
v,+55.*g00:,,,,"A*B="<
>"=B/A",,,,:00g/.55+,v
@,+55.%g00,,,,"A%B="<

View file

@ -0,0 +1,17 @@
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int a, b;
if (argc < 3) exit(1);
b = atoi(argv[--argc]);
if (b == 0) exit(2);
a = atoi(argv[--argc]);
printf("a+b = %d\n", a+b);
printf("a-b = %d\n", a-b);
printf("a*b = %d\n", a*b);
printf("a/b = %d\n", a/b); /* truncates towards 0 (in C99) */
printf("a%%b = %d\n", a%b); /* same sign as first operand (in C99) */
return 0;
}

View file

@ -0,0 +1,6 @@
(defn myfunc []
(println "Enter x and y")
(let [x (read), y (read)]
(doseq [op '(+ - * / Math/pow rem)]
(let [exp (list op x y)]
(printf "%s=%s\n" exp (eval exp))))))

View file

@ -0,0 +1,29 @@
class MAIN
creation make
feature make is
local
a, b: REAL;
do
print("a = ");
io.read_real;
a := io.last_real;
print("b = ");
io.read_real;
b := io.last_real;
print("a + b = ");
io.put_real(a + b);
print("%Na - b = ");
io.put_real(a - b);
print("%Na * b = ");
io.put_real(a * b);
print("%Na / b = ");
io.put_real(a / b);
print("%Na %% b = ");
io.put_real(((a / b) - (a / b).floor) * b);
print("%Na ^ b = ");
io.put_real(a.pow(b));
print("%N");
end
end

View file

@ -0,0 +1,7 @@
: arithmetic ( a b -- )
cr ." a=" over . ." b=" dup .
cr ." a+b=" 2dup + .
cr ." a-b=" 2dup - .
cr ." a*b=" 2dup * .
cr ." a/b=" /mod .
cr ." a mod b = " . cr ;

View file

@ -0,0 +1,3 @@
FM/MOD ( d n -- mod div ) \ floored
SM/REM ( d n -- rem div ) \ symmetric
M* ( n n -- d )

View file

@ -0,0 +1,2 @@
UM/MOD ( ud u -- umod udiv )
UM* ( u u -- ud )

View file

@ -0,0 +1,14 @@
INTEGER A, B
PRINT *, 'Type in two integer numbers separated by white space',
+ ' and press ENTER'
READ *, A, B
PRINT *, ' A + B = ', (A + B)
PRINT *, ' A - B = ', (A - B)
PRINT *, ' A * B = ', (A * B)
PRINT *, ' A / B = ', (A / B)
PRINT *, 'MOD(A,B) = ', MOD(A,B)
PRINT *
PRINT *, 'Even though you did not ask, ',
+ 'exponentiation is an intrinsic op in Fortran, so...'
PRINT *, ' A ** B = ', (A ** B)
END

View file

@ -0,0 +1,15 @@
package main
import "fmt"
func main() {
var a, b int
fmt.Print("enter two integers: ")
fmt.Scanln(&a, &b)
fmt.Printf("%d + %d = %d\n", a, b, a+b)
fmt.Printf("%d - %d = %d\n", a, b, a-b)
fmt.Printf("%d * %d = %d\n", a, b, a*b)
fmt.Printf("%d / %d = %d\n", a, b, a/b) // truncates towards 0
fmt.Printf("%d %% %d = %d\n", a, b, a%b) // same sign as first operand
// no exponentiation operator
}

View file

@ -0,0 +1,15 @@
main = do
a <- readLn :: IO Integer
b <- readLn :: IO Integer
putStrLn $ "a + b = " ++ show (a + b)
putStrLn $ "a - b = " ++ show (a - b)
putStrLn $ "a * b = " ++ show (a * b)
putStrLn $ "a to the power of b = " ++ show (a ** b)
putStrLn $ "a to the power of b = " ++ show (a ^ b)
putStrLn $ "a to the power of b = " ++ show (a ^^ b)
putStrLn $ "a `div` b = " ++ show (a `div` b) -- truncates towards negative infinity
putStrLn $ "a `mod` b = " ++ show (a `mod` b) -- same sign as second operand
putStrLn $ "a `divMod` b = " ++ show (a `divMod` b)
putStrLn $ "a `quot` b = " ++ show (a `quot` b) -- truncates towards 0
putStrLn $ "a `rem` b = " ++ show (a `rem` b) -- same sign as first operand
putStrLn $ "a `quotRem` b = " ++ show (a `quotRem` b)

View file

@ -0,0 +1,15 @@
import java.util.Scanner;
public class Int{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int sum = a + b;//integer addition is discouraged in print statements due to confusion with String concatenation
System.out.println("a + b = " + sum);
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("quotient of a / b = " + (a / b)); // truncates towards 0
System.out.println("remainder of a / b = " + (a % b)); // same sign as first operand
}
}

View file

@ -0,0 +1,26 @@
var a = parseInt(get_input("Enter an integer"), 10);
var b = parseInt(get_input("Enter an integer"), 10);
WScript.Echo("a = " + a);
WScript.Echo("b = " + b);
WScript.Echo("sum: a + b = " + (a + b));
WScript.Echo("difference: a - b = " + (a - b));
WScript.Echo("product: a * b = " + (a * b));
WScript.Echo("quotient: a / b = " + (a / b | 0)); // "| 0" casts it to an integer
WScript.Echo("remainder: a % b = " + (a % b));
function get_input(prompt) {
output(prompt);
try {
return WScript.StdIn.readLine();
} catch(e) {
return readline();
}
}
function output(prompt) {
try {
WScript.Echo(prompt);
} catch(e) {
print(prompt);
}
}

View file

@ -0,0 +1,9 @@
local x = io.read()
local y = io.read()
print ("Sum: " , (x + y))
print ("Difference: ", (x - y))
print ("Product: " , (x * y))
print ("Quotient: " , (x / y)) -- Does not truncate
print ("Remainder: " , (x % y)) -- Result has sign of right operand
print ("Exponent: " , (x ^ y))

View file

@ -0,0 +1,8 @@
disp("integer a: "); a = scanf("%d", 1);
disp("integer b: "); b = scanf("%d", 1);
a+b
a-b
a*b
floor(a/b)
mod(a,b)
a^b

View file

@ -0,0 +1,12 @@
<?php
$a = fgets(STDIN);
$b = fgets(STDIN);
echo
"sum: ", $a + $b, "\n",
"difference: ", $a - $b, "\n",
"product: ", $a * $b, "\n",
"truncating quotient: ", (int)($a / $b), "\n",
"flooring quotient: ", floor($a / $b), "\n",
"remainder: ", $a % $b, "\n";
?>

View file

@ -0,0 +1,11 @@
my $a = <>;
my $b = <>;
print
"sum: ", $a + $b, "\n",
"difference: ", $a - $b, "\n",
"product: ", $a * $b, "\n",
"integer quotient: ", int($a / $b), "\n",
"remainder: ", $a % $b, "\n",
"exponent: ", $a ** $b, "\n"
;

View file

@ -0,0 +1,8 @@
(de math (A B)
(prinl "Add " (+ A B))
(prinl "Subtract " (- A B))
(prinl "Multiply " (* A B))
(prinl "Divide " (/ A B)) # Trucates towards zero
(prinl "Div/rnd " (*/ A B)) # Rounds to next integer
(prinl "Modulus " (% A B)) # Sign of the first operand
(prinl "Power " (** A B)) )

View file

@ -0,0 +1,14 @@
x = int(raw_input("Number 1: "))
y = int(raw_input("Number 2: "))
print "Sum: %d" % (x + y)
print "Difference: %d" % (x - y)
print "Product: %d" % (x * y)
print "Quotient: %d" % (x / y) # or x // y for newer python versions.
# truncates towards negative infinity
print "Remainder: %d" % (x % y) # same sign as second operand
print "Quotient: %d with Remainder: %d" % divmod(x, y)
print "Power: %d" % x**y
## Only used to keep the display up when the program ends
raw_input( )

View file

@ -0,0 +1,13 @@
def getnum(prompt):
while True: # retrying ...
try:
n = int(raw_input(prompt))
except ValueError:
print "Input could not be parsed as an integer. Please try again."\
continue
break
return n
x = getnum("Number1: ")
y = getnum("Number2: ")
...

View file

@ -0,0 +1,8 @@
def arithmetic(x, y):
for op in "+ - * // % **".split():
expr = "%(x)s %(op)s %(y)s" % vars()
print("%s\t=> %s" % (expr, eval(expr)))
arithmetic(12, 8)
arithmetic(input("Number 1: "), input("Number 2: "))

View file

@ -0,0 +1,10 @@
cat("insert number ")
a <- scan(nmax=1, quiet=TRUE)
cat("insert number ")
b <- scan(nmax=1, quiet=TRUE)
print(paste('a+b=', a+b))
print(paste('a-b=', a-b))
print(paste('a*b=', a*b))
print(paste('a%/%b=', a%/%b))
print(paste('a%%b=', a%%b))
print(paste('a^b=', a^b))

View file

@ -0,0 +1,26 @@
/*REXX pgm gets 2 integers from the C.L. or via prompt, shows some opers*/
numeric digits 20 /*all numbers are rounded at ··· */
/*··· the 20th significant digit.*/
parse arg x y . /*maybe the integers are on C.L.?*/
if y=='' then do /*nope, then prompt user for 'em.*/
say "─────Enter two integer values (separated by blanks):"
parse pull x y .
end
do 2 /*show A with B, then B with A.*/
say /*show blank line for eyeballing.*/
call show 'addition' , "+", x+y
call show 'subtraction' , "-", x-y
call show 'multiplication', "*", x*y
call show 'int division' , "%", x%y, ' [rounds down]'
call show 'real division' , "/", x/y
call show 'div remainder' , "//", x//y, ' [sign from 1st operand]'
call show 'power' , "**", x**y
parse value x y with y x /*swap the two values & do again.*/
end /*2*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────SHOW subroutine─────────────────────*/
show: parse arg what,oper,value,comment
say right(what,25)' ' x center(oper,4) y ' ' value comment
return

View file

@ -0,0 +1,7 @@
#lang racket
(define (arithmetic x y)
(for ([op '(+ - * / quotient remainder modulo max min gcd lcm)])
(displayln (~a (list op x y) " => "
((eval op (make-base-namespace)) x y)))))
(arithmetic 8 12)

View file

@ -0,0 +1,10 @@
puts 'Enter x and y'
x=gets.to_i # to check errors, use x=Integer(gets)
y=gets.to_i
puts "Sum: #{x+y}",
"Difference: #{x-y}",
"Product: #{x*y}",
"Quotient: #{x/y}", # truncates towards negative infinity
"Remainder: #{x%y}", # same sign as second operand
"Exponentiation: #{x**y}"

View file

@ -0,0 +1,58 @@
$\
,
@
\=@@@-@-----# atoi
>
,
@
\=@@@-@-----#
<
@ # 4 copies
\=!/?!/->>+>>+>>+>>+<<<<<<<<?\#
> | #\?<<<<<<<<+>>+>>+>>+>>-/
@ |
\==/
\>>>>\
/>>>>/
@
\==!/===?\# add
< \>+<-/
@
\=@@@+@+++++# itoa
.
<
@
\==!/===?\# subtract
< \>-<-/
@
\=@@@+@+++++#
.
!
/\
?- multiply
\/ #/?<<+>+>-==\ /==-<+<+>>?\# /==-<<+>>?\#
< \->+>+<<!/?/# #\?\!>>+<+<-/ #\?\!>>+<<-/
@ /==|=========|=====\ /-\ |
\======<?!/>@/<-?!\>>>@/<<<-?\=>!\?/>!/@/<#
< \=======|==========/ /-\ |
@ \done======>>>!\?/<=/
\=@@@+@+++++#
.
!
/\
?- zero
\/
< divmod
@ /-\
\?\<!\?/#!===+<<<\ /-\
| \<==@\>@\>>!/?!/=<?\>!\?/<<#
| | | #\->->+</
| \=!\=?!/->>+<<?\#
@ #\?<<+>>-/
\=@@@+@+++++#
.
<
@
\=@@@+@+++++#
.
#

View file

@ -0,0 +1,9 @@
val a = Console.readInt
val b = Console.readInt
val sum = a + b;//integer addition is discouraged in print statements due to confusion with String concatenation
println("a + b = " + sum);
println("a - b = " + (a - b));
println("a * b = " + (a * b));
println("quotient of a / b = " + (a / b)); // truncates towards 0
println("remainder of a / b = " + (a % b)); // same sign as first operand

View file

@ -0,0 +1,9 @@
(define (arithmetic x y)
(for-each (lambda (op)
(write (list op x y))
(display " => ")
(write ((eval op) x y))
(newline))
'(+ - * / quotient remainder modulo max min gcd lcm)))
(arithmetic 8 12)

View file

@ -0,0 +1,10 @@
| a b |
'Input number a: ' display.
a := (stdin nextLine) asInteger.
'Input number b: ' display.
b := (stdin nextLine) asInteger.
('a+b=%1' % { a + b }) displayNl.
('a-b=%1' % { a - b }) displayNl.
('a*b=%1' % { a * b }) displayNl.
('a/b=%1' % { a // b }) displayNl.
('a%%b=%1' % { a \\ b }) displayNl.

View file

@ -0,0 +1,11 @@
puts "Please enter two numbers:"
set x [expr {int([gets stdin])}]; # Force integer interpretation
set y [expr {int([gets stdin])}]; # Force integer interpretation
puts "$x + $y = [expr {$x + $y}]"
puts "$x - $y = [expr {$x - $y}]"
puts "$x * $y = [expr {$x * $y}]"
puts "$x / $y = [expr {$x / $y}]"
puts "$x mod $y = [expr {$x % $y}]"
puts "$x 'to the' $y = [expr {$x ** $y}]"

View file

@ -0,0 +1 @@
incr x $y

View file

@ -0,0 +1,24 @@
>> a = [1 2 3]
a =
1 2 3
>> b = [4 5 6]
b =
4 5 6
>> concat = [a b]
concat =
1 2 3 4 5 6
>> concat = [a;b]
concat =
1 2 3
4 5 6

View file

@ -0,0 +1,7 @@
>> c = randn([3,4,5]);
>> d = randn([3,4,7]);
>> e = cat(3,c,d);
>> size(e)
ans =
3 4 12

View file

@ -0,0 +1,61 @@
>> a = [1 2 35] %Declaring a vector (i.e. one-dimensional array)
a =
1 2 35
>> a = [1 2 35;5 7 9] % Declaring a matrix (i.e. two-dimensional array)
a =
1 2 35
5 7 9
>> a3 = reshape(1:2*3*4,[2,3,4]); % declaring a three-dimensional array of size 2x3x4
a3 =
ans(:,:,1) =
1 3 5
2 4 6
ans(:,:,2) =
7 9 11
8 10 12
ans(:,:,3) =
13 15 17
14 16 18
ans(:,:,4) =
19 21 23
20 22 24
>> a(2,3) %Retrieving value using row and column indicies
9
>> a(6) %Retrieving value using array subscript
ans =
9
>> a = [a [10;42]] %Added a column vector to the array
a =
1 2 35 10
5 7 9 42
>> a(:,1) = [] %Deleting array elements
a =
2 35 10
7 9 42

View file

@ -0,0 +1 @@
assert(x == 42,'x = %d, not 42.',x);

View file

@ -0,0 +1,3 @@
x = 3;
assert(x == 42,'Assertion Failed: x = %d, not 42.',x);
??? Assertion Failed: x = 3, not 42.

View file

@ -0,0 +1,3 @@
hash.a = 1;
hash.b = 2;
hash.C = [3,4,5];

View file

@ -0,0 +1,4 @@
hash = [];
hash = setfield(hash,'a',1);
hash = setfield(hash,'b',2);
hash = setfield(hash,'C',[3,4,5]);

View file

@ -0,0 +1,3 @@
hash.('a') = 1;
hash.('b') = 2;
hash.('C') = [3,4,5];

View file

@ -0,0 +1,6 @@
keys = fieldnames(hash);
for k=1:length(keys),
key = keys{k};
value = getfield(hash,key); % get value of key
hash = setfield(hash,key,-value); % set value of key
end;

View file

@ -0,0 +1,6 @@
keys = fieldnames(hash);
for k=1:length(keys),
key = keys{k};
value = hash.(key); % get value of key
hash.(key) = -value; % set value of key
end;

View file

@ -0,0 +1,3 @@
function meanValue = findmean(setOfValues)
meanValue = mean(setOfValues);
end

View file

@ -0,0 +1,3 @@
function medianValue = findmedian(setOfValues)
medianValue = median(setOfValues);
end

View file

@ -0,0 +1,30 @@
#!/usr/bin/gawk -f
{
# compute histogram
histo[$1] += 1;
};
function mode(HIS) {
# Computes the mode from Histogram A
max = 0;
n = 0;
for (k in HIS) {
val = HIS[k];
if (HIS[k] > max) {
max = HIS[k];
n = 1;
List[n] = k;
} else if (HIS[k] == max) {
List[++n] = k;
}
}
for (k=1; k<=n; k++) {
o = o""OFS""List[k];
}
return o;
}
END {
print mode(histo);
};

View file

@ -0,0 +1,28 @@
function Mode(arr:Array):Array {
//Create an associative array to count how many times each element occurs,
//an array to contain the modes, and a variable to store how many times each mode appears.
var count:Array = new Array();
var modeList:Array;
var maxCount:uint=0;
for (var i:String in arr) {
//Record how many times an element has occurred. Note that each element in the cuont array
//has to be initialized explicitly, since it is an associative array.
if (count[arr[i]]==undefined) {
count[arr[i]]=1;
} else {
count[arr[i]]++;
}
//If this is now the most common element, clear the list of modes, and add this element.
if(count[arr[i]] > maxCount)
{
maxCount=count[arr[i]];
modeList = new Array();
modeList.push(arr[i]);
}
//If this is a mode, add it to the list.
else if(count[arr[i]] == maxCount){
modeList.push(arr[i]);
}
}
return modeList;
}

View file

@ -0,0 +1,8 @@
generic
type Element_Type is private;
type Element_Array is array (Positive range <>) of Element_Type;
package Mode is
function Get_Mode (Set : Element_Array) return Element_Array;
end Mode;

View file

@ -0,0 +1,102 @@
with Ada.Containers.Indefinite_Vectors;
package body Mode is
-- map Count to Elements
package Count_Vectors is new Ada.Containers.Indefinite_Vectors
(Element_Type => Element_Array,
Index_Type => Positive);
procedure Add (To : in out Count_Vectors.Vector; Item : Element_Type) is
use type Count_Vectors.Cursor;
Position : Count_Vectors.Cursor := To.First;
Found : Boolean := False;
begin
while not Found and then Position /= Count_Vectors.No_Element loop
declare
Elements : Element_Array := Count_Vectors.Element (Position);
begin
for I in Elements'Range loop
if Elements (I) = Item then
Found := True;
end if;
end loop;
end;
if not Found then
Position := Count_Vectors.Next (Position);
end if;
end loop;
if Position /= Count_Vectors.No_Element then
-- element found, remove it and insert to next count
declare
New_Position : Count_Vectors.Cursor :=
Count_Vectors.Next (Position);
begin
-- remove from old position
declare
Old_Elements : Element_Array :=
Count_Vectors.Element (Position);
New_Elements : Element_Array (1 .. Old_Elements'Length - 1);
New_Index : Positive := New_Elements'First;
begin
for I in Old_Elements'Range loop
if Old_Elements (I) /= Item then
New_Elements (New_Index) := Old_Elements (I);
New_Index := New_Index + 1;
end if;
end loop;
To.Replace_Element (Position, New_Elements);
end;
-- new position not already there?
if New_Position = Count_Vectors.No_Element then
declare
New_Array : Element_Array (1 .. 1) := (1 => Item);
begin
To.Append (New_Array);
end;
else
-- add to new position
declare
Old_Elements : Element_Array :=
Count_Vectors.Element (New_Position);
New_Elements : Element_Array (1 .. Old_Elements'Length + 1);
begin
New_Elements (1 .. Old_Elements'Length) := Old_Elements;
New_Elements (New_Elements'Last) := Item;
To.Replace_Element (New_Position, New_Elements);
end;
end if;
end;
else
-- element not found, add to count 1
Position := To.First;
if Position = Count_Vectors.No_Element then
declare
New_Array : Element_Array (1 .. 1) := (1 => Item);
begin
To.Append (New_Array);
end;
else
declare
Old_Elements : Element_Array :=
Count_Vectors.Element (Position);
New_Elements : Element_Array (1 .. Old_Elements'Length + 1);
begin
New_Elements (1 .. Old_Elements'Length) := Old_Elements;
New_Elements (New_Elements'Last) := Item;
To.Replace_Element (Position, New_Elements);
end;
end if;
end if;
end Add;
function Get_Mode (Set : Element_Array) return Element_Array is
Counts : Count_Vectors.Vector;
begin
for I in Set'Range loop
Add (Counts, Set (I));
end loop;
return Counts.Last_Element;
end Get_Mode;
end Mode;

View file

@ -0,0 +1,26 @@
with Ada.Text_IO;
with Mode;
procedure Main is
type Int_Array is array (Positive range <>) of Integer;
package Int_Mode is new Mode (Integer, Int_Array);
Test_1 : Int_Array := (1, 2, 3, 1, 2, 4, 2, 5, 2, 3, 3, 1, 3, 6);
Result : Int_Array := Int_Mode.Get_Mode (Test_1);
begin
Ada.Text_IO.Put ("Input: ");
for I in Test_1'Range loop
Ada.Text_IO.Put (Integer'Image (Test_1 (I)));
if I /= Test_1'Last then
Ada.Text_IO.Put (",");
end if;
end loop;
Ada.Text_IO.New_Line;
Ada.Text_IO.Put ("Result:");
for I in Result'Range loop
Ada.Text_IO.Put (Integer'Image (Result (I)));
if I /= Result'Last then
Ada.Text_IO.Put (",");
end if;
end loop;
Ada.Text_IO.New_Line;
end Main;

View file

@ -0,0 +1,15 @@
MsgBox % Mode("1 2 3")
MsgBox % Mode("1 2 0 3 0.0")
MsgBox % Mode("0.1 2.2 -0.1 0.22e1 2.20 0.1")
Mode(a, d=" ") { ; the number that occurs most frequently in a list delimited by d (space)
Sort a, ND%d%
Loop Parse, a, %d%
If (V != A_LoopField) {
If (Ct > MxCt)
MxV := V, MxCt := Ct
V := A_LoopField, Ct := 1
}
Else Ct++
Return Ct>MxCt ? V : MxV
}

View file

@ -0,0 +1,59 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct { double v; int c; } vcount;
int cmp_dbl(const void *a, const void *b)
{
double x = *(double*)a - *(double*)b;
return x < 0 ? -1 : x > 0;
}
int vc_cmp(const void *a, const void *b)
{
return ((vcount*)b)->c - ((vcount*)a)->c;
}
int get_mode(double* x, int len, vcount **list)
{
int i, j;
vcount *vc;
/* sort values */
qsort(x, len, sizeof(double), cmp_dbl);
/* count occurence of each value */
for (i = 0, j = 1; i < len - 1; i++, j += (x[i] != x[i + 1]));
*list = vc = malloc(sizeof(vcount) * j);
vc[0].v = x[0];
vc[0].c = 1;
/* generate list value-count pairs */
for (i = j = 0; i < len - 1; i++, vc[j].c++)
if (x[i] != x[i + 1]) vc[++j].v = x[i + 1];
/* sort that by count in descending order */
qsort(vc, j + 1, sizeof(vcount), vc_cmp);
/* the number of entries with same count as the highest */
for (i = 0; i <= j && vc[i].c == vc[0].c; i++);
return i;
}
int main()
{
double values[] = { 1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 12, 12, 17 };
# define len sizeof(values)/sizeof(double)
vcount *vc;
int i, n_modes = get_mode(values, len, &vc);
printf("got %d modes:\n", n_modes);
for (i = 0; i < n_modes; i++)
printf("\tvalue = %g, count = %d\n", vc[i].v, vc[i].c);
free(vc);
return 0;
}

View file

@ -0,0 +1,6 @@
(defn modes [coll]
(let [distrib (frequencies coll)
[value freq] [first second] ; name the key/value pairs in the distrib (map) entries
sorted (sort-by (comp - freq) distrib)
maxfq (freq (first sorted))]
(map value (take-while #(= maxfq (freq %)) sorted))))

View file

@ -0,0 +1,13 @@
mode = (arr) ->
# returns an array with the modes of arr, i.e. the
# elements that appear most often in arr
counts = {}
for elem in arr
counts[elem] ||= 0
counts[elem] += 1
max = 0
for key, cnt of counts
max = cnt if cnt > max
(key for key, cnt of counts when cnt == max)
console.log mode [1, 2, 2, 2, 3, 3, 3, 4, 4]

View file

@ -0,0 +1,15 @@
(defun mode (sequence &rest hash-table-options)
(let ((frequencies (apply #'make-hash-table hash-table-options)))
(map nil (lambda (element)
(incf (gethash element frequencies 0)))
sequence)
(let ((modes '())
(hifreq 0 ))
(maphash (lambda (element frequency)
(cond ((> frequency hifreq)
(setf hifreq frequency
modes (list element)))
((= frequency hifreq)
(push element modes))))
frequencies)
(values modes hifreq))))

View file

@ -0,0 +1,98 @@
program mode_test
use Qsort_Module only Qsort => sort
implicit none
integer, parameter :: S = 10
integer, dimension(S) :: a1 = (/ -1, 7, 7, 2, 2, 2, -1, 7, -3, -3 /)
integer, dimension(S) :: a2 = (/ 1, 1, 1, 1, 1, 0, 2, 2, 2, 2 /)
integer, dimension(S) :: a3 = (/ 0, 0, -1, -1, 9, 9, 3, 3, 7, 7 /)
integer, dimension(S) :: o
integer :: l, trash
print *, stat_mode(a1)
trash = stat_mode(a1, o, l)
print *, o(1:l)
trash = stat_mode(a2, o, l)
print *, o(1:l)
trash = stat_mode(a3, o, l)
print *, o(1:l)
contains
! stat_mode returns the lowest (if not unique) mode
! others can hold other modes, if the mode is not unique
! if others is provided, otherslen should be provided too, and
! it says how many other modes are there.
! ok can be used to know if the return value has a meaning
! or the mode can't be found (void arrays)
integer function stat_mode(a, others, otherslen, ok)
integer, dimension(:), intent(in) :: a
logical, optional, intent(out) :: ok
integer, dimension(size(a,1)), optional, intent(out) :: others
integer, optional, intent(out) :: otherslen
! ta is a copy of a, we sort ta modifying it, freq
! holds the frequencies and idx the index (for ta) so that
! the value appearing freq(i)-time is ta(idx(i))
integer, dimension(size(a, 1)) :: ta, freq, idx
integer :: rs, i, tm, ml, tf
if ( present(ok) ) ok = .false.
select case ( size(a, 1) )
case (0) ! no mode... ok is false
return
case (1)
if ( present(ok) ) ok = .true.
stat_mode = a(1)
return
case default
if ( present(ok) ) ok = .true.
ta = a ! copy the array
call sort(ta) ! sort it in place (cfr. sort algos on RC)
freq = 1
idx = 0
rs = 1 ! rs will be the number of different values
do i = 2, size(ta, 1)
if ( ta(i-1) == ta(i) ) then
freq(rs) = freq(rs) + 1
else
idx(rs) = i-1
rs = rs + 1
end if
end do
idx(rs) = i-1
ml = maxloc(freq(1:rs), 1) ! index of the max value of freq
tf = freq(ml) ! the max frequency
tm = ta(idx(ml)) ! the value with that freq
! if we want all the possible modes, we provide others
if ( present(others) ) then
i = 1
others(1) = tm
do
freq(ml) = 0
ml = maxloc(freq(1:rs), 1)
if ( tf == freq(ml) ) then ! the same freq
i = i + 1 ! as the max one
others(i) = ta(idx(ml))
else
exit
end if
end do
if ( present(otherslen) ) then
otherslen = i
end if
end if
stat_mode = tm
end select
end function stat_mode
end program mode_test

Some files were not shown because too many files have changed in this diff Show more