unable to run Mozart code - mozart

local MainSum in
fun {MainSum N}
local Sum in
fun {Sum N Acc}
if N==0 then Acc
else Acc+{Sum N-1 N*N}
end
end
{Sum 5 0}
end
end
end
When i Try this codes it shows following error
%************************** syntax error ************************
%**
%** nesting marker expected as designator of nested function
%**
%** in file "exercise.oz", line 2, column 7
%** ------------------ rejected (1 error)

You code work on my computer... But you didn't use the argument of MainSum
I believe that's what you wanted to do:
local MainSum in
fun {MainSum N}
local Sum in
fun {Sum N Acc}
if N==0 then Acc
else Acc+{Sum N-1 N*N}
end
end
{Sum N 0}
end
end
{Browse {MainSum 5}}
end
which can be written, using a more concise notation, and using terminal recursion!
local
fun{MainSum N}
fun{Sum N Acc}
if N==0 then Acc
else {Sum N-1 N*N+Acc}
end
end
in
{Sum N 0}
end
in
{Browse {MainSum 5}}
end

Related

Ruby fiber additional resume

In this example, the fiber is resumed once more to create one more output unexpectedly. The target is to print all the permutation of one array of numbers by iterating through all the possibilities with recursion and print out the result in a fiber.
class Fiber
def self.wrap
if block_given?
f=Fiber.new do |*args|
yield *args
end
return lambda{|*args| f.resume(*args) if f.alive? }
end
end
end
class FiberIterator
def initialize
#fiber_wrap=Fiber.wrap do
yield
end
end
def each
while value=#fiber_wrap.call
yield value
end
end
end
def perm(a)
FiberIterator.new{ permgen(a,a.size) }
end
def permgen (a, n)
if n == 0 then
Fiber.yield a
else
n.times do |i|
a[n-1], a[i] = a[i], a[n-1]
permgen(a, n - 1)
a[n-1], a[i] = a[i], a[n-1]
end
end
end
def printResult (a)
p a
end
it=perm([1,2,3,4])
for a in it
printResult(a)
end
The result will include an additional 3 after print out all the permutations have been printed. Could anyone help with this?
The reason is that n.times returns n:
1.times { } # => 1
and the return value from permgen is being caught and evaluated as part of it and thus printed out. Too tired atm to go through and fully understand what's yielded or resumed where and when to try and explain how it's getting caught up and printed as if it was a permutation, but you can fix the code by just changing permgen to:
def permgen (a, n)
if n == 0 then
Fiber.yield a
else
n.times do |i|
a[n-1], a[i] = a[i], a[n-1]
permgen(a, n - 1)
a[n-1], a[i] = a[i], a[n-1]
end
nil # << This is all I added
end
end
As a side note, when I ran your code it was printing a 4 not a 3 at the end, based this answer on that being a typo or the result of a different array or playing around with different sized permutations.

Palindrome product

I'm trying to find the largest product of 2 three-digit numbers that is a palindrome. The answer is 993 * 913 = 906609.
This is my code:
x = 123
until x == x.to_s.reverse.to_i
999.downto(100) do |i|
i.downto(100) do |j|
x = i * j
puts "#{i} * #{j} = #{x}"
end
end
end
puts x
I wrapped everything in an until statement that is supposed to check its palindrome-ness, but my code keeps going on even after it hits the correct value. Does anyone see what I am doing incorrectly here?
Even if your code worked, it would pick 995 * 585 = 580085 as there is no logic to pick the palindrome with highest value.
So, you may want to collect all palindromes in an array and then find max from that array as shown below:
arr = []
999.downto(100) do |i|
i.downto(100) do |j|
x = i * j
arr << x if x.to_s == x.to_s.reverse
end
end
p arr.max
#=> 906609
Try and think about what you are telling your code to do in plain english:
"Until x is a palindrome, do this doubly nested loop to completion"
The until loop is never breaking because it is FULLY running both loops BEFORE checking if x is a palindrome. The solution would be to instead break when you find a palindrome Try this:
999.downto(100) do |i|
i.downto(100) do |j|
x = i * j
break if x == x.to_s.reverse.to_i
puts "#{i} * #{j} = #{x}"
end
break if x == x.to_s.reverse.to_i
end
puts x
Ah but now we have arrived at another problem - looping in this way does not guarantee that the product will be the highest product. We can modify slightly to achieve this:
palindromes = []
999.downto(100) do |i|
i.downto(100) do |j|
x = i * j
palindromes << x if x == x.to_s.reverse.to_i
end
end
puts palindromes.max
This probably isn't the best solution, but it works.
The problem is that the condition is never being checked, as the inner loops run until they finish without returning the execution to the until loop
You could to it this way
x = 123
999.downto(100) do |i|
i.downto(100) do |j|
x = i * j
puts "#{i} * #{j} = #{x}"
break if x == x.to_s.reverse.to_i
end
end
puts x
Anyway this (as your initial solution if it worked) will not give you the biggest palindrome, but the first one it finds.
The outer until loop is controlled by the condition x == x.to_s.reverse.to_i, but the inner two downto loops are not controlled by that condition. When the condition is satisfied in the middle of the two downto loops, that does not have any effect in stopping in the middle of the two downto loops, it only stops the until loop from continuing to the next iteration.
As pointed out by Wand Maker, it also does not give the correct result even if it worked. The problem is with the order of iteration. You are decrementing i and j in the order such as:
...
..., [i, j], [i, j - 1], ...,
..., [i - 1, j], [i -1, j - 1], ...,
...
Under this order, you are assuming for example that i * (j - 1) is greater than (i - 1) * j, and hence if they both satisfy the condition, the earlier among them, i * (j - 1), should be picked as the greater number, stopping the iteration to go on to the latter. But that assumption about the ordering is wrong.

Comma assignment (why right go first?) i.e. n,m = 1, 2?

In the process of figuring out blocks and yields I came across these comma-separated assignments:
def fibit
n,m =1,1
loop do |variable|
yield n
n,m = m,n+m # this line
puts "n is #{n} m is #{m}"
end
end
fibit do |num|
puts "Next : #{num}"
break if num > 100
end
Why does the m get assigned first in this scenario?
Does the last one always go first? If so why?
This was also seen as only e has the value of 1 meaning e went first?
e,r=1
puts r
puts "-------"
puts e
Also, does anyone have an idea why the code-block versions just executes, where if I write the same code with no code block I actually need to call the method for it to run?
def fibit
n,m =1,1
loop do |variable|
puts "Next : #{n}"
break if n > 100
n,m = m,n+m
end
end
fibit
If I didn't have the last line it wouldn't run. Where in the first one I don't actually call the fibit method? Or is the block kicking it off?
m does not get assigned first. When using multiple assignments, all right hand side calculations are done before any assignment to the left hand side.
That's how this code works:
a = 1
b = 3
a, b = b, a
a
# => 3
b
# => 1
This would not be possible if the assignment was done serially, since you would get that both would be either equal 1 or 3.
To further prove my point, simply swap the assignment of n and m in your code, and you'll find that the result is the same:
def fibit
n,m =1,1
loop do |variable|
yield n
m,n = n+m,m # this line
puts "n is #{n} m is #{m}"
end
end
fibit do |num|
puts "Next : #{num}"
break if num > 100
end

Pascal's Triangle in Ruby

I am writing Pascal's triangle in Ruby, but keep getting the error message:
pascalsTriangle.rb:3:in 'triangle': undefined method `each' for
4:Fixnum (NoMethodError) from pascalsTriangle.rb:18
def triangle(n)
for r in n:
lst=[1]
term=1
k=0
(0..r+1).step(1){ |index|
term=term*(r-k+1)/k
lst.append(term)
k+=1
}
print lst
end
end
triangle(4)
Why code C style in Ruby? :-)
Breaking the problem down would allow you to concentrate on one problem at a time and iterators would make the code more readable. I'm using the binomial theorem to calculate the values in the triangle. If you don't need a super large value from the triangle, this will be fast enough.
Calculating the 1000th line took 2.9 seconds on my virtual linux:
# factorial method
def fact(n)
(1..n).reduce(:*)
end
# binomial theorem, n choose k
def binomial(n,k)
return 1 if n-k <= 0
return 1 if k <= 0
fact(n) / ( fact(k) * fact( n - k ) )
end
def triangle(nth_line)
(0..nth_line).map { |e| binomial(nth_line, e) }
end
p triangle(5)
the final source code:
def triangle(n)
(0..n).each{|r|
lst=[1]
term=1
k=1
(0..r-1).step(1){|index|
term=term*(r-k+1)/k
lst.push term
k+=1
}
p lst
}
end
triangle(4)
changes:
you have syntax error on for r in n:.
a logical error on k=0 that causes Division by zero.
(0..r+1) is changed to (0..r-1)
there is no append method for array. changed to push
p is used instead of print
Factorial(num), takes a number and return the factorial of it.
find_num(n, k), is the mathmatical formula of pascales triangle. !n/
!k * !(n - k) ---- '!' = factorial of number
Lastly pascale(num), this iterates a new row of the triangle by
maping the index numbers or (k) for each row of (n).
If you want to truly understand how this works comment out the
pascale, and simply run numbers through find_num((row number),
(index number)). Then compare to a picture of the triangle to see
the magic for your self
-
def find_num(n, k)
result = factorial(n) / (factorial(k) * factorial(n - k))
end
def pascale(num)
i = 0
scale = 75
while i <= num
new_arr = []
(0..i).map {|x| new_arr << find_num(i, x)}
p new_arr.to_s.rjust(50 + scale)
i += 1
scale += 1
end
def factorial(num)
if num == 0
return 1
else
num *= factorial(num - 1)
end
end
end
pascale(12)

Ruby - determine if a number is a prime

I'm running through the problems on Project Euler to teach myself Ruby programming. I know there is a built-in function to do this, but I'm avoiding the built-in functions to help me learn.
So I have to write a method to determine if a number is a prime. The first method works, but the second doesn't. Can anyone explain why?
def is_prime n
for d in 2..(n - 1)
if (n % d) == 0
return false
end
end
true
end
def is_prime2 n
foundDivider = false
for d in 2..(n - 1)
foundDivider = ((n % d) == 0) or foundDivider
end
not foundDivider
end
It's because = is of higher precedence than or. See Ruby's operator precedence table below (highest to lowest precedence):
[ ] [ ]=
**
! ~ + -
* / %
+ -
>> <<
&
^ |
<= < > >=
<=> == === != =~ !~
&&
||
.. ...
? :
= %= { /= -= += |= &= >>= <<= *= &&= ||= **=
defined?
not
or and
if unless while until
begin/end
The problematic line is being parsed as...
(foundDivider = ((n % d) == 0)) or foundDivider
...which is certainly not what you mean. There are two possible solutions:
Force the precedence to be what you really mean...
foundDivider = (((n % d) == 0) or foundDivider)
...or use the || operator instead, which has higher precedence than =:
foundDivider = ((n % d) == 0) || foundDivider
Ruby comes with predefined classes such as Prime. All you have to do is to require that class into your project.
require 'prime'
Than, you can use some of the Prime methods such as first to get first x prime elements:
Prime.first(5) # Ret => [2, 3, 5, 6, 11]
Or you could do something like this:
Prime.each(100) do |prime|
p prime # Ret => [2, 3, 5, 7, 11, ..., 97]
end
I hope you find this useful.
def prime(n)
return false if n < 2
(2..n/2).none?{|i| n % i == 0}
end
A prime number is any number that has no positive divisors other than itself and 1.
def prime? n
(2..Math.sqrt(n)).none? {|f| n % f == 0}
end
The range of factors should start at 2 and end at the square root of n because every number is divisible by one and no number is divisible by two numbers greater than its square root.
Explanation: A non-prime number is the product of two numbers.
n = f1 * f2
n is always divisible by its square root so both f1 and f2 cannot be greater than the square root of n, otherwise f1 * f2 would be greater than n. Therefore, at least one factor is less than or at most equal to Math.sqrt(n). In the case of finding prime numbers its only necessary to find one factor so we should loop from 2 to the square root of n.
Find prime numbers from loop:
def get_prime_no_upto(number)
pre = [1]
start = 2
primes = (start..number).to_a
(start..number).each do |no|
(start..no).each do |num|
if ( no % num == 0) && num != no
primes.delete(no)
break
end
end
end
pre + primes
end
and use it as below:
puts get_prime_no_upto(100)
Cheers!
Here is code that will prompt you to enter a number for prime check:
puts "welcome to prime number check"
puts "enter number for check: "
n = gets
n = n.to_i
def prime(n)
puts "That's not an integer." unless n.is_a? Integer
is_prime = true
for i in 2..n-1
if n % i == 0
is_prime = false
end
end
if is_prime
puts "#{n} is prime!"
else
puts "#{n} is not prime."
end
end
prime(n)
Based on the answer by Darmouse but including edge cases
def prime? (n)
if n <= 1
false
elsif n == 2
true
else
(2..n/2).none? { |i| n % i == 0}
end
end
FYI - re: DarkMouses prime method above - I found it really helpful, but there are a few errors (I think!) that need explaining:
It should be parentheses rather than square brackets... Otherwise you get a TypeError
Range can't be coerced into Fixnum (TypeError)
Secondly, that first colon before 'false' would cause an error too. It's incorrect syntax, as far as I know. Get rid of it.
Lastly, I think you got it the wrong way round?? If you correct the errors I mentioned, it returns true if it ISN'T a prime, and false if it IS.
You can drop the ternary operator altogether I think, and just do:
def prime?(n)
(2..n/2).none?{|i| n % i == 0}
end
Obviously it doesn't cover the edge cases (0,1,2), but let's not split hairs.
...For those who enjoy hairsplitting, here is my full solution to this problem:
def prime?(n)
return false if n < 2
(2..Math.sqrt(n)).none? {|num| length % num == 0}
end
Hope I didn't miss anything :)
This is a little bit off topic according to the details, but correct for the title : using bash integration in ruby you could do :
def is_prime n
`factor #{n}`.split.count < 3
end
bash factor function returns a number plus all of his factors, so if the number is prime, there will be two words count.
This is usefull for code golf only.
I tried this and it worked:
def prime?(n)
return false if n < 2
return true if n == 3 || n == 2
if (2...n-1).any?{|i| n % i == 0}
false
else
true
end
end
def prime?(n)
if n <= 1
return false
else (2..n-1).to_a.all? do |integer|
n % integer != 0
end
end
end
From my prime? lab. Started with eliminating all integers less than or equal to 1.
def prime(n)
pn = [2]
if n < 2
return false
else
(2..n).each do |i|
not_prime = false
(2..Math.sqrt(i).ceil).each do |j|
not_prime = true if i % j == 0
end
pn.push(i) unless not_prime
end
end
return pn
end
p prime(30) gives
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
It will return true if the number is prime.
def prime_number(number)
(2..(number-1)).each do |value|
if (number % value) == 0
return false
end
return true
end
end
puts prime_number(4)
class Object
private
def prime? num
if (2..3).include? num
return true
else
!num.even? and num % 3 != 0 and num > 1
end
end
end
prime? 1
prime? 2
prime? 9
prime? 17
** FOR A SIMPLE SHORTED METHOD**
FIRST INSTALL PRIME GEM
require 'prime'
`p prime.first(20)`
Now save that file as your desired name, this will generate the first 20 prime numbers Automatically!! :-)

Resources