(Godot Engine) Compute string as PEMDAS - math

I've been trying to create a function in GDScript to process and calculate a string using PEMDAS rules. Below is my try on the subject. It can so far only use the MDAS rules:
Is there a better way to achieve such a function?
func _ready() -> void:
### USE CASES ###
print(Compute_String("1+2*3+3=")) # Output = 10
print(Compute_String("1+2*3*3=")) # Output = 19
print(Compute_String("1*2*3+3=")) # Output = 9
print(Compute_String("1+2+3*3=")) # Output = 12
print(Compute_String("5*2+7-3/2=")) # Output = 15.5
print(Compute_String("9+5.5*2.25=")) # Output = 21.375
print(Compute_String("5*2+7-3/2")) # Output = 1.#QNAN (Missing equals)
print(Compute_String("5*2+7-/2=")) # Output = 1.#QNAN (Adjacent operators)
print(Compute_String("*2+7-3/2=")) # Output = 1.#QNAN (Begins with operator)
print(Compute_String("")) # Output = 1.#QNAN (Empty)
print(Compute_String("=")) # Output = 1.#QNAN (Considered as empty)
print(Compute_String("1 +2=")) # Output = 1.#QNAN (Contains space)
print(Compute_String("(1+2)*3=")) # Output = 1.#QNAN (Parentheses not supported)
func Compute_String(_string: String) -> float:
var _result: float = NAN
var _elements: Array = []
if not _string.empty() and _string[_string.length() - 1] == "=":
var _current_element: String = ""
for _count in _string.length():
if _string[_count].is_valid_float() or _string[_count] == ".": _current_element += _string[_count]
else:
if _string[_count - 1].is_valid_float() and (_string[_count + 1].is_valid_float() if _string[_count] != "=" else true):
_elements.append_array([_current_element,_string[_count]]) ; _current_element = ""
else: return NAN
if not _elements.empty():
_elements.resize(_elements.size() - 1)
while _get_operators_count(_elements) != 0:
var _id: Array = [0, 0.0, 0.0]
if "*" in _elements:
_id = _add_adjacent(_elements, "*") ; _remove_adjacent(_elements, _id[0]) ; _elements.insert(_id[0] - 1, _id[1] * _id[2])
elif "/" in _elements:
_id = _add_adjacent(_elements, "/") ; _remove_adjacent(_elements, _id[0]) ; _elements.insert(_id[0] - 1, _id[1] / _id[2])
elif "+" in _elements:
_id = _add_adjacent(_elements, "+") ; _remove_adjacent(_elements, _id[0]) ; _elements.insert(_id[0] - 1, _id[1] + _id[2])
elif "-" in _elements:
_id = _add_adjacent(_elements, "-") ; _remove_adjacent(_elements, _id[0]) ; _elements.insert(_id[0] - 1, _id[1] - _id[2])
else: return NAN
if _elements.size() == 1: _result = _elements[0]
return _result
func _get_operators_count(_elements: Array) -> int:
var _result: int = 0 ; for _element in _elements: if not str(_element).is_valid_float(): _result += 1 ; return _result
func _add_adjacent(_elements: Array, _operator) -> Array:
return [_elements.find(_operator), float(_elements[_elements.find(_operator) - 1]), float(_elements[_elements.find(_operator) + 1])]
func _remove_adjacent(_elements: Array, _operator_idx: int) -> void:
_elements.remove(_operator_idx + 1) ; _elements.remove(_operator_idx) ; _elements.remove(_operator_idx - 1)

Related

How to create Pascal?

I am very difficult to display all the output results.
this code.
DEF VAR INPUTAN AS INTEGER.
DEF VAR i AS INTEGER.
DEF VAR j AS INTEGER.
DEF VAR a AS INTEGER.
DEF VAR rows AS INT.
DEF VAR pascal AS CHAR FORMAT "x(25)".
SET INPUTAN.
a = 1.
REPEAT i = 0 TO INPUTAN:
rows = i.
DISPLAY rows.
REPEAT j = 0 TO i :
IF j = 0 OR j = i THEN DO:
a = 1.
END.
ELSE
a = a * (i + 1 - j) / j.
pascal = STRING(a).
display a.
END.
END.
DEF VAR INPUTAN AS INTEGER.
DEF VAR i AS INTEGER.
DEF VAR j AS INTEGER.
DEF VAR a AS INTEGER.
DEF VAR rows AS INT.
DEF VAR pascal AS CHAR.
SET INPUTAN.
a = 1.
REPEAT i = 0 TO INPUTAN:
rows = i.
/*DISPLAY rows. */
REPEAT j = 0 TO i :
IF j = 0 OR j = i THEN DO:
a = 1.
END.
ELSE
a = a * (i + 1 - j) / j.
IF j = 0 THEN
pascal = pascal + FILL(" ", INPUTAN - i).
pascal = pascal + STRING(a) + " ".
IF j = i THEN
pascal = pascal + CHR(13).
/* display a.*/
END.
END.
MESSAGE pascal
VIEW-AS ALERT-BOX INFO BUTTONS OK.

Why inside Let while loop does not work SML

i am new at Standard ML and i have a question , at the code below when
i run without the let-in structure , the code runs and gives result .When i put the the let-in
it shows syntax errors . Can anyone help me ?
fun findInd([],size, value , ans , l , h ) = ~1
| findInd(lista ,size, value , ans , l , h) =
let
val midval = Real.round((real l + real h) / real 2)
val Nelem = List.nth(lista,midval)
in
if l<=h then
if Nelem <= value then findInd(lista,size,value,midval,midval+1,h )
else findInd(lista,size,value,ans,l,midval+(~1) )
else
ans
end;
let (* <-- this let gives the problem *)
val s = 0
val sum = ref s
val maxlen = 0
val maxlenptr = ref maxlen
val counter_start = 0
val counter = ref counter_start
val arr = [1,5,~58,~1]
val presum = [~53,~52,1,6]
val minInd = [3,2,0,0
while !counter < List.length(arr) do (
sum := !sum + List.nth(arr,!counter);
if !sum >=0 then maxlenptr := !counter + 1
else
let
val ind = findInd(presum, List.length(arr) , s , ~1 ,0 , List.length(arr) + (~1) )
val temp = List.nth(minInd,ind)
in
if ind <> ~1 andalso temp < counter_start then maxlenptr := Int.max(!maxlenptr,counter_start + (~temp))
else ()
end;
counter := !counter + 1
);
val m = !maxlenptr
in (* <--- this in *)
m
end;
The syntax of let is let <declarations> in <expression> and a while loop is not a declaration. You'll need to move it after the in (like you did with the ifs in the other lets).

Python RSA Encryption Decryption

Im currently working on a project about the multiple encryption method! I am having a lot of trouble with RSA. I have a code that encrypt, give the public and the private key. Now I need to let someone write the private key and the encrypted text, and make the program decrypt it. I tried many times, ando got so many different erros that I deleted the decrypt function to do it over from start. Could anyone shine some ligth upon me? How to do, what should I do... Any help, really.
This is the code:
import random
def totient(number):
if(prime(number)):
return number-1
else:
return False
def prime(n):
if (n <= 1):
return False
if (n <= 3):
return True
if (n%2 == 0 or n%3 == 0):
return False
i = 5
while(i * i <= n):
if (n%i == 0 or n%(i+2) == 0):
return False
i+=6
return True
def generate_E(num):
def mdc(n1,n2):
rest = 1
while(n2 != 0):
rest = n1%n2
n1 = n2
n2 = rest
return n1
while True:
e = random.randrange(2,num)
if(mdc(num,e) == 1):
return e
def generate_prime():
while True:
x=random.randrange(1,100)
if(prime(x)==True):
return x
def mod(a,b):
if(a<b):
return a
else:
c=a%b
return c
def cipher(words,e,n):
tam = len(words)
i = 0
lista = []
while(i < tam):
letter = words[i]
k = ord(letter)
k = k**e
d = mod(k,n)
lista.append(d)
i += 1
return lista
def calculate_private_key(toti,e):
d = 0
while(mod(d*e,toti)!=1):
d += 1
return d
## MAIN
if __name__=='__main__':
text = input("Insert message: ")
p = generate_prime() # generates random P
q = generate_prime() # generates random Q
n = p*q # compute N
y = totient(p) # compute the totient of P
x = totient(q) # compute the totient of Q
totient_de_N = x*y # compute the totient of N
e = generate_E(totient_de_N) # generate E
public_key = (n, e)
print('Your public key:', public_key)
text_cipher = cipher(text,e,n)
print('Your encrypted message:', text_cipher)
d = calculate_private_key(totient_de_N,e)
print('Your private key is:', d)

I have written a path tracer using julia programming language but i think it is slow

I have changed my post and posted the whole of my code! Could someone tell me how can I optimize it?
import Base: *, +, -, /, ^
using Images
const Π = convert(Float64, π)
#define vector
mutable struct Vec3
x::Float64
y::Float64
z::Float64
end
function +(u::Vec3, v::Vec3)
Vec3(u.x+v.x, u.y+v.y, u.z+v.z)
end
function -(u::Vec3, v::Vec3)
Vec3(u.x-v.x, u.y-v.y, u.z-v.z)
end
function /(u::Vec3, v::Float64)
Vec3(u.x/v, u.y/v, u.z/v)
end
function *(u, v::Vec3)
if typeof(u) == Float64
Vec3(u*v.x, u*v.y, u*v.z)
elseif typeof(u) == Vec3
Vec3(u.x*v.x, u.y*v.y, u.z*v.z)
end
end
function ^(u::Vec3, v::Float64)
Vec3(u.x^v, u.y^v, u.z^v)
end
function dot(u::Vec3, v::Vec3)
u.x*v.x + u.y*v.y + u.z*v.z
end
function normalize(u::Vec3)
u/sqrt(dot(u,u))
end
function cross(u::Vec3, v::Vec3)
Vec3(u.y*v.z - v.y*u.z, u.z*v.x - v.z*u.x, u.x*v.y - v.x*u.y)
end
function gamma(u::Vec3)
Vec3(u.x^(1/2.2), u.y^(1/2.2), u.z^(1/2.2))
end
function clamp(u::Vec3)
u.x = u.x <= 1 ? u.x : 1
u.y = u.y <= 1 ? u.y : 1
u.z = u.z <= 1 ? u.z : 1
u
end
#define ray
struct Ray
s::Vec3
d::Vec3
end
#define planes
struct xyRect
z; x1; x2; y1; y2::Float64
normal; emittance; reflectance::Vec3
isLight::Bool
end
struct xzRect
y; x1; x2; z1; z2::Float64
normal; emittance; reflectance::Vec3
isLight::Bool
end
struct yzRect
x; y1; y2; z1; z2::Float64
normal; emittance; reflectance::Vec3
isLight::Bool
end
#define sphere
mutable struct Sphere
radius::Float64
center; normal; emittance; reflectance::Vec3
isLight::Bool
end
#define empty object
struct Empty
normal; emittance; reflectance::Vec3
end
#define surfaces
Surfaces = Union{xyRect, xzRect, yzRect, Sphere}
#define intersection function
function intersect(surface::Surfaces, ray::Ray)
if typeof(surface) == xyRect
t = (surface.z - ray.s.z)/ray.d.z
if surface.x1 < ray.s.x + t*ray.d.x < surface.x2 && surface.y1 < ray.s.y + t*ray.d.y < surface.y2 && t > 0
t
else
Inf
end
elseif typeof(surface) == xzRect
t = (surface.y - ray.s.y)/ray.d.y
if surface.x1 < ray.s.x + t*ray.d.x < surface.x2 && surface.z1 < ray.s.z + t*ray.d.z < surface.z2 && t > 0
t
else
Inf
end
elseif typeof(surface) == yzRect
t = (surface.x - ray.s.x)/ray.d.x
if surface.y1 < ray.s.y + t*ray.d.y < surface.y2 && surface.z1 < ray.s.z + t*ray.d.z < surface.z2 && t > 0
t
else
Inf
end
elseif typeof(surface) == Sphere
a = dot(ray.d, ray.d)
b = 2dot(ray.d, ray.s - surface.center)
c = dot(ray.s - surface.center, ray.s - surface.center) - surface.radius*surface.radius
Δ = b*b - 4*a*c
if Δ > 0
Δ = sqrt(Δ)
t1 = 0.5(-b-Δ)/a
t2 = 0.5(-b+Δ)/a
if t1 > 0
surface.normal = normalize(ray.s + t1*ray.d - surface.center)
t1
elseif t2 > 0
surface.normal = normalize(ray.s + t2*ray.d - surface.center)
t2
else
Inf
end
else
Inf
end
end
end
#define nearest function
function nearest(surfaces::Array{Surfaces, 1}, ray::Ray, tMin::Float64)
hitSurface = Empty(Vec3(0,0,0), Vec3(0,0,0), Vec3(0,0,0))
for surface in surfaces
t = intersect(surface, ray)
if t < tMin
tMin = t
hitSurface = surface
end
end
tMin, hitSurface
end
#cosine weighted sampling of hemisphere
function hemiRand(n::Vec3)
ξ1 = rand()
ξ2 = rand()
x = cos(2π*ξ2)*sqrt(ξ1)
y = sin(2π*ξ2)*sqrt(ξ1)
z = sqrt(1-ξ1)
r = normalize(Vec3(2rand()-1, 2rand()-1, 2rand()-1))
b = cross(n,r)
t = cross(n,b)
Vec3(x*t.x + y*b.x + z*n.x, x*t.y + y*b.y + z*n.y, x*t.z + y*b.z + z*n.z)
end
#trace the path
function trace(surfaces::Array{Surfaces, 1}, ray::Ray, depth::Int64, maxDepth::Int64)
if depth >= maxDepth
return Vec3(0,0,0)
end
t, material = nearest(surfaces, ray, Inf)
if typeof(material) == Empty
return Vec3(0,0,0)
end
if material.isLight == true
return material.emittance
end
ρ = material.reflectance
BRDF = ρ/Π
n = material.normal
R = hemiRand(n)
In = trace(surfaces, Ray(ray.s + t*ray.d, R), depth+1, maxDepth)
return Π*BRDF*In
end
#define camera
struct Camera
eye; v_up; N::Vec3
fov; aspect; distance::Float64
end
#render function
function render(surfaces::Array{Surfaces,1},camera::Camera,xRes::Int64,yRes::Int64,numSamples::Int64,maxDepth::Int64)
n = normalize(camera.N)
e = camera.eye
c = e - camera.distance*n
θ = camera.fov*(π/180)
H = 2*camera.distance*tan(θ/2)
W = H*camera.aspect
u = normalize(cross(camera.v_up,n))
v = cross(n,u)
img = zeros(3, xRes, yRes)
pixHeight = H/yRes
pixWidth = W/xRes
L = c - 0.5*W*u - 0.5*H*v
for i=1:xRes
for j=1:yRes
cl = Vec3(0,0,0)
for s=1:numSamples
pt = L + (i-rand())*pixWidth*u + (yRes-j+rand())*pixHeight*v
cl = cl + trace(surfaces, Ray(e, pt-e), 0, maxDepth)
end
cl = gamma(clamp(cl/convert(Float64, numSamples)))
img[:,j,i] = [cl.x, cl.y, cl.z]
end
end
img
end
#the scene
p1 = xzRect(1.,0.,1.,-1.,0.,Vec3(0,-1,0),Vec3(0,0,0),Vec3(0.75,0.75,0.75),false)
p2 = xzRect(0.,0.,1.,-1.,0.,Vec3(0,1,0),Vec3(0,0,0),Vec3(0.75,0.75,0.75),false)
p3 = xyRect(-1.,0.,1.,0.,1.,Vec3(0,0,1),Vec3(0,0,0),Vec3(0.75,0.75,0.75),false)
p4 = yzRect(0.,0.,1.,-1.,0.,Vec3(1,0,0),Vec3(0,0,0),Vec3(0.75,0.25,0.25),false)
p5 = yzRect(1.,0.,1.,-1.,0.,Vec3(-1,0,0),Vec3(0,0,0),Vec3(0.25,0.25,0.75),false)
p6 = xzRect(0.999,0.35,0.65,-0.65,-0.35,Vec3(0,-1,0),Vec3(18,18,18),Vec3(0,0,0),true)
s1 = Sphere(0.15,Vec3(0.3,0.15,-0.6),Vec3(0,0,0),Vec3(0,0,0),Vec3(0.75,0.75,0.75),false)
surfs = Surfaces[p1,p2,p3,p4,p5,p6,s1]
cam = Camera(Vec3(0.5,0.5,2),Vec3(0,1,0),Vec3(0,0,1),28.07,1,2)
#time image = render(surfs, cam, 400, 400, 1, 4);
colorview(RGB, image)
I need to know why my code is bad and slow. I am a beginner programmer and I don't have enough experience. My path tracer scene contains 7 objects, its maximum depth is 4, and it takes more than 2 seconds to generate an image of size 400*400. I think It shouldn't be that slow because my cpu is core i7 4770.
Sorry for changing my post.
To start with,
struct yzRect
x; y1; y2; z1; z2::Float64
normal; emittance; reflectance::Vec3
isLight::Bool
end
ends up only applying the type to the last variable for each line:
julia> fieldtypes(yzRect)
(Any, Any, Any, Any, Float64, Any, Any, Vec3, Bool)
so Julia will basically not know about any types in your structs which slows things down.
Also, your Vec3 should really be immutable and you then just create new instances of it when you want to "modify" the Vector.
There might be many more issues but those are two standing out.
Reading through https://docs.julialang.org/en/v1/manual/performance-tips/index.html and applying the guidelines in there is strongly recommended when analyzing performance.

Difficulty solving this with recursive code

I need to find the length of the longest common subsequence.
s and t are Strings, and n and m are their lengths. I would like to write a recursive code.
This is what I did so far but I cant get any progress:
def lcs_len_v1(s, t):
n = len(s)
m = len(t)
return lcs_len_rec(s,n,t,m)
def lcs_len_rec(s,size_s,t,size_t):
cnt= 0
if size_s==0 or size_t==0:
return 0
elif s[0]==t[0]:
cnt= +1
return cnt, lcs_len_rec(s[1:], len(s[1:]), t[1:], len(t[1:]))
This works:
def lcs(xstr, ystr):
if not xstr or not ystr:
return ""
x, xs, y, ys = xstr[0], xstr[1:], ystr[0], ystr[1:]
if x == y:
return x + lcs(xs, ys)
else:
return max(lcs(xstr, ys), lcs(xs, ystr), key=len)
print(lcs("AAAABCC","AAAACCB"))
# AAAACC
You should know that a recursive approach will only work with relatively trivial string; the complexity increases very rapidly with longer strings.
this is my code, how can I use on it the memoization technique?
def lcs_len_v1(s, t):
n = len(s)
m = len(t)
return lcs_len_rec(s,n,t,m)
def lcs_len_rec(s,size_s,t,size_t):
if size_s==0 or size_t==0:
return 0
elif s[0]==t[0]:
cnt=0
cnt+= 1
return cnt+ lcs_len_rec(s[1:], size_s-1, t[1:], size_t-1)
else:
return max(lcs_len_rec(s[1:], size_s-1, t, size_t), lcs_len_rec(s, size_s, t[1:], size_t-1))
Using the memoization technique, you can run the algorithm also with a very long strings. Infact it is just O(n^2):
def recursiveLCS(table, s1, s2):
if(table[len(s1)][len(s2)] != False):
return table[len(s1)][len(s2)]
elif len(s1) == 0 or len(s2) == 0:
val = ""
elif s1[0] == s2[0]:
val = s1[0] + recursiveLCS(table, s1[1:], s2[1:])
else:
res1 = recursiveLCS(table, s1[1:], s2)
res2 = recursiveLCS(table, s1, s2[1:])
val = res2
if len(res1) > len(res2):
val = res1
table[len(s1)][len(s2)] = val
return val
def computeLCS(s1, s2):
table = [[False for col in range(len(s2) + 1)] for row in range(len(s1) + 1)]
return recursiveLCS(table, s1, s2)
print computeLCS("testistest", "this_is_a_long_testtest_for_testing_the_algorithm")
Output:
teststest

Resources