i was given a homework by my instructor which i was supposed to upload into autograding system and i did.
And even though the program flawlessly works in my ruby interpreter, it prints an error in autograding system:
This is my output of the program:
Range: 1453-2011
Sum: 129339
Binary: 1 1 1 1 1 1 0 0 1 0 0 1 1 1 0 1 1
This is what resulted in autograding system:
❌ Example1
::error::The output for test Example1 did not match%0AExpected:%0ARange: 1453-2011%0ASum: 129339%0ABinary: 1 1 1 1 1 1 0 0 1 0 0 1 1 1 0 1 1%0AActual:%0ARange: 1453-2011%0ASum: 129339%0ABinary: 1 1 1 1 1 1 0 0 1 0 0 1 1 1 0 1 1
I didn't understand the reason why this error occurred at all. The output of my program is absolutely the same as the demanded output. Can you please explain?
It's basically a program that asks an input for which should be used to create an array with a range and the sum of the prime numbers within that range. It also asks for the binary representation of the sum of the prime numbers in that range:
# frozen_string_literal: true
def set_number(index1, index2) # Create an array with a range by asking the minimum and maximum points of the range specified by the user.
Array(index1..index2)
end
def prime?(number) # Is the number prime?
if number < 2
return false
elsif (2..Integer.sqrt(number)).each do
|divisor| if number % divisor == 0
return false
end
end
return number
end
end
def decimal_to_binary(number) # Convert the number from decimal to binary.
number = number.to_i
if number == 0
return 0
end
binary = []
while number != 0
binary = binary << String(number % 2)
number = number / 2
end
binary
end
index1, index2 = gets.chomp.split.map(&:to_i)
array = set_number(index1, index2)
puts "Range: #{index1}-#{index2}"
primes = []
array.each do |x|
primes << x if prime?(x)
end
sum = 0
primes.each {|element| sum = sum + element}
puts "Sum: #{sum}"
binary = decimal_to_binary(sum)
puts "Binary: #{binary.reverse.join(" " " ")}"
I expected the autograding system to verify the result which is correct and pass to the another example but it didn't.
Related
How can I get the number of iterations/steps that this method takes to find an answer?
def binary_search(array, n)
min = 0
max = (array.length) - 1
while min <= max
middle = (min + max) / 2
if array[middle] == n
return middle
elsif array[middle] > n
max = middle - 1
elsif array[middle] < n
min = middle + 1
end
end
"#{n} not found in this array"
end
One option to use instead of a counter is the .with_index keyword. To use this you'll need to use loop instead of while, but it should work the same. Here's a basic example with output.
arr = [1,2,3,4,5,6,7,8]
loop.with_index do |_, index| # The underscore is to ignore the first variable as it's not used
if (arr[index] % 2).zero?
puts "even: #{arr[index]}"
else
puts "odd: #{arr[index]}"
end
break if index.eql?(arr.length - 1)
end
=>
odd: 1
even: 2
odd: 3
even: 4
odd: 5
even: 6
odd: 7
even: 8
Just count the number of iterations.
Set a variable to 0 outside the loop
Add 1 to it inside the loop
When you return the index, return the count with it (return [middle, count]).
I assume the code to count numbers of interations required by binary_search is to be used for testing or optimization. If so, the method binary_search should be modified in such a way that to produce production code it is only necessary to remove (or comment out) lines of code, as opposed to modifying statements. Here is one way that might be done.
def binary_search(array, n)
# remove from production code lines marked -> #******
_bin_srch_iters = 0 #******
begin #******
min = 0
max = (array.length) - 1
loop do
_bin_srch_iters += 1 #******
middle = (min + max) / 2
break middle if array[middle] == n
break nil if min == max
if array[middle] > n
max = middle - 1
else # array[middle] < n
min = middle + 1
end
end
ensure #******
puts "binary_search reqd #{_bin_srch_iters} interations" #******
end #******
end
x = binary_search([1,3,6,7,9,11], 3)
# binary_search reqd 3 interations
#=> 1
binary_search([1,3,6,7,9,11], 5)
# binary_search reqd 3 interations
#=> nil
I have a matrix of N rows of binary vectors, i.e.
mymatrix = [ 1 0 0 1 0;
1 1 0 0 1;
0 1 1 0 1;
0 1 0 0 1;
0 0 1 0 0;
0 0 1 1 0;
.... ]
where I'd like to find the combinations of rows that, when added together, gets me exactly:
[1 1 1 1 1]
So in the above example, the combinations that would work are 1/3, 1/4/5, and 2/6.
The code I have for this right now is:
i = 1;
for j = 1:5
C = combnk([1:N],j); % Get every possible combination of rows
for c = 1:size(C,1)
if isequal(ones(1,5),sum(mymatrix(C(c,:),:)))
combis{i} = C(c,:);
i = i+1;
end
end
end
But as you would imagine, this takes a while, especially because of that combnk in there.
What might be a useful algorithm/function that can help me speed this up?
M = [
1 0 0 1 0;
1 1 0 0 1;
0 1 1 0 1;
0 1 0 0 1;
0 0 1 0 0;
0 0 1 1 0;
1 1 1 1 1
];
% Find all the unique combinations of rows...
S = (dec2bin(1:2^size(M,1)-1) == '1');
% Find the matching combinations...
matches = cell(0,1);
for i = 1:size(S,1)
S_curr = S(i,:);
rows = M(S_curr,:);
rows_sum = sum(rows,1);
if (all(rows_sum == 1))
matches = [matches; {find(S_curr)}];
end
end
To display your matches in a good stylized way:
for i = 1:numel(matches)
match = matches{i};
if (numel(match) == 1)
disp(['Match found for row: ' mat2str(match) '.']);
else
disp(['Match found for rows: ' mat2str(match) '.']);
end
end
This will produce:
Match found for row: 7.
Match found for rows: [2 6].
Match found for rows: [1 4 5].
Match found for rows: [1 3].
In terms of efficiency, in my machine this algoritm is completing the detection of matches in about 2 milliseconds.
I wrote code to find how many operations a number required under the Collatz Conjecture. However, my operations variable doesn't seem to be incrementing.
My code is:
puts "Please input a number"
number = gets.chomp
number = number.to_i
operations = 0
modulo = number % 2
while number =! 1
if modulo == 0
number = number / 2
operations = operations + 1
elsif modulo =! 0 && number =! 1
number = number * 3
number = number += 1
operations = operations + 2
else
puts "Uh oh, something went wrong."
end
end
puts "It took #{operations} operations!"
I am running this code on https://www.repl.it.
First of all, it's elsif; not elseif (I edited that in your question). And unequal sign is !=; not =!. But that has a somewhat different meaning. (i.e.: number =! 1 means number = !1)
In the 12th line, what is number = number += 1? I think you meant number += 1 or number = number + 1.
Now, the code works. :)
Here's the final version.
puts "Please input a number"
number = gets.chomp
number = number.to_i
operations = 0
modulo = number % 2
while number != 1
if modulo == 0
number = number / 2
operations = operations + 1
elsif modulo != 0 && number != 1
number = number * 3
number = number + 1
operations = operations + 2
else
puts "Uh oh, something went wrong."
end
end
puts "It took #{operations} operations!"
Usage:
Please input a number
256
It took 8 operations!
An optimal solution using functions:
def collatz(n)
if n % 2 == 0
return n / 2
else
return 3*n + 1
end
end
def chainLength(num)
count = 1
while num > 1
count += 1
num = collatz(num)
end
return count
end
puts "Please input a number"
number = gets.chomp
number = number.to_i
operations = chainLength(number)
puts "It took #{operations} operations!"
If you need more performance, read about dynamic programming and memoization techniques.
I wrote a program in SciLab that solves sudoku's.
But it can only solve sudoku's that always have a square with 1 possible value.
Like very easy and easy sudoku's on brainbashers.com .
Medium sudoku's always reach a point that they do not have a square with 1 possible value.
How can I modify my code to solve these, more difficult sudoku's?
///////////////////////////////////////////////////////////////////////////
////////////////////////// Check Sudoku ///////////////////////////////
///////////////////////////////////////////////////////////////////////////
function r=OneToNine(V) // function checks if the given vector V contains 1 to 9
r = %T // this works
u = %F
index = 1
while r == %T & index < 10
for i=1 : length(V)
if V(i)==index then
u = %T
end
end
index=index+1
if u == %F then r = %F
else u = %F
end
end
if length(V) > 9 then r = %F
end
endfunction
function y=check(M) // Checks if the given matrix M is a solved sudoku
y = %T // this works too
if size(M,1)<>9 | size(M,2)<>9 then // if it has more or less than 9 rows and columns
y = %F // we return false
end
for i=1 : size(M,1) // if not all rows have 1-9 we return false
if OneToNine(M(i,:)) == %F then
y = %F
end
end
endfunction
function P=PossibilitiesPosition(board, x, y)
// this one works
// we fill the vector possibilites with 9 zeros
// 0 means empty, 1 means it already has a value, so we don't need to change it
possibilities = [] // a vector that stores the possible values for position(x,y)
for t=1 : 9 // sudoku has 9 values
possibilities(t)=0
end
// Check row f the value (x,y) for possibilities
// we fill the possibilities further by puttin '1' where the value is not possible
for i=1 : 9 // sudoku has 9 values
if board(x,i) > 0 then
possibilities(board(x,i))=1
end
end
// Check column of the value (x,y) for possibilities
// we fill the possibilities further by puttin '1' where the value is not possible
for j=1 : 9 // sudoku has 9 values
if board(j, y) > 0 then
possibilities(board(j, y))=1
end
end
// Check the 3x3 matrix of the value (x,y) for possibilities
// first we see which 3x3 matrix we need
k=0
m=0
if x >= 1 & x <=3 then
k=1
else if x >= 4 & x <= 6 then
k = 4
else k = 7
end
end
if y >= 1 & y <=3 then
m=1
else if y >= 4 & y <= 6 then
m = 4
else m = 7
end
end
// then we fill the possibilities further by puttin '1' where the value is not possible
for i=k : k+2
for j=m : m+2
if board(i,j) > 0 then
possibilities(board(i,j))=1
end
end
end
P = possibilities
// we want to see the real values of the possibilities. not just 1 and 0
for i=1 : 9 // sudoku has 9 values
if P(i)==0 then
P(i) = i
else P(i) = 0
end
end
endfunction
function [x,y]=firstEmptyValue(board) // Checks the first empty square of the sudoku
R=%T // and returns the position (x,y)
for i=1 : 9
for j=1 : 9
if board(i,j) == 0 & R = %T then
x=i
y=j
R=%F
end
end
end
endfunction
function A=numberOfPossibilities(V) // this checks the number of possible values for a position
A=0 // so basically it returns the number of elements different from 0 in the vector V
for i=1 : 9
if V(i)>0 then
A=A+1
end
end
endfunction
function u=getUniquePossibility(M,x,y) // this returns the first possible value for that square
pos = [] // in function fillInValue we only use it
pos = PossibilitiesPosition(M,x,y) // when we know that this square (x,y) has only one possible value
for n=1 : 9
if pos(n)>0 then
u=pos(n)
end
end
endfunction
///////////////////////////////////////////////////////////////////////////
////////////////////////// Solve Sudoku ///////////////////////////////
///////////////////////////////////////////////////////////////////////////
function G=fillInValue(M) // fills in a square that has only 1 possibile value
x=0
y=0
pos = []
for i=1 : 9
for j=1 : 9
if M(i,j)==0 then
if numberOfPossibilities(PossibilitiesPosition(M,i,j)) == 1 then
x=i
y=j
break
end
end
end
if x>0 then
break
end
end
M(x,y)=getUniquePossibility(M,x,y)
G=M
endfunction
function H=solve(M) // repeats the fillInValue until it is a fully solved sudoku
P=[]
P=M
if check(M)=%F then
P=fillInValue(M)
H=solve(P)
else
H=M
end
endfunction
//////////////////////////////////////////////////////////////////////////////
So it solves this first one
// Very easy and easy sudokus from brainbashers.com get solved completely
// Very Easy sudoku from brainbashers.com
M = [0 2 0 0 0 0 0 4 0
7 0 4 0 0 0 8 0 2
0 5 8 4 0 7 1 3 0
0 0 1 2 8 4 9 0 0
0 0 0 7 0 5 0 0 0
0 0 7 9 3 6 5 0 0
0 8 9 5 0 2 4 6 0
4 0 2 0 0 0 3 0 9
0 1 0 0 0 0 0 8 0]
But it doens't solve this medium:
M2= [0 0 6 8 7 1 2 0 0
0 0 0 0 0 0 0 0 0
5 0 1 3 0 9 7 0 8
1 0 7 0 0 0 6 0 9
2 0 0 0 0 0 0 0 7
9 0 3 0 0 0 8 0 1
3 0 5 9 0 7 4 0 2
0 0 0 0 0 0 0 0 0
0 0 2 4 3 5 1 0 0]
Error code when trying to solve medium sudoku:
-->solve(M2)
!--error 21
Invalid index.
at line 14 of function PossibilitiesPosition called by :
at line 3 of function getUniquePossibility called by :
at line 20 of function fillInValue called by :
at line 182 of function solve called by :
at line 183 of function solve called by :
at line 183 of function solve called by :
at line 183 of function solve called by :
at line 183 of function solve called by :
solve(M2)
at line 208 of exec file called by :
_SCILAB-6548660277741359031.sce', 1
while executing a callback
Well, one of the easiest way to program a Sudoku solver (not the most efficient) could be to solve each cell with all the possible options recursively (which could be similar to the "Backtracking" algorithm) until a full answer is found.
Another options (I would say it's better) is to iterate trough all the squares solving all the "simple" squares and storing the possible answers in the others squares, then repeat (now you have some more solved), repeat the process until the Sudoku is solved or no more squares can be solved directly. Then you could try the rest with brute-force or Backtracking (maybe half or more of the Sudoku is already solved, so it may be relatively efficient)
Anyway,with a quick search I found this Wikipedia page where some Sudoku solving algorithms are explained with pseudo-code examples, hopefully these will be useful to you
I want to write a loop that scans all binary sequences of length n with k 1's and n-k 0's.
Actually, in each iteration an action is performed on the sequence and if a criterion is met the loop will break, otherwise it goes to next sequence. (I am not looking for nchoosek or perms since for large values of n it takes so much time to give the output).
What MATLAB code do you suggest?
You could implement something like an iterator/generator pattern:
classdef Iterator < handle
properties (SetAccess = private)
n % sequence length
counter % keeps track of current iteration
end
methods
function obj = Iterator(n)
% constructor
obj.n = n;
obj.counter = 0;
end
function seq = next(obj)
% get next bit sequence
if (obj.counter > 2^(obj.n) - 1)
error('Iterator:StopIteration', 'Stop iteration')
end
seq = dec2bin(obj.counter, obj.n) - '0';
obj.counter = obj.counter + 1;
end
function tf = hasNext(obj)
% check if sequence still not ended
tf = (obj.counter <= 2^(obj.n) - 1);
end
function reset(obj)
% reset the iterator
obj.counter = 0;
end
end
end
Now you can use it as:
k = 2;
iter = Iterator(4);
while iter.hasNext()
seq = iter.next();
if sum(seq)~=k, continue, end
disp(seq)
end
In the example above, this will iterate through all 0/1 sequences of length 4 with exactly k=2 ones:
0 0 1 1
0 1 0 1
0 1 1 0
1 0 0 1
1 0 1 0
1 1 0 0