Wrong answer from spigot algorithm - ada

I'm coding the spigot algorithm for displaying digits of pi in ada, but my output is wrong and I can't figure out why
I've tried messing with the range of my loops and different ways to output my data but nothings worked properly
with ada.integer_text_io; use ada.integer_text_io;
with Ada.Text_IO; use Ada.Text_IO;
procedure Spigot is
n : constant Integer := 1000;
length : constant Integer := 10*n/3+1;
x,q,nines,predigit :Integer :=0;
a: array (0..length) of Integer;
begin
nines:=0;
predigit:=0;
for j in 0..length loop
a(j):=2;
end loop;
for j in 1..n loop
q:=0;
for i in reverse 1..length loop
x:=10*a(i) + q*i;
a(i):= x mod (2*i-1);
q:= x/(2*i-1);
end loop;
a(1):= q mod 10;
q:=q/10;
if q = 9 then
nines:=nines+1;
elsif q = 10 then
put(predigit+1);
for k in 0..nines loop
put("0");
end loop;
predigit:=0;
nines:=0;
else
put(predigit);
predigit:=q;
if nines/=0 then
for k in 0..nines loop
put("9");
end loop;
nines:=0;
end if;
end if;
end loop;
put(predigit);
end Spigot;
so it should just be displayed at 0 3 1 4 1 5 9 2 6 5 3 5 8 9... but the output i get is 0 3 1 4 1 599 2 6 5 3 5 89... it should only be 1 digit at a time and also the outputted values for pi aren't completely correct

I don't know the algorithm well enough to talk about why the digits are off, but I did notice some issues:
Your array is defined with bounds 0 .. Length, which would give you 1 extra element
In your loop that does the calculation, you loop from 1..length, which is ok, but you don't adjust the variable i consistently. The array indices need to be one less than the i's used in the actual calculations (keep in mind they still have to be correctly in bounds of your array). For example
x:=10*a(i) + q*i;
needs to either be
x:=10*a(i-1) + q*i;
or
x:=10*a(i) + q*(i+1);
depending on what you decide your array bounds to be. This applies to multiple lines in your code. See this Stackoverflow thread
You assign A(1) when your array starts at 0
Your loops to print out "0" and "9" should be either 1..length or 0 .. length-1
When you print the digits using Integer_Text_IO.Put, you need to specify a width of 1 to get rid of the spaces
There might be more, that's all I saw.

I think you are translating this answer.
You need to be more careful of your indices and your loop ranges; for example, you’ve translated
for(int i = len; i > 0; --i) {
int x = 10 * A[i-1] + q*i;
A[i-1] = x % (2*i - 1);
q = x / (2*i - 1);
}
as
for i in reverse 1..length loop
x:=10*a(i) + q*i;
a(i):= x mod (2*i-1);
q:= x/(2*i-1);
end loop;
The loop ranges are the same. But in the seocnd line, the C code uses A[i-1], whereas yours uses a(i); similarly in the third line.
Later, for
for (int k = 0; k < nines; ++k) {
printf("%d", 0);
}
you have
for k in 0..nines loop
put("0");
end loop;
in which the C loop runs from 0 to nines - 1, but yours runs from 0 to nines. So you put out one more 0 than you should (and later on, likewise for 9s).
Also, you should use put (predigit, width=> 0).

Related

Fibonacci series in Ada using recursion

In this code, I am trying to write a program that prints out the Fibonacci series based on the users' input (Index, Size). An then, the program should print out all the Fibonacci numbers between Index..Size. I have trouble, writing a recursion that calculates and prints out the Fibonacci numbers. Any suggestions?
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO, Ada.Unchecked_Deallocation;
procedure Fibonacci is
type Arr is array (Positive range <>) of Integer;
type Array_Access is access Arr;
Size, Index : Positive;
Variable : Array_Access;
procedure Free is new Ada.Unchecked_Deallocation (Arr, Array_Access);
procedure Recursion (Item : Arr) is --Recursion
begin
Put_Line
(Item (Item'First)'Image); --Prints out the numbers
Recursion
(Item
(Item'First + Item'First + 1 ..
Item'Last)); --Calculating the Fibonacci numbers
end Recursion;
begin
Put ("Welcome to the Fibonacci number series!");
Put
("Enter an initial value and how many Fibonacci numbers you want to print: ");
Get (Index);
Get (Size);
Variable := new Arr (Index .. Size);
Recursion (Variable);
end Fibonacci;
Example: Enter Index (the initial value of the Fibonacci series): 1
Enter Size (how many Fibonacci numbers to print): 5
The first 5 Fibonacci numbers are: 1 1 2 3 5
From Wikipedia,
In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
F0 = 0
F1 = 1
and
Fn = Fn - 1 + Fn - 2
which translates pretty directly into
function Fibonacci (N : Natural) return Natural is
(case N is
when 0 => 0,
when 1 => 1,
when others => Fibonacci (N - 1) + Fibonacci (N - 2));
or, old style,
function Fibonacci (N : Natural) return Natural is
begin
if N = 0 then
return 0;
elsif N = 1 then
return 1;
else
return Fibonacci (N - 1) + Fibonacci (N - 2);
end if;
end Fibonacci;
You do have to do your printing outside the function, and admittedly there’s an inefficiency in repeatedly calculating the lower results, but you weren’t asking for efficiency.
Here is how you can do it (this code is based on https://rosettacode.org/wiki/Fibonacci_sequence#Recursive)
with Ada.Text_IO;
with Ada.Integer_Text_IO;
procedure Fibonacci is
First, Amount: Positive;
function Fib(P: Positive) return Positive is --Recursion
begin
if P <= 2 then
return 1;
else
return Fib(P-1) + Fib(P-2);
end if;
end Fib;
begin
Ada.Text_IO.Put_Line("Welcome to the Fibonacci number series!");
Ada.Text_IO.Put_Line("Enter an initial value and how many Kombinacci numbers you want to print: ");
Ada.Integer_Text_IO.Get(First);
Ada.Integer_Text_IO.Get(Amount);
for I in First .. First + Amount loop
Ada.Text_IO.Put("Fibonacci(" & Positive'Image(I) & " ) = ");
Ada.Text_IO.Put_Line(Positive'Image(Fib(I)));
end loop;
end Fibonacci;

Pascal recursive summation function school practice problem

This function is a school practice problem (it is running but does not work properly).
My task is to call for a integer from the user.
When the number arrives, my task is to write out (with a recursive algorithm)
what is the sum of the number with the numbers before the given number.
For example if our number is 10 then the upshot is 55 because 1+2+3+4+5+6+7+8+9+10 = 55, etc.
I've already tried to write this code:
function egesszamosszeg(n:integer) : integer;
begin
egesszamosszeg:=0
if n=1 then
egesszamosszeg:=1
else
for n:=1 to egesszamosszeg do
begin
egesszamosszeg:=egesszamosszeg+1;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var egesszam:integer;
begin
egesszam:=strtoint(Inputbox('','Give an integer please!',''));
Showmessage(inttostr(Egesszamosszeg(egesszam)));
end;
My problem is that I do not know what is the main problem with this code.
I do not know what is the main problem with this code.
There are several problems with your code: it's iterative, not recursive; it's way too complicated; this loop:
for n:=1 to egesszamosszeg do
is effectively:
for n:=1 to 0 do
Consider this simple function which effectively implements the gist of your problem:
function egesszamosszeg(n:integer) : integer;
begin
egesszamosszeg := n;
if (n > 1) then
egesszamosszeg := egesszamosszeg + egesszamosszeg(n - 1);
end;
begin
writeln(egesszamosszeg(10));
end.
You are simply trying to increment egesszamosszeg (couldn't you use an easier name?), instead of adding the consecutive numbers to it. But your loop is wrong: eggesszamosszeg is 0, so you are in fact doing for n := 1 to 0 do. That loop will never run. Don't re-use n, use another variable for the loop index:
for i := 1 to n do
egesszamosszeg := egesszamosszeg + i;
But you say it must be recursive, so it must call itself with a different parameter value. Then do something like:
function egesszamosszeg(n: integer): integer;
begin
if n = 1 then // terminating condition
egesszamosszeg := 1
else
egesszamosszeg := n + egesszamosszeg(n - 1); // recursion
end;
In most Pascals, you can use the pseudo-variable Result instead of the function name. Often, that makes typing a little easier.
FWIW, did you know that you could make this a little simpler and do not need recursion or iteration at all? The result can be calculated directly:
function egesszamosszeg(n: Integer): Integer;
begin
result := n * (n + 1) div 2;
end;
For 1..10, that will give 10 * 11 div 2 = 55 too.
See: https://www.wikihow.com/Sum-the-Integers-from-1-to-N
In effect, you count (1+10) + (2+9) + (3+8) + (4+7) + (5+6) = 5 * 11 = 55. You can do the same for any positive number. Same with 1..6: (1+6) + (2+5) + (3+4) = 3 * 7 = 21.
That leads to the formula:
sum = n * (n + 1) div 2
(or actually:
n div 2 * (n+1) // mathematically: n/2 * (n+1)
which is the same).

Solving 4X4 sudoku in maple

So I am trying to use recursion and backtracking to solve a 4x4 sudoku.
When I call SolveSmallSudoku(L);
"Solving now..."
it gives me this "Error, (in SolveSmallSudoku) Matrix index out of range"
But I cannot spot any bug that is related to my matrix, L, indices. It seems like that my program doesn't do my backtracking part properly. I think my findPossibleEntries procedure works fine. It does find all the possible values for that certain cell. Anyone got any hint?
> L := Matrix(4,4,[ [0,4,0,0],[2,0,0,3],[4,0,0,1],[0,0,3,0] ]);
> isFull := proc(L)
local x, y;
for x from 1 to 4 do
for y from 1 to 4 do
if L[x,y]=0 then
return false;
end if;
end do;
end do;
return true;
end proc;
>findPossibleEntries := proc(L, i, j)
local x, y, possible:=[0,0,0,0];
local r:=1, c:=1;
#Checking possible entries in ith row
for y from 1 to 4 do
if not L[i,y] = 0 then
possible[L[i,y]] := 1;
end if;
end do;
#Checking possible entries in jth col
for x from 1 to 4 do
if not L[x,j] = 0 then
possible[L[x,j]] := 1;
end if;
end do;
#Checking possible entries block by block
if i >= 1 and i <= 2 then
r := 1;
elif i >= 3 and i <= 4 then
r := 3;
end if;
if j >= 1 and j <= 2 then
c := 1;
elif j >= 3 and j <= 4 then
c := 3;
end if;
#Using for-loop to find possible entries in the block
for x in range(r, r+1) do
for y in range(c, c+1) do
if not L[x,y] = 0 then
possible[L[x,y]] := 1;
end if;
end do;
end do;
#Now the list, possible, only holds the possible entries
for x from 1 to 4 do
if possible[x] = 0 then
possible[x] := x;
else
possible[x] := 0;
end if;
end do;
return possible;
end proc;
>SolveSmallSudoku := proc(L)
local x, y, i:=0, j:=0, possibleVal:=[0,0,0,0];
if isFull(L) then
print("Solved!");
print(L);
return;
else
print("Solving now...");
for x from 1 to 4 do
for y from 1 to 4 do
if L[x,y] = 0 then
i:=x;
j:=y;
break;
end if
end do;
#Breaks the outer loop as well
if L[x,y] = 0 then
break;
end if
end do;
#Finds all the possibilities for i,j
possibleVal := findPossibleEntries(L,i,j);
#Traverses the list, possibleVal to find the correct entries and finishes the sudoku recursively
for x from 1 to 4 do
if not possibleVal[x] = 0 then
L[i,j]:= possibleVal[x];
SolveSmallSudoku(L);
end if;
end do;
#Backtracking
L[i,j]:= 0;
end if;
end proc;
Get rid of,
#Breaks the outer loop as well
if L[x,y] = 0 then
break;
end if
As you had it originally that outer check was trying to access L[1,5] for your given example L.
Instead, replace the break in the inner loop with,
x:=4; break;
That will cause the outer loop to also complete at the next iteration (which happens to occur right after the inner loop ends or breaks. So you'll get the full break you wanted.
The code then seems to work as you intended, and the solution gets printed for your input example.

Pascal's Triangle in SML

I'm trying to write a function of the type:
pascal : int * int -> int
where the pair of ints represent the row and column, respectively, of Pascal's triangle.
Here's my attempt:
fun pascal(i : int, j : int) : int =
if (i = 0 andalso j = 0) orelse i = j orelse i = 0
then 1
else
pascal(i - 1, j - 1) + pascal(i - 1, j);
It works for my base cases but gives me strange output otherwise. For instance:
pascal(4, 2) gives me 11 and pascal(4, 1) gives me 15
It's a bit strange because, as long as the if clause fails and the else gets evaluated, I do want to return the sum of the element one row above and the element one row above and one element to the left.
What am I doing wrong?
Consider pascal 1 0. If you're using zero-based indexing for the table then this should be equal to 1. But:
pascal 1 0 = pascal 0 -1 + pascal 0 0 = 2
You should put some guards to deal with negative indices and indices where j is greater than i.

How to find the index of a set in Julia/JuMP?

I am trying to create a linear optimization model. I have a set that looks like this:
si=[1,51,39,400909,1244]
sj=[31,47,5]
The numbers in this set represent codes. I am trying to loop through the set to add a constraint to my model, but I do not want to loop through the sets using their values, I want to loop through the sets based on their indices.
Here is the code I have now:
si=[1,51,39,400909,1244]
sj=[31,47,5]
c= [3 5 2;
4 3 5;
4 5 3;
5 4 3;
3 5 4]
b= [80;
75;
80;
120;
60]
# x_ij >= 0 ∀ i = 1,...,5, j = 1,...,3
#defVar(m, x[i in si,j in sj] >= 0)
#setObjective(m,Min,sum{c[i,j]*x[i,j],i in si, j in sj})
# ∀j = 1,...,3
for j in sj
#addConstraint(m, sum{x[i,j],i in si} <= 480)
end
for i in si
#addConstraint(m, sum{x[i,j],j in sj} >= b[i])
end
I keep getting an error because the numbers in the sets are too big. Does anyone know how to loop through the indices instead? Or does anyone have another way to do this?
I am also having trouble printing my solution. Here is my code:
for i in n
for j in p
println("x",i,",",j,"= ", getValue(x[i,j]))
end
end (incorporating Iain Dunning's answer from below)
However the output only reads
Objective value: 1165.0
x5,3= 0.0
Do you know how to fix the output so I can read the values of my variables?
The code you have posted doesn't work because you are trying to index c by, e.g. 400909,47. Try this:
n = length(si)
p = length(sj)
#variable(m, x[i=1:n,j=1:p] >= 0)
#objective(m,Min,sum{c[i,j]*x[i,j],i=1:n,j=1:p})
for j in 1:p
#constraint(m, sum{x[i,j],i=1:n} <= 480)
end
for i in 1:n
#constraint(m, sum{x[i,j],j=1:p} >= b[i])
end

Resources