VHDL calculations inside a function - vhdl

I want to write a function that returns mod 100.
What's wrong with code below?
subtype int is integer range 0 to 255;
function div(val : int) return int is
variable result : int;
variable number : int;
begin
result := 0;
number := val;
while number >= 100 loop
result := result + 1;
number := number - 100;
end loop;
return result;
end div;

Edit: extend the answer to be more understandable.
In your function you return the quotient that is counted in result, not the remainder that is left in number. But this is what I would expect from a function named div().
If you want to return the remainder, you can use the same code, but change the last line into
return number;
And I would rename this new function to mod().

Related

How to perform a sort + indexing whilst removing duplicates at the same time?

I use the following code to sort both items and an index:
There are about 256*1024*1024 entries in the values and index arrays.
The uncompressed values array occupies about 10GB, which is why I want to compress it by grouping together duplicate values of which there are many.
I've come up with the following proof of concept code, but there is a problem in the Compress method. Every time it finds a duplicate it performs a search in the index which costs O(N2) time.
I need to keep an index, because I need to be able to access elements in the array as if no de-duplication took place.
This is done, using a simple default property array property, thus mimicking the original array:
function TLookupTable.GetItems(Index: integer): TSlice;
begin
Result:= FData[FIndex[Index]];
end;
The proof of concept code (which is dog slow) is as follows.
TMyArray = class
class procedure QuickSort<T,Idx>(var Values: array of T; var Index: array of Idx; const Comparer: IComparer<T>;
L, R: Integer);
class procedure Compress<T>(const Values: array of T; var Index: array of Integer; out CompressedValues: TArray<T>; const Comparer: IComparer<T>);
end;
class procedure TMyArray.QuickSort<T,Idx>(var Values: array of T; var Index: array of Idx; const Comparer: IComparer<T>;
L, R: Integer);
var
I, J: Integer;
pivot, temp: T;
TempIdx: Idx;
begin
if (Length(Values) = 0) or ((R - L) <= 0) then
Exit;
repeat
I := L;
J := R;
pivot := Values[L + (R - L) shr 1];
repeat
while Comparer.Compare(Values[I], pivot) < 0 do Inc(I);
while Comparer.Compare(Values[J], pivot) > 0 do Dec(J);
if I <= J then begin
if I <> J then begin
temp := Values[I];
Values[I] := Values[J];
Values[J] := temp;
//Keep the index in sync
tempIdx := Index[I];
Index[I] := Index[J];
Index[J] := tempIdx;
end;
Inc(I);
Dec(J);
end;
until I > J;
if L < J then QuickSort<T,Idx>(Values, Index, Comparer, L, J);
L := I;
until I >= R;
end;
class procedure TMyArray.Compress<T>(const Values: array of T; var Index: array of integer; out CompressedValues: TArray<T>; const Comparer: IComparer<T>);
var
i,j: integer;
Count: integer;
Duplicate: integer;
begin
Count:= 256*1024*1024;
SetLength(CompressedValues, Count);
CompressedValues[0]:= Values[0];
Duplicate:= 0;
for i := 1 to High(Values) do begin
//Compress duplicate values
if Comparer.Compare(Values[i], CompressedValues[Duplicate]) = 0 then begin
//Search for the indexed item
//Very time consuming: O(N*N)
for j:= i to High(Index) do if Index[j] = i then begin
Index[j]:= Duplicate; //Fix up the index
Break;
end; {for j}
end else begin
Inc(Duplicate);
if Duplicate >= Count then begin
Inc(Count, 1024*1024);
SetLength(CompressedValues, Count);
end;
CompressedValues[Duplicate]:= Values[i];
end;
end; {for i}
SetLength(CompressedValues, Duplicate+1)
end;
How can I speed up the compress step so that it takes O(N) time?
If there is a way to both keep the index and remove duplicates and sort, all at the same time, that would be great. My answer below splits the sort and the dedup into two separate stages.
The trick is to leave the original data array alone and just sort the index.
We can then exploit the fact that the original data is in the correct order and use that to build a new index.
In addition that means that we no longer need a custom Sort function; it also moves a lot less data around.
Create the index like so:
FIndex: TArray<integer>;
....
SetLength(FIndex, Length(FAllData));
for i:= 0 to count-1 do begin
FIndex[i]:= i;
end;
TArray.Sort<Integer>(FIndex, TDelegatedComparer<integer>.Construct(
function(const Left, Right: Integer): Integer
begin
if FAllData[Left] > FAllData[Right] then Exit(1);
if FAllData[Left] < FAllData[Right] then Exit(-1);
Result:= 0;
end));
Change the TMyArray class like so:
TMyArray = class
class procedure Compress<T>(const Values: array of T; var Index: TArray<integer>; out CompressedValues: TArray<T>; const Comparer: IComparer<T>);
end;
class procedure TMyArray.Compress<T>(const Values: array of T; var Index: TArray<integer>; out CompressedValues: TArray<T>; const Comparer: IComparer<T>);
const
Equal = 0;
var
i,j: integer;
Count: integer;
Duplicate: integer;
IndexEntry: integer;
OutIndex: TArray<integer>;
begin
Count:= 16*1024*1024; //Start with something reasonable
SetLength(CompressedValues, Count);
SetLength(OutIndex, Length(Index));
Duplicate:= 0;
CompressedValues[0]:= Values[Index[0]];
OutIndex[Index[0]]:= 0;
for i:= 1 to High(Index) do begin
if Comparer.Compare(Values[Index[i]], CompressedValues[Duplicate]) = Equal then begin
OutIndex[Index[i]]:= Duplicate;
end else begin
Inc(Duplicate);
//Grow as needed
if (Duplicate >= Length(CompressedValues)) then SetLength(CompressedValues, Length(CompressedValues) + 1024*1024);
CompressedValues[Duplicate]:= Values[Index[i]];
OutIndex[Index[i]]:= Duplicate;
end;
end;
Index:= OutIndex;
SetLength(CompressedValues, Duplicate+1);
end;

Find the Maximum of an input vector in verilog

Im trying to get the maximum of an input vector. Im assuming all inputs are unsigned and that it should work on a range of bitwidths and array lengths.
I have to keep the parameters and input and output logic the way they are. Here is what I have, but I get a syntax error at the if statement:
module max
#(parameter int bW=16,
parameter int eC=8)
(input logic [bW-1:0] a[eC-1:0],
output logic [bW-1:0] z);
logic i=0;
always #* begin
for (i=0; i<size; i++) {
if(a[i] >z)
z = a[i];
}
end
endmodule
Maybe using a case statement would be better? I dont know. Any help would be nice!
Two simple problems.
You used brackets {/} instead of begin/end to wrap your looping statement. No need to wrap a single statement anyways.
You defined i as a single bit. use an int.
You'll also want to use a default for the initial value, then compute max from there.
For example:
module max
#(parameter int bW=16,
parameter int eC=8)
(input logic [bW-1:0] a[eC-1:0],
output logic [bW-1:0] z);
always #(*) begin
// defaults
z = 0;
for (int i=0; i<size; i++) begin
if (a[i] > z)
z = a[i];
end
end
endmodule
In addition to the other comments, I believe the for comparison value should be 'eC', not 'size'. This compiles for me (with the sverilog flag of course):
module max #(
parameter int bW = 16,
parameter int eC = 8
)
(
input logic [bW-1:0] a [eC-1:0],
output logic [bW-1:0] z
);
always #* begin
z = a[0];
for (int i=1; i<eC; i++) begin
if(a[i] > z) begin
z = a[i];
end
end
end
endmodule

system verilog - implementation of randomize()

I have to implement randomize() function in systemVerilog because the tool I use (model sim) doesn't support this function.
I implemented a basic function in a class with the following member:
bit [15:0] data_xi;
bit [15:0] data_xq;
the basic random function:
//function my_randomize
function int my_randomize(int seed);
int temp1, temp2;
temp1 = (($urandom(seed)) + 1);
data_xi = temp1 - 1;
temp2 = (($urandom(seed)) + 1);
data_xq = temp2 - 1;
if(temp1 != 0 || temp2 != 0 )
return 1;
else
return 0;
endfunction: my_randomize
Now I have to change it to static function which suppose to behave like randomize() with constraints.
How can I implement this?
1) To make your function like constraints, you can have inputs to your function to set the range or a modulo.
//function my_randomize
function int my_randomize(int seed, int temp1_min, int temp1_max, int temp2_min, int temp2_max, int temp3_min, int temp3_max);
int temp1, temp2, temp3;
temp1 = $urandom_range(temp1_min, temp1_max);
temp2 = (($urandom(seed)) % (temp2_max+1));
data_xi = temp2 - 1;
temp3 = ((($urandom($urandom(seed))) % temp3_max+1) + temp3_min;
data_xq = temp3 - 1;
if(temp1 != 0 || temp2 != 0 )
return 1;
else
return 0;
endfunction: my_randomize
Ofcourse you can decide how to implement the randomization for temp1, temp2 and temp3. These are some ideas.
2) If you want all classes to access this function, create a base class with the randomize functionality, and then derive all your classes from it. Although you won't have access to the derived class variables in this case, just base-class variables. You can always make this a virtual function to override in your derived class.
3) Note that using the same seed for $urandom/$urandom_range in the same thread will create the same random number.

Pascal, function returns wrong value

I seem to have a problem with a function in Pascal. The program is just an ordinary recursive binsearch, but it returns always the value of 4? Can anybody point to the mistake in the solution?
var i: integer;
const n = 10;
type tablice = array[1..n] of integer;
function Binsearch(const tab:tablice;l:integer;p:integer;x:integer):integer;
var s: integer;
begin
if l=p then
begin
if tab[l]=x then
Binsearch:=p
else
Binsearch:=-1;
end
else
begin
s:=(l+p) div 2;
if tab[s]<x then
l:=s+1
else
p:=s;
Binsearch(tab,l,p,x);
end;
end;
var A:tablice;
x:integer;
begin
for i:=1 to n do A[i]:=i;
x:=30;
writeln(Binsearch(A,1,n,x));
readln;
end.
On the other hand same code in C++ works fine:
using namespace std;
int rekursja(int tab[], int l, int p, int x){
if(l==p){
if(tab[l]==x) return l;
else return -1;
}else{
int s=(l+p)/2;
if(tab[s]<x) l=s+1;
else p=s;
rekursja(tab,l,p,x);
}
}
int main(){
int t[] = {1,2,3,4,5,6,7,8,9,11};
cout << rekursja(t,0,9,11);
}
Binsearch returns the result only exiting from the last call (result := -1 in this case). In the other cases no result is assigned, so a random value is shown.
Change the ricorsive call with
Binsearch:=Binsearch(tab,l,p,x);
In this way it returns the result to all previos call.

Generate character combinations based on arbitrary string and length - similar to permutations

This question was asked before in other languages but not delphi after searching SO.
see this question:How to Generate Permutations With Repeated Characters and this question: Generate all combinations of arbitrary alphabet up to arbitrary length and this one: How to generate combination of fix length strings using a set of characters?
so the question is not new but I am having a hard time translating any of this to delphi.
What I'm trying to do is generate combinations that does include repeats of characters such as this:
if we have a string of characters (specified by user): ABC and we want to generate length of three characters (also length specified by user) I would get:
AAA AAB AAC ABA ABB ABC ACA ACB ACC BAA BAB BAC etc...
This code seems to do this but in C++:
int N_LETTERS = 4;
char alphabet[] = {'a', 'b', 'c', 'd'};
std::vector<std::string> get_all_words(int length)
{
std::vector<int> index(length, 0);
std::vector<std::string> words;
while(true)
{
std::string word(length);
for (int i = 0; i < length; ++i)
word[i] = alphabet[index[i]];
words.push_back(word);
for (int i = length-1; ; --i)
{
if (i < 0) return words;
index[i]++;
if (index[i] == N_LETTERS)
index[i] = 0;
else
break;
}
}
}
This also seems to do this:
#include <iostream>
#include <string>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
void displayPermutation(string permutation[], int length){
int i;
for (i=0;i<length;i++){
cout<<permutation[i];
}
cout << endl;
}
void getPermutations(string operatorBank[], int operatorCount,
string permutation[],int permutationLength, int curIndex){
int i;
//stop recursion condition
if(curIndex == permutationLength){
displayPermutation(permutation,permutationLength);
}
else{
for(i = 0; i < operatorCount; i++){
permutation[curIndex] = operatorBank[i];
getPermutations(operatorBank,operatorCount,permutation,
permutationLength,curIndex+1);
}
}
}
int main ()
{
int operatorCount = 4;
int permutationLength = 3;
string operatorBank[] = {"+","-","*","/"};
string permutation[] = {"","","",""}; //empty string
int curIndex = 0;
getPermutations(operatorBank,operatorCount,permutation,
permutationLength,curIndex);
return 0;
}
closest to what I want in delphi is found here but does not allow AAA for example:
http://www.swissdelphicenter.ch/torry/showcode.php?id=1032
And no this is not homework in case you are guessing. No other motive but just learning.
EDIT3:
Removed all irrelevant code from question to make it easier for other people to read it and get to the answers below. Look under answers for 2 different methods to accomplish this: one using recursion and the other by using a counter function.
The examples you show make this considerably more complex than necessary, at least IMO.
What you're really looking at is a 3 digit, base 3 number. You can just count from 0 to 33 = 27, then convert each number to base 3 (using 'A', 'B' and 'C' as your digits instead of '0', '1' and '2').
In C++, the conversion could look something like this:
std::string cvt(int in) {
static const int base = 3;
static const int digits = 3;
std::string ret;
for (int i = 0; i<digits; i++) {
ret.push_back('A' + in % base);
in /= base;
}
return std::string(ret.rbegin(), ret.rend());
}
With the conversion in place, producing all the combinations becomes utterly trivial:
for (int i = 0; i < 27; i++)
std::cout << cvt(i) << "\t";
I believe converting that to Delphi should be barely short of purely mechanical -- assignments change from = to :=, % becomes mod, the integer division changes to div, the for loop changes to something like for i = 0 to 27 do, and so on. The most tedious (but ultimately quite simple) part will probably be dealing with the fact that in C++, char is simply a small integer type, on which you can do normal integer math. At least if memory serves, in Pascal (or a derivative like Delphi) you'll need ord to convert from a character to an ordinal, and chr to convert back from ordinal to character. So the 'A' + in % base; will end up something more like chr(ord('A') + in mod base);
Like I said though, it seems like nearly the entire translation could/should end up almost completely mechanical, with no requirement for real changes in how the basic algorithms work, or anything like that.
Not exactly following your sequence of output, but following a sequence similar to the way binary numbers add up...
0001
0010
0011
0100
...
The idea is simple: loop index values in an array indicating which character to use at the respective position to compose the output combination string. No recursion required.
NextCombination updates the index array so the next combination is defined, it returns true as long as not all combinations are formed. False when back to all 0's.
DefineCombinations accepts a string with chars to use (for example 'ABC') and a size of the combined string (eg: 3): this adds the following sequence to a memo:
AAA, AAB, AAC, ABA, ABB, ABC, ACA, ACB, ACC, BAA, BAB, BAC, BBA, BBB, BBC, BCA, BCB, BCC, CAA, CAB, CAC, CBA, CBB, CBC, CCA, CCB, CCC
Adapt as you wish.
function TForm1.NextCombination(var aIndices: array of Integer; const MaxValue: Integer): Boolean;
var Index : Integer;
begin
Result:=False;
Index:=High(aIndices);
while not(Result) and (Index >= Low(aIndices)) do
begin
if (aIndices[Index] < MaxValue) then
begin
{ inc current index }
aIndices[Index]:=aIndices[Index] + 1;
Result:=True;
end
else
begin
{ reset current index, process next }
aIndices[Index]:=0;
Dec(Index);
end;
end;
end;
procedure TForm1.DefineCombinations(const Chars: String; const Size: Integer);
var aIndices : array of Integer;
Index : Integer;
sData : String;
begin
try
SetLength(sData, Size);
SetLength(aIndices, Size);
repeat
for Index:=Low(aIndices) to High(aIndices) do
sData[Index + 1]:=Chars[aIndices[Index] + 1];
memo1.Lines.Add(sData);
until not(NextCombination(aIndices, Length(Chars) - 1));
finally
SetLength(aIndices, 0);
SetLength(sData, 0);
end;
end;
Let me know if I missed something from the original question.
Here it is done with Recursion (Credit to this post's accepted answer:How to Generate Permutations With Repeated Characters
program Combinations;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
procedure displayPermutation(const permutation : array of char; ilength: integer);
var
i: integer;
begin
for i := 0 to ilength - 1 do
begin
if i mod iLength = 0 then
writeln('')
else write(permutation[i]);
end;
end;
procedure getPermutations(const operatorBank: array of char; operatorCount: integer;
permutation: array of char; permutationLength, curIndex: integer);
var
i : integer;
begin
//stop recursion condition
if(curIndex = permutationLength)then
displayPermutation(permutation, permutationLength)
else
for i := 0 to operatorCount - 1 do
begin
permutation[curIndex] := operatorBank[i];
getPermutations(operatorBank,operatorCount,permutation,
permutationLength,curIndex+1);
end;
end;
var
operatorBank,permutation : array of char;
i, permutationLength, curIndex, operatorCount: integer;
Q, S : String;
begin
try
Q := ' ';
S := ' ';
while (Q <> '') and (S <> '') do
begin
Writeln('');
Write('P(N,R) N=? : ');
ReadLn(Q);
operatorCount := Length(Q);
setLength(operatorBank,operatorCount);
for i := 0 to operatorCount - 1 do
operatorBank[i] := Q[i+1];
Write('P(N,R) R=? : ');
ReadLn(S);
if S <> '' then permutationLength := StrToInt(S) + 1;
SetLength(permutation,operatorCount);
curIndex := 0;
Writeln('');
getPermutations(operatorBank, operatorCount, permutation,
permutationLength, curIndex );
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.

Resources