WeixiangYan/CodeTransOcean huggingface dataset:
Task: Amicable pairs






PHP: <?php

function sumDivs ($n) {
    $sum = 1;
    for ($d = 2; $d <= sqrt($n); $d++) {
        if ($n % $d == 0) $sum += $n / $d + $d;
    }
    return $sum;
}
    
for ($n = 2; $n < 20000; $n++) {
    $m = sumDivs($n);
    if ($m > $n) {
        if (sumDivs($m) == $n) echo $n."&ensp;".$m."<br />";
    }
}

?>





Fortran:       MODULE FACTORSTUFF	
Concocted by R.N.McLean, MMXV.
       INTEGER LOTS,ILIMIT		
       PARAMETER (ILIMIT = 2147483647)	
       PARAMETER (LOTS = 22000)	
       INTEGER KNOWNSUM(LOTS)		
       CONTAINS			
        INTEGER FUNCTION SUMF(N)	
         INTEGER N			
         INTEGER S,F,F2,INC,BOOST	
          IF (N.LE.LOTS) THEN		
            SUMF = KNOWNSUM(N)			
           ELSE			
Could use SUMF in place of S, but some compilers have been confused by such usage.
            S = 1			
            F = 1			
            INC = 1			
            IF (MOD(N,2) .EQ. 1) INC = 2
    1       F = F + INC			
            F2 = F*F				
            IF (F2 .LT. N) THEN			
              IF (MOD(N,F) .EQ. 0) THEN		
                BOOST = F + N/F			
                IF (S .GT. ILIMIT - BOOST) GO TO 666	
                S = S + BOOST			
              END IF				
              GO TO 1				
            END IF			
            IF (F2 .EQ. N) THEN	
              IF (S .GT. ILIMIT - F) GO TO 666	
              S = S + F			
            END IF			
            SUMF = S			
          END IF			
         RETURN			
Cannot calculate the sum, because it exceeds the integer limit.
  666     SUMF = -666		
        END FUNCTION SUMF	
         SUBROUTINE PREPARESUMF	
Convert the Sieve of Eratoshenes to have each slot contain the sum of the proper divisors of its slot number.
Changes to instead count the number of factors, or prime factors, etc. would be simple enough.
         INTEGER F		
          KNOWNSUM(1) = 0		
          KNOWNSUM(2:LOTS) = 1		
          DO F = 2,LOTS/2		
            FOR ALL(I = F + F:LOTS:F) KNOWNSUM(I) = KNOWNSUM(I) + F	
          END DO			
        END SUBROUTINE PREPARESUMF	
      END MODULE FACTORSTUFF	
       PROGRAM AMICABLE		
       USE FACTORSTUFF		
       INTEGER I,N		
       INTEGER S1,S2		
        CALL PREPARESUMF		
c        WRITE (6,66) (I,KNOWNSUM(I), I = 1,48)
c   66   FORMAT (10(I3,":",I5,"|"))
        DO N = 2,20000		
          S1 = SUMF(N)			
          IF (S1 .EQ. N) THEN		
            WRITE (6,*) "Perfect
          ELSE IF (S1 .GT. N) THEN	
            S2 = SUMF(S1)		
            IF (S2.EQ.N) WRITE (6,*) "Amicable
          END IF			
        END DO			
      END
Task: Amicable pairs






PHP: <?php

function sumDivs ($n) {
    $sum = 1;
    for ($d = 2; $d <= sqrt($n); $d++) {
        if ($n % $d == 0) $sum += $n / $d + $d;
    }
    return $sum;
}
    
for ($n = 2; $n < 20000; $n++) {
    $m = sumDivs($n);
    if ($m > $n) {
        if (sumDivs($m) == $n) echo $n."&ensp;".$m."<br />";
    }
}

?>
Task: Amicable pairs






PHP: <?php

function sumDivs ($n) {
    $sum = 1;
    for ($d = 2; $d <= sqrt($n); $d++) {
        if ($n % $d == 0) $sum += $n / $d + $d;
    }
    return $sum;
}
    
for ($n = 2; $n < 20000; $n++) {
    $m = sumDivs($n);
    if ($m > $n) {
        if (sumDivs($m) == $n) echo $n."&ensp;".$m."<br />";
    }
}

?>






Ada: with Ada.Text_IO, Generic_Divisors; use Ada.Text_IO;
 
procedure Amicable_Pairs is
   
   function Same(P: Positive) return Positive is (P);
   
   package Divisor_Sum is new Generic_Divisors
     (Result_Type => Natural, None => 0, One => Same, Add =>  "+");
   
   Num2 : Integer;
begin
   for Num1 in 4 .. 20_000 loop
      Num2 := Divisor_Sum.Process(Num1);
      if Num1 < Num2 then
	 if Num1 = Divisor_Sum.Process(Num2) then
	   Put_Line(Integer'Image(Num1) & "," & Integer'Image(Num2));
	 end if;
      end if;
   end loop;
end Amicable_Pairs;
Task: Animation

C: #include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>

const gchar *hello = "Hello World! ";
gint direction = -1;
gint cx=0;
gint slen=0;

GtkLabel *label;

void change_dir(GtkLayout *o, gpointer d)
{
  direction = -direction;
}

gchar *rotateby(const gchar *t, gint q, gint l)
{
  gint i, cl = l, j;
  gchar *r = malloc(l+1);
  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)
    r[j] = t[i];
  r[l] = 0;
  return r;
}

gboolean scroll_it(gpointer data)
{
  if ( direction > 0 )
    cx = (cx + 1) % slen;
  else
    cx = (cx + slen - 1 ) % slen;
  gchar *scrolled = rotateby(hello, cx, slen);
  gtk_label_set_text(label, scrolled);
  free(scrolled);
  return TRUE;
}


int main(int argc, char **argv)
{
  GtkWidget *win;
  GtkButton *button;
  PangoFontDescription *pd;

  gtk_init(&argc, &argv);
  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(GTK_WINDOW(win), "Basic Animation");
  g_signal_connect(G_OBJECT(win), "delete-event", gtk_main_quit, NULL);

  label = (GtkLabel *)gtk_label_new(hello);

  
  
  pd = pango_font_description_new();
  pango_font_description_set_family(pd, "monospace");
  gtk_widget_modify_font(GTK_WIDGET(label), pd);

  button = (GtkButton *)gtk_button_new();
  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));

  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));
  g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(change_dir), NULL);

  slen = strlen(hello);

  g_timeout_add(125, scroll_it, NULL);
  
  gtk_widget_show_all(GTK_WIDGET(win));
  gtk_main();
  return 0;
}
Task: Animation



C#: using System;
using System.Drawing;
using System.Windows.Forms;

namespace BasicAnimation
{
  class BasicAnimationForm : Form
  {
    bool isReverseDirection;
    Label textLabel;
    Timer timer;

    internal BasicAnimationForm()
    {
      this.Size = new Size(150, 75);
      this.Text = "Basic Animation";

      textLabel = new Label();
      textLabel.Text = "Hello World! ";
      textLabel.Location = new Point(3,3);
      textLabel.AutoSize = true;
      textLabel.Click += new EventHandler(textLabel_OnClick);
      this.Controls.Add(textLabel);

      timer = new Timer();
      timer.Interval = 500;
      timer.Tick += new EventHandler(timer_OnTick);
      timer.Enabled = true;

      isReverseDirection = false;
    }

    private void timer_OnTick(object sender, EventArgs e)
    {
      string oldText = textLabel.Text, newText;
      if(isReverseDirection)
        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);
      else
        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);
      textLabel.Text = newText;
    }

    private void textLabel_OnClick(object sender, EventArgs e)
    {
      isReverseDirection = !isReverseDirection;
    }
  }

   class Program
   {
      static void Main()
      {
	Application.Run(new BasicAnimationForm());
      }
   }
}
Task: Animation


C++: #include "animationwidget.h"

#include <QLabel>
#include <QTimer>
#include <QVBoxLayout>

#include <algorithm>

AnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {
    setWindowTitle(tr("Animation"));
    QFont font("Courier", 24);
    QLabel* label = new QLabel("Hello World! ");
    label->setFont(font);
    QVBoxLayout* layout = new QVBoxLayout(this);
    layout->addWidget(label);
    QTimer* timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [label,this]() {
        QString text = label->text();
        std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());
        label->setText(text);
    });
    timer->start(200);
}

void AnimationWidget::mousePressEvent(QMouseEvent*) {
    right_ = !right_;
}
Task: Animation





Java: import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;

public class Rotate {

    private static class State {
        private final String text = "Hello World! ";
        private int startIndex = 0;
        private boolean rotateRight = true;
    }

    public static void main(String[] args) {
        State state = new State();

        JLabel label = new JLabel(state.text);
        label.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent event) {
                state.rotateRight = !state.rotateRight;
            }
        });

        TimerTask task = new TimerTask() {
            public void run() {
                int delta = state.rotateRight ? 1 : -1;
                state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();
                label.setText(rotate(state.text, state.startIndex));
            }
        };
        Timer timer = new Timer(false);
        timer.schedule(task, 0, 500);

        JFrame rot = new JFrame();
        rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        rot.add(label);
        rot.pack();
        rot.setLocationRelativeTo(null);
        rot.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                timer.cancel();
            }
        });
        rot.setVisible(true);
    }

    private static String rotate(String text, int startIdx) {
        char[] rotated = new char[text.length()];
        for (int i = 0; i < text.length(); i++) {
            rotated[i] = text.charAt((i + startIdx) % text.length());
        }
        return String.valueOf(rotated);
    }
}
Task: Animation







Python: txt = "Hello, world! "
left = True

def draw():
    global txt
    background(128)
    text(txt, 10, height / 2)
    if frameCount % 10 == 0:
        if (left):
            txt = rotate(txt, 1)
        else:
            txt = rotate(txt, -1)
        println(txt)

def mouseReleased():
    global left
    left = not left

def rotate(text, startIdx):
    rotated = text[startIdx:] + text[:startIdx]
    return rotated
Task: Animation








VB: VERSION 5.00
Begin VB.Form Form1
   Begin VB.Timer Timer1
      Interval = 250
   End
   Begin VB.Label Label1
      AutoSize = -1  
      Caption  = "Hello World! "
   End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False


Private goRight As Boolean

Private Sub Label1_Click()
    goRight = Not goRight
End Sub

Private Sub Timer1_Timer()
    If goRight Then
        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)
    Else
        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)
    End If
    Label1.Caption = x
End Sub
Task: Animation




Go: package main

import (
    "log"
    "time"

    "github.com/gdamore/tcell"
)

const (
    msg             = "Hello World! "
    x0, y0          = 8, 3
    shiftsPerSecond = 4
    clicksToExit    = 5
)

func main() {
    s, err := tcell.NewScreen()
    if err != nil {
        log.Fatal(err)
    }
    if err = s.Init(); err != nil {
        log.Fatal(err)
    }
    s.Clear()
    s.EnableMouse()
    tick := time.Tick(time.Second / shiftsPerSecond)
    click := make(chan bool)
    go func() {
        for {
            em, ok := s.PollEvent().(*tcell.EventMouse)
            if !ok || em.Buttons()&0xFF == tcell.ButtonNone {
                continue
            }
            mx, my := em.Position()
            if my == y0 && mx >= x0 && mx < x0+len(msg) {
                click <- true
            }
        }
    }()
    for inc, shift, clicks := 1, 0, 0; ; {
        select {
        case <-tick:
            shift = (shift + inc) % len(msg)
            for i, r := range msg {
                s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0)
            }
            s.Show()
        case <-click:
            clicks++
            if clicks == clicksToExit {
                s.Fini()
                return
            }
            inc = len(msg) - inc
        }
    }
}
Task: Knapsack problem_Unbounded

C: #include <stdio.h>
#include <stdlib.h>

typedef struct {
    char *name;
    double value;
    double weight;
    double volume;
} item_t;

item_t items[] = {
    {"panacea", 3000.0, 0.3, 0.025},
    {"ichor",   1800.0, 0.2, 0.015},
    {"gold",    2500.0, 2.0, 0.002},
};

int n = sizeof (items) / sizeof (item_t);
int *count;
int *best;
double best_value;

void knapsack (int i, double value, double weight, double volume) {
    int j, m1, m2, m;
    if (i == n) {
        if (value > best_value) {
            best_value = value;
            for (j = 0; j < n; j++) {
                best[j] = count[j];
            }
        }
        return;
    }
    m1 = weight / items[i].weight;
    m2 = volume / items[i].volume;
    m = m1 < m2 ? m1 : m2;
    for (count[i] = m; count[i] >= 0; count[i]--) {
        knapsack(
            i + 1,
            value + count[i] * items[i].value,
            weight - count[i] * items[i].weight,
            volume - count[i] * items[i].volume
        );
    }
}

int main () {
    count = malloc(n * sizeof (int));
    best = malloc(n * sizeof (int));
    best_value = 0;
    knapsack(0, 0.0, 25.0, 0.25);
    int i;
    for (i = 0; i < n; i++) {
        printf("%d %s\n", best[i], items[i].name);
    }
    printf("best value: %.0f\n", best_value);
    free(count); free(best);
    return 0;
}
Task: Knapsack problem_Unbounded



C#: 
using System;
class Program
{
    static void Main()
    {
        uint[] r = items1();
        Console.WriteLine(r[0] + " v  " + r[1] + " a  " + r[2] + " b");  
        var sw = System.Diagnostics.Stopwatch.StartNew();
        for (int i = 1000; i > 0; i--) items1();
        Console.Write(sw.Elapsed); Console.Read();
    }

    static uint[] items0()  
    {
        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0;
        for (a = 0; a <= 10; a++)
            for (b = 0; a * 5 + b * 3 <= 50; b++)
                for (c = 0; a * 25 + b * 15 + c * 2 <= 250 && a * 3 + b * 2 + c * 20 <= 250; c++)
                    if (v0 < (v = a * 30 + b * 18 + c * 25))
                    {
                        v0 = v; a0 = a; b0 = b; c0 = c;
                        
                    }
        return new uint[] { a0, b0, c0 };
    }

    static uint[] items1()  
    {
        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0, c1 = 0;
        for (a = 0; a <= 10; a++)
            for (b = 0; a * 5 + b * 3 <= 50; b++)
            {
                c = (250 - a * 25 - b * 15) / 2;
                if ((c1 = (250 - a * 3 - b * 2) / 20) < c) c = c1;
                if (v0 < (v = a * 30 + b * 18 + c * 25))
                { v0 = v; a0 = a; b0 = b; c0 = c; }
            }
        return new uint[] { a0, b0, c0 };
    }
}
Task: Knapsack problem_Unbounded





Java: package hu.pj.alg;

import hu.pj.obj.Item;
import java.text.*;

public class UnboundedKnapsack {

    protected Item []  items = {
                               new Item("panacea", 3000,  0.3, 0.025),
                               new Item("ichor"  , 1800,  0.2, 0.015),
                               new Item("gold"   , 2500,  2.0, 0.002)
                               };
    protected final int    n = items.length; 
    protected Item      sack = new Item("sack"   ,    0, 25.0, 0.250);
    protected Item      best = new Item("best"   ,    0,  0.0, 0.000);
    protected int  []  maxIt = new int [n];  
    protected int  []    iIt = new int [n];  
    protected int  [] bestAm = new int [n];  

    public UnboundedKnapsack() {
        
        for (int i = 0; i < n; i++) {
            maxIt [i] = Math.min(
                           (int)(sack.getWeight() / items[i].getWeight()),
                           (int)(sack.getVolume() / items[i].getVolume())
                        );
        } 

        
        calcWithRecursion(0);

        
        NumberFormat nf = NumberFormat.getInstance();
        System.out.println("Maximum value achievable is: " + best.getValue());
        System.out.print("This is achieved by carrying (one solution): ");
        for (int i = 0; i < n; i++) {
            System.out.print(bestAm[i] + " " + items[i].getName() + ", ");
        }
        System.out.println();
        System.out.println("The weight to carry is: " + nf.format(best.getWeight()) +
                           "   and the volume used is: " + nf.format(best.getVolume())
                          );

    }

    
    
    public void calcWithRecursion(int item) {
        for (int i = 0; i <= maxIt[item]; i++) {
            iIt[item] = i;
            if (item < n-1) {
                calcWithRecursion(item+1);
            } else {
                int    currVal = 0;   
                double currWei = 0.0; 
                double currVol = 0.0; 
                for (int j = 0; j < n; j++) {
                    currVal += iIt[j] * items[j].getValue();
                    currWei += iIt[j] * items[j].getWeight();
                    currVol += iIt[j] * items[j].getVolume();
                }

                if (currVal > best.getValue()
                    &&
                    currWei <= sack.getWeight()
                    &&
                    currVol <= sack.getVolume()
                )
                {
                    best.setValue (currVal);
                    best.setWeight(currWei);
                    best.setVolume(currVol);
                    for (int j = 0; j < n; j++) bestAm[j] = iIt[j];
                } 
            } 
        } 
    } 

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

}
Task: Knapsack problem_Unbounded








VB: #define min(a, b) iif((a) < (b), (a), (b))

Dim As Single totalPeso, totalVolumen
Dim As Integer maxPanacea, maxIchor, maxGold, maxValor
Dim As Integer i, j ,k
Dim As Integer n(2)

Type Bounty
    articulo As String*7
    valor  As Integer
    peso As Single
    volumen As Single
End Type

Dim item(1 To 5) As Bounty => { _
("panacea", 3000, 0.3, 0.025), ("ichor", 1800,  0.2, 0.015), _
("gold",    2500, 2.0, 0.002), ("sack",     0, 25.0, 0.25 )}

maxPanacea = min(item(4).peso/item(1).peso, item(4).volumen/item(1).volumen)
maxIchor   = min(item(4).peso/item(2).peso, item(4).volumen/item(2).volumen)
maxGold    = min(item(4).peso/item(3).peso, item(4).volumen/item(3).volumen)

For i = 0 To maxPanacea
    For j = 0 To maxIchor
        For k = 0 To maxGold
            item(0).valor =  k*item(3).valor  + j*item(2).valor  + i*item(1).valor
            item(0).peso = k*item(3).peso + j*item(2).peso + i*item(1).peso
            item(0).volumen = k*item(3).volumen + j*item(2).volumen + i*item(1).volumen
            If item(0).peso > item(4).peso Or item(0).volumen > item(4).volumen Then
                Continue For
            End If
            If item(0).valor > maxValor Then
                maxValor = item(0).valor
                totalPeso = item(0).peso
                totalVolumen = item(0).volumen
                n(0) = i: n(1) = j: n(2) = k
            End If
        Next k
    Next j
Next i

Print "Maximum valor achievable is "; Str(maxValor)
Print "This is achieved by carrying "; Str(n(0));
Print " panacea, "; Str(n(1)); " ichor and "; Str(n(2)); " gold items."
Print "The peso to carry is "; Str(totalPeso);
Print " and the volume used is "; Str(totalVolumen)

Sleep
Task: Knapsack problem_Unbounded




Go: package main

import "fmt"

type Item struct {
	Name           string
	Value          int
	Weight, Volume float64
}

type Result struct {
	Counts []int
	Sum    int
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func Knapsack(items []Item, weight, volume float64) (best Result) {
	if len(items) == 0 {
		return
	}
	n := len(items) - 1
	maxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume))
	for count := 0; count <= maxCount; count++ {
		sol := Knapsack(items[:n],
			weight-float64(count)*items[n].Weight,
			volume-float64(count)*items[n].Volume)
		sol.Sum += items[n].Value * count
		if sol.Sum > best.Sum {
			sol.Counts = append(sol.Counts, count)
			best = sol
		}
	}
	return
}

func main() {
	items := []Item{
		{"Panacea", 3000, 0.3, 0.025},
		{"Ichor", 1800, 0.2, 0.015},
		{"Gold", 2500, 2.0, 0.002},
	}
	var sumCount, sumValue int
	var sumWeight, sumVolume float64

	result := Knapsack(items, 25, 0.25)

	for i := range result.Counts {
		fmt.Printf("%-8s x%3d  -> Weight: %4.1f  Volume: %5.3f  Value: %6d\n",
			items[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]),
			items[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i])

		sumCount += result.Counts[i]
		sumValue += items[i].Value * result.Counts[i]
		sumWeight += items[i].Weight * float64(result.Counts[i])
		sumVolume += items[i].Volume * float64(result.Counts[i])
	}

	fmt.Printf("TOTAL (%3d items) Weight: %4.1f  Volume: %5.3f  Value: %6d\n",
		sumCount, sumWeight, sumVolume, sumValue)
}
Task: Knapsack problem_Unbounded



C#: 
using System;
class Program
{
    static void Main()
    {
        uint[] r = items1();
        Console.WriteLine(r[0] + " v  " + r[1] + " a  " + r[2] + " b");  
        var sw = System.Diagnostics.Stopwatch.StartNew();
        for (int i = 1000; i > 0; i--) items1();
        Console.Write(sw.Elapsed); Console.Read();
    }

    static uint[] items0()  
    {
        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0;
        for (a = 0; a <= 10; a++)
            for (b = 0; a * 5 + b * 3 <= 50; b++)
                for (c = 0; a * 25 + b * 15 + c * 2 <= 250 && a * 3 + b * 2 + c * 20 <= 250; c++)
                    if (v0 < (v = a * 30 + b * 18 + c * 25))
                    {
                        v0 = v; a0 = a; b0 = b; c0 = c;
                        
                    }
        return new uint[] { a0, b0, c0 };
    }

    static uint[] items1()  
    {
        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0, c1 = 0;
        for (a = 0; a <= 10; a++)
            for (b = 0; a * 5 + b * 3 <= 50; b++)
            {
                c = (250 - a * 25 - b * 15) / 2;
                if ((c1 = (250 - a * 3 - b * 2) / 20) < c) c = c1;
                if (v0 < (v = a * 30 + b * 18 + c * 25))
                { v0 = v; a0 = a; b0 = b; c0 = c; }
            }
        return new uint[] { a0, b0, c0 };
    }
}








Fortran: PROGRAM KNAPSACK

  IMPLICIT NONE
 
  REAL :: totalWeight, totalVolume
  INTEGER :: maxPanacea, maxIchor, maxGold, maxValue = 0
  INTEGER :: i, j, k
  INTEGER :: n(3)  

  TYPE Bounty
    INTEGER :: value
    REAL :: weight
    REAL :: volume
  END TYPE Bounty

  TYPE(Bounty) :: panacea, ichor, gold, sack, current

  panacea = Bounty(3000, 0.3, 0.025)
  ichor   = Bounty(1800, 0.2, 0.015)
  gold    = Bounty(2500, 2.0, 0.002)
  sack    = Bounty(0, 25.0, 0.25)

  maxPanacea = MIN(sack%weight / panacea%weight, sack%volume / panacea%volume)
  maxIchor = MIN(sack%weight / ichor%weight, sack%volume / ichor%volume)
  maxGold = MIN(sack%weight / gold%weight, sack%volume / gold%volume)
  
  DO i = 0, maxPanacea
     DO j = 0, maxIchor
        Do k = 0, maxGold
           current%value = k * gold%value + j * ichor%value + i * panacea%value
           current%weight = k * gold%weight + j * ichor%weight + i * panacea%weight
           current%volume = k * gold%volume + j * ichor%volume + i * panacea%volume       
           IF (current%weight > sack%weight .OR. current%volume > sack%volume) CYCLE
           IF (current%value > maxValue) THEN
              maxValue = current%value
              totalWeight = current%weight
              totalVolume = current%volume
              n(1) = i ; n(2) = j ; n(3) = k
           END IF
        END DO  
     END DO
  END DO

  WRITE(*, "(A,I0)") "Maximum value achievable is ", maxValue
  WRITE(*, "(3(A,I0),A)") "This is achieved by carrying ", n(1), " panacea, ", n(2), " ichor and ", n(3), " gold items"
  WRITE(*, "(A,F4.1,A,F5.3)") "The weight to carry is ", totalWeight, " and the volume used is ", totalVolume
 
END PROGRAM KNAPSACK