I attempted to port the BayerMoore algorithm for finding patterns in
strings using the TLA+ toolkit. My main question is about the
syntax. I think this error is thrown by these lines as the character to ASCII
conversion isn't automatic. This conversion is also required in the rest of
the code. How can I fix this ? Can I also ask if there is a way to execute
the code to test just once without simulating using the model checker ?
p := in_pattern[i];
flag[ p ] := 1;
I understand that the state space here is enormous. So I just simulate now but that doesn't seem to complete either.
: Attempted to apply function: ( 0 :> -1 ## 1 :> -1 ## 2 :> -1 ##
3 :> -1 ## 4 :> -1 ## ----- ----- to argument "T", which is not
in the domain of the function.
This is the pluscal code. It is written in an imperative style as I am still learning
TLA+
EXTENDS Integers, Sequences,Naturals, TLC
Max(x,y) == IF x < y THEN y ELSE x
(*--algorithm bayermoore
variables
i,m,l,n,j,k,p,skips,
flag \in [0 .. 256 -> -1 .. -1],
in_pattern = <<"T", "E", "S", "T">>,
in_text = <<"N", "T", "E", "S", "T", "E", "E", "D">>;
begin
i := 0;
while i < Len(in_pattern) do
i := i + 1;
p := in_pattern[i];
flag[ p ] := 1;
end while;
m := Len(in_pattern); n := Len(in_text); j := m - 1; k := n - m;
while j <= k do
skips := 0;
l := m - 1;
while j >= 0 do
if in_text[j] # in_text[i + j]
then
skips := Max(1,j - flag[in_text[i+j]]);
skip;
else
j := j - 1;
end if
end while;
if skips = 0
then
print i;
end if
end while;
end algorithm; *)
I believe the loops will work but that isn't fully tested.
The Java code that works is this.
public class BoyerMoore {
int R = 256;
String pattern = "TEST";
String text = "MYFUNNYONLINETESTCANSUCCEEDORNOT";
int[] right = new int[256];
public BoyerMoore(){
for(int i = 0 ; i < R ; i++){
right[i] = -1;
}
for( int i = 0 ; i < pattern.length() ; i ++ ){
right[pattern.charAt(i)] = i;
}
}
public int search(){
int m = pattern.length();
int n = text.length();
int skip;
for(int i = 0 ; i <= n - m ; i += skip){
skip = 0;
for( int j = m - 1 ; j >= 0 ;j --){
if( pattern.charAt(j) != text.charAt(i+j)){
skip = Math.max(1,j - right[text.charAt(i+j)]);
break;
}
}
if( skip == 0 ) return i;
}
return n;
}
This helped me understand how to use the TLA+ toolkit and execute the TLC Model checker even though the spec./code may have a bug.
But mainly I used
struct == [a |-> 97, b |-> 98, c |-> 99]
and a subset of values in the TLA Toolkit configuration section.
This section
CONSTANTS Character, text, pattern
ASSUME text \in Seq(Character)
ASSUME pattern \in Seq(Character)
uses the configured values when the model checker executes.
So now the state space is small. This was suggested to me by Stephan Merz when I asked the TLA+ Google group.
I tried a few methods and eventually set it up like this in the toolkit.
The original function that I was looking for is this.
Ascii(char) == 96 + CHOOSE z \in 1 .. 26 :"abcdefghijklmnopqrstuvwxyz"[z] = char
But this throws an error
----------------------------- MODULE bayermoore -----------------------------
EXTENDS Integers, Sequences,Naturals, TLC
CONSTANTS Character, text, pattern
ASSUME text \in Seq(Character)
ASSUME pattern \in Seq(Character)
Max(x,y) == IF x < y THEN y ELSE x
struct == [a |-> 97, b |-> 98, c |-> 99]
(*--algorithm bayermoore
variables
i,m,l,n,j,k,p,skips,x,y,
flag = [g \in 0..256 |-> -1];
begin
i := 1;
while i < Len(pattern) do
p := struct[pattern[i]];
flag[p] := 1;
i := i + 1;
end while;
i := 1;
m := Len(pattern);
n := Len(text);
k := n - m;
while i <= k do
skips := 0;
j := m - 1;
while j >= 0 do
x := struct[pattern[j+1]];
y := struct[text[i + j]];
\* print ( "x " \o ToString(x) \o "y " \o ToString(y) );
print ( "i " \o ToString(i) \o " j " \o ToString(j));
if x # y then
skips := Max(1,j - flag[y]);
j := -1;
end if;
j := j - 1;
end while;
i := i + skips;
print ("i - " \o ToString(i));
end while;
end algorithm; *)
Related
Given a set of numbers, check whether it can be partitioned into two subsets such that the sum of elements in both subsets is same or not
I am getting segmentation fault in C++(g++ 5.4) with a this problem.
This is where i submitted my solution in C++
https://practice.geeksforgeeks.org/problems/subset-sum-problem/0
I am checking if the array can be divided into two parts with equal sum. So I am just checking if there exists a subset with sum equal to half the sum of the array
I have implemented the below logic with dynamic programming
Let dp[i][j] denote yes or no whether a subset with sum j is possible to form with elements in the range [0, i](both inclusive) where i is 0-based index. I have done nothing new with this traditional problem. But I am getting segmentation fault. The program is giving correct output for small test cases. What mistake have I made
I haven't used any comments because I have done nothing new. Hope it is understandable.
#include <iostream>
#include <bits/stdc++.h>
#include<cstdio>
#define ll long long int
using namespace std;
bool isVowel(char c){
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
bool isLower(char c){
return 97 <= c && c <= 122;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cout << setprecision(10);
ll t, n;
cin >> t;
while (t--) {
cin >> n;
ll a[n];
ll sum = 0;
for (ll i = 0; i < n; i++) {
cin >> a[i];
sum += a[i];
}
if (sum % 2) {
cout << "NO" << '\n';
continue;
}
sum /= 2;
ll dp[n][sum + 1];
for (ll i = 0; i < n; i++) {
for(ll j = 0; j < sum + 1; j++) {
dp[i][j] = 0;
}
}
for (ll i = 0; i < n; i++) {
dp[i][a[i]] = 1;
dp[i][0] = 1;
}
for (ll i = 1; i < n; i++) {
for (ll j = 1; j < sum + 1; j++){
if (j - a[i] > 0) {
dp[i][j] = dp[i - 1][j - a[i]];
}
dp[i][j] |= dp[i - 1][j];
}
}
cout << (dp[n - 1][sum] ? "YES" : "NO") << '\n';
}
}
The segmentation fault is due to
ll dp[n][sum + 1];
Even though the constraints say 1 <= N<= 100, 0 <= arr[i]<= 1000, the test cases used are probably much larger, so ll dp[n][sum + 1] will end up taking some serious stack memory, use
bool dp[n][sum + 1];
It should work fine.
On a side note, avoid using ll randomly, use them according to the constraints.
I'm wondering what the fastest way would be to create a string of n instances of the same character. I could imagine a few approaches, some naive and some less so:
String concatenation (very naive)
func nchars(b byte, n int) string {
s := ""
c := string([]byte{b})
for i := 0; i < n; i++ {
s += c
}
return s
}
Byte slice
func nchars(b byte, n int) string {
s := make([]byte, n)
for i := 0; i < n; i++ {
s[i] = b
}
return string(s)
}
The byte slice approach is at least the one chosen in strings.Repeat: see its source:
b := make([]byte, len(s)*count)
bp := 0
for i := 0; i < count; i++ {
bp += copy(b[bp:], s)
}
return string(b)
So I would go with your second choice.
res1 := strings.Repeat(str1, 4)
I have the Verilog code shown below, and if I try to compile it I get an error message. The point is that I'm trying to manipulate an input, which as long as I know cannot be done in Verilog. The point is that I need check the following condition in Verilog:
static int prime(unsigned long long n)
{
unsigned long long val = 1;
unsigned long long divisor = 5;
if (n == 2 || n == 3)
return 1;
if (n < 2 || n%2 == 0 || n%3 == 0)
return 0;
for ( ; divisor<=n/divisor; val++, divisor=6*val-1)
{
if (n%divisor == 0 || n%(divisor+2) == 0)
return 0;
}
return 1;
}
At the moment I have the following code:
module prime(clk, rst, start, A, ready, P);
input clk, rst, start;
input [7:0] A;
output ready, P;
reg ready, P;
wire [7:0] divisor;
assign divisor = 5;
wire [7:0] val;
assign val = 1;
always # (posedge clk or posedge rst) begin
if (!rst) begin
P <= 0;
end
else if (start) begin
case (A)
0 : P <= 1;
1 : P <= 1;
2 : P <= 1;
3 : P <= 1;
endcase
if (A%2 == 0 && A != 2) begin
P <= 0;
end
else begin
for( ; divisor <= A/divisor; val=val+1, divisor=6*val-1) begin
if (A%divisor == 0 || A%(divisor+2) == 0) begin
P <= 0;
end
end
// need to set P to 1
end
end
end
endmodule
Please also note I need to test primes in the form of 6n+1 or 6n-1, and I also need to assume in my code that 0 and 1 are also primes.
If I try the above code I get an error message saying:
Enhanced FOR loop is not enabled for verilog
If anyone can help me solve the error and finish my logic in Verilog, I would be glad.
The Verilog BNF does not allow empty or compound statements in for(;;). Change the file to *.sv to compile it under SystemVerilog rules. Otherwise change your for loop statement to have simple statements
for( divisor =5; divisor <= A/divisor; divisor=6*val-1) begin
if (A%divisor == 0 || A%(divisor+2) == 0) begin
P <= 0;
end
val++;
end
Also, you can't make procedural assignments to wires. make them variables.
So I'm trying to implement a basic ALU for my first Verilog course, DSD II. Xilinx keeps reporting an error on the lines where I call the gate primitives "and"/"or", but I've used them in previous assignments this way with no errors. Can anybody see what I'm missing?
Code:
module ALU(a,b, opcode, carry, Y, zeroflag);
input [15:0]a;
input [15:0]b;
input [3:0]opcode;
wire In = {opcode,a,b};
output reg carry;
output reg [15:0]Y;
output reg zeroflag;
always #(In)
begin
case(opcode)
//Zero Op
4'b0000 :
begin
Y = 16'h00;
carry = 0;
zeroflag = 1;
end
//Add
4'b0001:
begin
Ripple_Carry_Adder RCA1(Y,carry,a,b,carry);
end
//Subtract
4'b0010:
begin
end
//Multiply
4'b0011:
begin
Y = a*b;
if (Y > 65535)
carry = 1;
else
carry = 0;
if (Y == 0)
zeroflag = 1;
else
zeroflag = 0;
end
//Divide
4'b0100:
begin
Y = a/b;
if (Y > 65535)
carry = 1;
else
carry = 0;
if (Y == 0)
zeroflag = 1;
else
zeroflag = 0;
end
//And
4'b0110:
begin
and(Y, a, b);
if (Y == 0)
zeroflag = 1;
else
zeroflag = 0;
end
//Or
4'b0111:
begin
or(Y,a,b);
if (Y == 0)
zeroflag = 1;
else
zeroflag = 0;
end
//Zero Test
4'b1001:
if((a || b) == 0)
begin
Y = 0;
zeroflag = 1;
carry = 0;
end
//Greater Than
4'b1010:
begin
if(a > b)
Y = a;
else if (b > a)
Y = b;
else
Y = 16'h00;
if (Y == 0)
zeroflag = 1;
else
zeroflag = 0;
end
//Equal
4'b1011:
begin
if (a == b)
Y = 16'h11;
else
Y = 16'h00;
if (Y == 0)
zeroflag = 1;
else
zeroflag = 0;
end
//Less Than
4'b1100:
begin
if(a < b)
Y = a;
else if (b < a)
Y = b;
else
Y = 16'h00;
if (Y == 0)
zeroflag = 1;
else
zeroflag = 0;
end
default :
begin
Y = 16'hxx;
carry = 1'bx;
zeroflag = 1'bx;
end
endcase
end
endmodule
You are instantiating the primitives (as well as the module Ripple_Carry_Adder) inside of an always block, which is not allowed.
Any time you create a module or primitive instance, think of it as placing down a physical piece of hardware. You cannot create it conditionally - it is always there.
So for something like an ALU design, you may want all the operations (add, sub, multiply, divide, etc.) to always happen, and then select the desired output depending on the opcode.
I want to create a function in Delphi that computes different levels of two strings. If two strings are equal (ignoring case), then it should return 0, but if they are not equal, it should return the number of different characters. This function can be very useful for checking spelling.
function GetDiffStringLevel(S1,S2:string):Integer;
begin
if SameText(S1,S2) then Exit(0);
// i want get different chars count
end
samples code:
Diff:=GetDiffStringLevel('Hello','Hello');// Diff:=0;
Diff:=GetDiffStringLevel('Hello','2Hello');// Diff:=1;
Diff:=GetDiffStringLevel('Hello','H2ello');// Diff:=1;
Diff:=GetDiffStringLevel('Hello','Hello W');// Diff:=2;
Diff:=GetDiffStringLevel('Hello','World');// Diff:=6; or 5
Fast and compact implementation.
About 3 times as fast as smasher's implementation with normal strings.
More than 100 times as fast if one of the strings is empty.
Smasher's function is case insensitive though, which can be useful as well.
function LevenshteinDistance(const s, t: string): integer;inline;
var
d : array of array of integer;
n, m, i, j : integer;
begin
n := length(s);
m := length(t);
if n = 0 then Exit(m);
if m = 0 then Exit(n);
SetLength(d, n + 1, m + 1);
for i := 0 to n do d[i, 0] := i;
for j := 0 to m do d[0, j] := j;
for i := 1 to n do
for j := 1 to m do
d[i, j] := Min(Min(d[i-1, j]+1, d[i,j-1]+1), d[i-1,j-1]+Integer(s[i] <> t[j]));
Result := d[n, m];
end;
Note: the inline directive reduces the execution time to less than 70% on my machine, but only for the win32 target platform. If you compile to 64bits (Delphi XE2), inlining actually makes it a tiny bit slower.
What you want is known as the Levenshtein distance (the minimum number of edits to transform one string into the other, where an edit is either a character insertion, character deletion or character substitution). The wikipedia site has a pseudo code implementation.
Delphi implementation:
function LevenshteinDistance(String1 : String; String2 : String) : Integer;
var
Length1, Length2 : Integer;
WorkMatrix : array of array of Integer;
I, J : Integer;
Cost : Integer;
Val1, Val2, Val3 : Integer;
begin
String1 := TCharacter.ToUpper (String1);
String2 := TCharacter.ToUpper (String2);
Length1 := Length (String1);
Length2 := Length (String2);
SetLength (WorkMatrix, Length1+1, Length2+1);
for I := 0 to Length1 do
WorkMatrix [I, 0] := I;
for J := 0 to Length2 do
WorkMatrix [0, J] := J;
for I := 1 to Length1 do
for J := 1 to Length2 do
begin
if (String1 [I] = String2 [J]) then
Cost := 0
else
Cost := 1;
Val1 := WorkMatrix [I-1, J] + 1;
Val2 := WorkMatrix [I, J-1] + 1;
Val3 := WorkMatrix[I-1, J-1] + Cost;
if (Val1 < Val2) then
if (Val1 < Val3) then
WorkMatrix [I, J] := Val1
else
WorkMatrix [I, J] := Val3
else
if (Val2 < Val3) then
WorkMatrix [I, J] := Val2
else
WorkMatrix [I, J] := Val3;
end;
Result := WorkMatrix [Length1, Length2];
end;