How to measure distance between two data in vhdl - vhdl

Calculate the distance between the position of each element in a list1 and the position of the same element in list2 then find the normalized distance in vhdl
First, we will make mem1 (consist of addresses for every data input) i.e address from 1,2,3,4.... to end of the mem1 data input,ok
mem2 (consist of addresses for every data input ) i.e address from 1,2,3,4.... t0 end of the mem2 data input,ok
Check if any of the data input from mem1 = any data input from mem2 .
I.e. The position of each element in mem1 and the position of the same element in mem2
So the address to the same element will be different in the two mem
The address difference will be the distance measure.
I.e searching for similarity, the compute the distance between list1 and list2
How I can do this in vhdl code???
Any help please???

Your approach sounds logical. I would design a single entity that instantiated a piece of memory. The input would be the data that you are looking for. The output would be the location of the data, and a signal indicating if the data was found or not. It would take a number of clock cycles to read out all of the data from the memory. The number of clock cycles would be equal to the depth of the memory. So if you have 10 data words in your memory, it would take 10 clocks to read through all of the words.
There are corner cases that you should consider... what if the data word is in the memory twice? Is the data stored in the memory in sequential order?
Once you've figured all of this out, instantiate two of these components inside a higher level file. This file does the calculation of the distance between the two data locations.
This is just how I would tackle it conceptually. Good luck.

i make a code as your suggestion rick, but i have the same problem ,what is the mistake Type of distances is incompatible with type of -
library IEEE;
use IEEE.STD_LOGIC_1164.all;
package samples is
type sample is array( 0 to 255) of std_logic_vector (0 to 7);
end samples;
entity measure is
port(
clk:std_logic;
A1: in sample;
A2: in sample;
distance: out sample);
end measure;
architecture Behavioral of measure is
signal d: sample ;
function distances(A1, A2: sample) return sample is
variable distances: sample;
begin
for i in A1'range loop
for j in A2'range loop
if (A1(i) = A2(j)) then
distances := (j - i);
end if;
end loop;
end loop;
return distances;
end;
end behavioral;

If I understand correctly, you want to produce an array containing the distances from each element in array_1 to the element holding the same value in array_2.
If so, here's a first stab at a possible solution:
function individual_distances(vector_1, vector_2: integer_vector) return integer_vector is
variable distances: integer_vector(vector_1'range);
begin
for i in vector_1'range loop
for j in vector_2'range loop
if (vector_1(i) = vector_2(j)) then
distances(i) := j - i;
end if;
end loop;
end loop;
return distances;
end;
Here's a sample output for a few random arrays:
individual_distances( (1, 2, 3, 4, 5), (5, 4, 3, 2, 1) ); --> (4, 2, 0, -2, -4)
individual_distances( (1, 2, 3, 4), (4, 3, 2, 1) ); --> (3, 1, -1, -3)
individual_distances( (1, 2, 3), (1, 2, 3) ); --> (0, 0, 0)
As Martin Thompson noted, whether this solution is usable in your case depends on your performance goals and the size of the lists. In practice, this could work for small to medium-sized lists. If your lists are large, you should study architectural choices. For instance, a fully serialized version of the algorithm would take N^2 clock cycles. The example below takes 64 cycles to compute the distances between two arrays with 8 elements each:
process (clock, reset) is
variable i, j: integer range 0 to 7;
begin
if reset then
i := 0;
j := 0;
distances <= (others => 0);
elsif rising_edge(clock) then
if (vector_1(i) = vector_2(j)) then
distances(i) <= abs(j - i);
end if;
if i < 7 then
i := i + 1;
else
i := 0;
j := (j + 1) mod 8;
end if;
end if;
end process;
Other intermediate solutions exist, such as serializing only the outer loop. If you need performance, you could also consider pipelining.
The above code is synthesizable, just remember to constrain the ranges as per your design requirements.

Related

how to check if the sum of digits is divisible by this sum?

I want to calculate the sum of the digits of a user-specified number first. Then I want to check if this number is divisible by the sum of its digits. Unfortunately, for example, for 21 it shows that it is not divisible, and for 200 that it is divisible. Maybe someone helps me. I'm just learning the language pl SQL.
DECLARE
n number(5):=&give_number;
temp_sum INTEGER;
r INTEGER;
a varchar(20);
BEGIN
temp_sum := 0;
WHILE n <> 0 LOOP
r := MOD(n, 10);
temp_sum := temp_sum + r;
n := Trunc(n / 10);
END LOOP;
a:=mod(r,temp_sum);
if a = 0 then
dbms_output.put_line('Divisible');
else
dbms_output.put_line('No divisible');
end if;
END;
You are checking if r is divisible by temp_sum and, if you consider what values they are holding then r is the most-significant digit and temp_sum is the digit sum. Which for an input of 21 checks whether 2 (the most-significant digit) is exactly divisible by 3, which it correctly reports that it is not divisible.
To fix it, you want to keep the input number in a variable that you do not modify and use that in the final comparison and not r:
If we remove some of the unnecessary variables and give the others more meaningful names:
DECLARE
input_value NUMBER(5) := &give_number;
remainder_value NUMBER(5) := input_value;
digit_sum INTEGER;
BEGIN
digit_sum := 0;
WHILE remainder_value <> 0 LOOP
digit_sum := digit_sum + MOD(remainder_value, 10);
remainder_value := TRUNC(remainder_value / 10);
END LOOP;
dbms_output.Put_line(remainder_value);
dbms_output.Put_line('sum of digits = ' || digit_sum);
IF MOD(input_value,digit_sum) = 0 then
dbms_output.put_line('Divisible');
ELSE
dbms_output.put_line('Not divisible');
END IF;
END;
/
Then when you put in 21 the output is:
0
sum of digits = 3
Divisible
And for 202, the output is:
0
sum of digits = 4
Not Divisible
db<>fiddle here
Here is a more compact way to write your PL/SQL block, using some of the features specific to the language. Perhaps the most interesting one is the nesting of program units (subroutines) - something that, in C for example, is not permitted. I am referring to the declaration and full code of a "helper function" (the sum of digits function) right in the DECLARE section of the outer block.
The function also demonstrates a compact way to write the function recursively. In this case recursion isn't too deep (only as many recursive calls as there are digits in the input number); in general, if you can write the same function using a loop, as you did, instead of using recursion, is preferred - far less overhead. On the other hand, with the proper settings (an advanced topic), the interpreter will inline the recursive calls - essentially converting the recursive function to a simple loop. That way you can have the best of both worlds: clean, compact code, yet efficient interpreted code and execution.
I also show the more compact way to display your output to the screen. You only need one call to put_line; let the "if" (or "case expression") take care of what is to be displayed within the put_line call. Moreover, the common part, 'Divisible', can be factored out; the case expression simply adds 'Not ' when it's needed.
declare
n number := &input_number;
function sum_of_digits(n integer) return integer is
begin
return mod(n, 10) + case when n < 10 then 0
else sum_of_digits(trunc(n/10)) end;
end;
begin
dbms_output.put_line(
case when mod(n, sum_of_digits(n)) != 0 then 'Not' end || 'Divisible');
end;
/
Notice one more thing: the outer block has a variable called n, but the function (in the declare section) also has a variable n. For the duration of the nested block (the function definition), n means the local variable. You need to always pay attention to such "masking" of an outer variable by a local variable by the same name.

How to find the divisors of a number and print them out in ascending order?

I'm trying to do it as fast as it is possible. What I can not figure out is how to put all the divisors into the array, and sort that array after that.
I've optimized the for loop - it ends with sqrt(n).
I've also refactored my code, but it still doesn't pass all the tests
type output = array of longint;
var
grater,lower: output;
n,i,v,counter:longint;
begin
read(n);
setLength(grater, round(Sqrt(n)));
setLength(lower, round(Sqrt(n)));
counter:= 0;
for i:=1 to round(Sqrt(n)) do
begin
if (n mod i = 0) then
begin
if i>round(Sqrt(n)) then
grater[counter]:= i
else
lower[counter]:=i;
if n div i>round(Sqrt(n)) then
grater[counter]:= n div i
else
lower[counter]:=n div i;
counter:= counter +1;
end;
end;
for v:=0 to Length(lower) do
begin
if (lower[v] <> 0) then writeln(lower[v]);
end;
for v:=Length(grater)-1 downto 0 do
begin
if grater[v] <> 0 then writeln(grater[v]);
end;
end.
It looks like what you're doing is this:
check all integers from 2 up to sqrt(n)
if the input is divisible by the integer, record the integer and (input/integer)
So for input 12, your output might look like:
2
6
3
4
An easy way to adjust what you have is to use two lists for your answers: the first list will record factors less than sqrt(input) in ascending order, and the second will record factors greater than sqrt(input) in descending order. Then, to print them out in order, simply print the contents of the first list in order, and follow up with the contents of the second list in reverse order.

Algorithm for Permutation with Buckets

I am looking for an algorithm which works like this
permutateBuckets([A,B,C])
and gives the following result:
[ [[A,B,C]],
[[A,B],[C]], [[A,C],[B]], [[B,C],[A]], [[A],[B,C]], [[B],[A,C]], [[C],[A,B]],
[[A],[B],[C]], [[A],[C],[B]], [[B],[A],[C]], [[B],[C],[A]], [[C],[A],[B]], [[C],[B],[A]]
]
In general:
The permutation for [1,2,...,n] should include any possible arrangements of 1 up to n buckets that contain the input values, order of values within buckets is not relevant (e.g. [1,2] equals [2,1]), only the order of the containing buckets matters (e.g. [[1,2],[3]] is different than [[3],[1,2]] ).
Each input element has to be in exactly one bucket for a result to be valid (e.g. an input of [1,2] cannot give [[1]] (missing 2), or [[1,2],[1]] (1 appears twice) as output).
The simplest approach is recursive:
Make [[A]] list
Insert new item in all possible places -
before current sublists
between all sublists
after current sublists
into every sublist
For example, list [[B][A]] produces 5 new lists with item C - places to insert C are:
[ [B] [A] ]
^ ^ ^ ^ ^
and three level-2 lists [[A],[B]], [[B],[A]], [[A,B]] produce 5+5+3=13 level-3 lists.
Alternative way:
Generate all n-length nondecreasing sequences from 1...1 to 1..n and generate unique permutations for every sequence.
Values on these permutations correspond to the bucket number for every item. For example, 122 sequence gives 3 permutations that corresponds to distributions:
1 2 2 [1],[2, 3]
2 1 2 [2],[1, 3]
2 2 1 [3],[1, 2]
In any case number of distributions rises very quickly (ordered Bell numbers 1, 3, 13, 75, 541, 4683, 47293, 545835, 7087261, 102247563...)
Implementation of iterative approach in Delphi (full FP-compatible code at ideone)
procedure GenDistributions(N: Integer);
var
seq, t, i, mx: Integer;
Data: array of Byte;
Dist: TBytes2D;
begin
SetLength(Data, N);
//there are n-1 places for incrementing
//so 2^(n-1) possible sequences
for seq := 0 to 1 shl (N - 1) - 1 do begin
t := seq;
mx := 0;
Data[0] := mx;
for i := 1 to N - 1 do begin
mx := mx + (t and 1); //check for the lowest bit
Data[i] := mx;
t := t shr 1;
end;
//here Data contains nondecreasing sequence 0..mx, increment is 0 or 1
//Data[i] corresponds to the number of sublist which item i belongs to
repeat
Dist := nil;
SetLength(Dist, mx + 1); // reset result array into [][][] state
for i := 0 to N - 1 do
Dist[Data[i]] := Dist[Data[i]] + [i]; //add item to calculated sublist
PrintOut(Dist);
until not NextPerm(Data); //generates next permutation if possible
end;
And now Python recursive implementation (ideone)
import copy
cnt = 0
def ModifySublist(Ls, idx, value):
res = copy.deepcopy(Ls)
res[idx].append(value)
return res
def InsertSublist(Ls, idx, value):
res = copy.deepcopy(Ls)
res.insert(idx, [value])
return res
def GenDists(AList, Level, Limit):
global cnt
if (Level==Limit):
print( AList)
cnt += 1
else:
for i in range(len(AList)):
GenDists(ModifySublist(AList, i, Level), Level + 1, Limit)
GenDists(InsertSublist(AList, i, Level), Level + 1, Limit)
GenDists(InsertSublist(AList, len(AList), Level), Level + 1, Limit)
GenDists([], 0, 3)
print(cnt)
Edit: #mhmnn cloned this code in JavaScript using custom items for output.

Tic Tac Toe check winner free pascal

function CheckWinner(const track:MarkArray ;const index:Integer; p1:Player; p2:Player):String;
var
i,N:Integer; //Creating index to traverse the 2D array
row,col: Integer; //creating variables to fix rows and columns
temp : String;
begin
row:=(index-1) DIV 3; //fix row to check
col:=(index-1) MOD 3; //fix column to check
N:=3;
temp:='YES';
for i:=0 to N-1 do
begin
//check for player 1
if(NOT(track[row][i]=p1.sign)) then
begin
temp:='NO';
WriteLn('P1',temp);
end;
if((i=(N-1)) AND NOT(temp='NO') AND (track[row][i]=p1.sign)) then
begin
temp:='P1';
WriteLn('P1 won');
continue;
end;
///player 2 check for rows
if(NOT(track[row][i]=p2.sign)) then
begin
temp:='NO';
WriteLn('P2',temp);
continue;
end;
if((i=N-1) AND NOT(temp='NO') AND (track[row][i]=p2.sign)) then
begin
temp:='P2';
WriteLn('P2 won');
end;
end;
Hey I am writing code for TicTacToe in pascal and stuck at check winner function.
The problem is this code always check the last index of the row for the sign and is telling only for player 1, the main problem is with checks and i can't think of any checks anymore.
Please help.
The function is being passed two player records for player 1 and player 2, player sign is tick or cross and index parameter is the box number on screen converted to a 2D array index. Please someone help with this.This is a row only check i can add to it later.
I think you are trying to do too much in that one function. Split the single tasks up in smaller functions and it will become a lot more readable and a lot simpler.
I would do something like this:
type
TSign = (empty, nought, cross);
TMarkArray = array[0..2, 0..2] of TSign;
TPlayer = record
sign: TSign;
// other fields you may need
end;
function CheckSign(const track: TMarkArray; sign: TSign; p1, p2, p3: Integer): Boolean;
begin
Result := (track[p1 div 3, p1 mod 3] = sign) and
(track[p2 div 3, p2 mod 3] = sign) and
(track[p3 div 3, p3 mod 3] = sign);
end;
function CheckPlayer(const track: TMarkArray; sign: TSign): Boolean;
begin
Result := CheckSign(track, sign, 0, 1, 2) or // top row
CheckSign(track, sign, 3, 4, 5) or // middle row
CheckSign(track, sign, 6, 7, 8) or // bottom row
CheckSign(track, sign, 0, 3, 6) or // left column
CheckSign(track, sign, 1, 4, 7) or // middle column
CheckSign(track, sign, 2, 5, 8) or // right column
CheckSign(track, sign, 0, 4, 8) or // top-left - bottom right
CheckSign(track, sign, 2, 4, 6); // top right - bottom left
end;
function CheckWinner(const track: TMarkArray; p1, p2: TPlayer): string;
begin
if CheckPlayer(track, p1.sign) then
Result := 'P1'
else if CheckPlayer(track, p2.sign) then
Result := 'P2'
else
Result := 'NO';
end;
I don't know how your types are defined, but I made them as simple as possible for this piece of code and added a T in front to designate them as types.
You could check rows and columns in a loop and jump out if you found a winner, but for a small playfield like this, with only 8 possible winner series, I left out the loops. They would only complicate CheckPlayer. For larger playfields, loops might make sense.
Try if that works.

Counting Overlaps of Integer Ranges

I've been stumped on this algorithm for quite a bit.
Say there are four ranges of integers. Each range has a Start and an End value.
Range A: 0,5
Range B: 4,12
Range C: 2,10
Range D: 8,14
From these values I would like to get a new set which counts of the number of the ranges that fall in a particular span of ints. Each of these would have Start, End and Count values, producing something like this:
(Start, End, Count)
0,1,1 (Only 1 range (A) falls between 0 and 1 inclusive)
2,3,2 (2 ranges (A,C))
4,5,3 (3 ranges (A,B,C))
6,7,2 (2 ranges (B,C))
8,10,3 (3 ranges (B,C,D))
11,12,2 (2 ranges (B,D))
13,14,1 (1 range (D))
Does that make sense? What's a good way to approach the algorithm?
You can solve this in O(N ln N) time (for sorting) followed by the same amount of time for outputting results. If the number range is large, O(N ln N) is better than the O(M·N) time of the method suggested in a comment (where M = total range of numbers covered by the ranges).
Sort the N ranges into ascending order, keyed by Start value, say in array S. Initialize an empty priority queue P. Initialize a depth-count D to zero, and the current “reach” to R = S[0].Start.
While S[i].Start=R, push S[i].End on P and advance i and D. When S[i].Start>R, yield the tuple (R, p.top, D). Pop P to R and then decrease D by one and pop P while P.top==R.
Repeat the above paragraph while i<N.
const ranges = {
A: [10, 12],
B: [20, 30],
C: [29, 31],
D: [15, 95],
E: [195, 196]
};
let overlaps = {},
keys = Object.keys(ranges),
values = Object.values(ranges),
i, j;
for (i = 0; i < values.length; i++)
for (j = 0; j < values.length; j++)
if (keys[i] !== keys[j] && // skip same item
values[i][0] < values[j][1] && // overlap check
values[j][0] < values[i][1]) // overlap check
overlaps[keys[i]] = 1;
console.log( Object.keys(overlaps) )
A range x intersects the input range y if:
x.End >= y.Start AND y.End >= x.Start
So, for a given input, just loop through your collection of ranges and see which satisfy the above condition.
If your given collection of ranges doesn't change very often, and your collection of ranges gets much larger than the 4 you stated in the problem description, then sort them first so that you can more efficiently search for the ranges that intersect your input, rather than looping through all of them.
If the given collection of ranges changes often, the sorting could be too expensive, and it would then be smarter to just loop through all of them each time.

Resources