Best way to handle multiple checks ruby - ruby

So I'm trying to write a converter for HSL to RGB (and eventually into hex)
I'm following this colorspace conversion theory and I seem to be stuck on step 6
Now we need to do up to 3 tests to select the correct formula for each
color channel. Let’s start with Red.
test 1 – If 6 x temporary_R is smaller then 1, Red = temporary_2 +
(temporary_1 – temporary_2) x 6 x temporary_R In the case the first
test is larger then 1 check the following
test 2 – If 2 x temporary_R is smaller then 1, Red = temporary_1 In
the case the second test also is larger then 1 do the following
test 3 – If 3 x temporary_R is smaller then 2, Red = temporary_2 +
(temporary_1 – temporary_2) x (0.666 – temporary_R) x 6 In the case
the third test also is larger then 2 you do the following
Red = temporary_2
Ok lets do it for our Red value
6 x temporary_R = 6 x 0.869 = 5.214, so it’s larger then 1, we need to
do test 2 2 x temporary_R = 2 x 0.869 = 1.738, it’s also larger then
1, we need to do test 3 3 x temporary_R = 3 x 0.869 = 2.607, it’s
larger then 2, so we go for the last formula Red = temporary_2 =
0.0924 which rounded down is 0.09, which is a number we recognize from the RGB to HSL conversion
So far I've monkey patched a function to take my HSL colours
def toRGB(hue, sat, lum)
temp_1 =
case lum
when lum < 0.0
lum x (1.0 * sat)
when lum > 0.0
(lum + sat) - lum
end
temp_2 = (2 * lum) - temp_1.to_f
h = (hue/360.0).round(4)
temp_r = (h + 0.333).round(4)
temp_r = temp_r + 1 if temp_r < 0
temp_r = temp_r - 1 if temp_r > 1
temp_g = h
temp_b = (h - 0.333).round(4)
temp_b = temp_b + 1 if temp_b < 0
temp_b = temp_b - 1 if temp_b > 1
red =
#test 1
#test 2
#test 3
"#{red}"
end
I was trying to use a case statement
red =
case temp_r
when 6 * temp_r < 1
temp_2 + (temp_1 - temp_2) * 6 * temp_r
when 2 * temp_r < 1
temp_1
when 3 * temp_r < 2
temp_2 + (temp_1 - temp_2) * (0.666 - temp_r * 6)
end
but then I started re-reading the instructions and now I can't really see a way to do what I need in ruby. Maybe I'm over-thinking it.
If you want to see the rest of my code in context you can see it here

There are two things I noticed in your code snippet:
You are mixing two types of switch case statement in ruby.
case a
when 1..5
"It's between 1 and 5"
when 6
"It's 6"
end
case
when a > 1 && a < 5
"It's between 1 and 5"
when a == 6
"It's 6"
end
See a difference, in first case when you directly compare cases, you've to mention the variable name you're comparing with, while in second case you're comparing with true & false condition by explicitly putting a condition on your variable so you don't need to put it next to case.
The second thing is as per your condition statement, you'll need an else case in your case statement.
red =
case
when 6 * temp_r < 1
temp_2 + (temp_1 - temp_2) * 6 * temp_r
when 2 * temp_r < 1
temp_1
when 3 * temp_r < 2
temp_2 + (temp_1 - temp_2) * (0.666 - temp_r * 6)
else
temp_2
end

Related

For loop variables get changed in Fortran

I am using the finite element method and separating a unit isosceles triangle into triangles with six nodes. While calculating coordinates of the nodes I noticed that the variables in the for loop get messed up for some reason and I cannot figure out why. Here is my code:
PROGRAM triangle
IMPLICIT NONE
INTEGER, PARAMETER :: stepSize = 4
INTEGER, PARAMETER :: numberOfNodes = ((2*stepSize - 1) * (2*stepSize)) / 2
INTEGER :: i, j, counter
REAL, DIMENSION(2, numberOfNodes) :: nodeCoordinates
counter = 0
DO j = 1, 2*stepSize - 1
DO i = 1, 2*stepSize - 1 - counter
nodeCoordinates(1, i + (j-1)*(2*stepSize - 1)) = ((REAL(i-1)) / REAL(2*stepSize - 2))
nodeCoordinates(2, i + (j-1)*(2*stepSize - 1)) = ((REAL(j-1)) / REAL(2*stepSize - 2))
END DO
counter = counter + 1
END DO
END PROGRAM triangle
When I print the variable j in the inner for loop, the following is shown:
1
1
1
1
1
1
1
2
2
2
2
2
2
3
3
3
3
3
4
4
4
4
0
0
0
1
1
2

Analyzing a recursive algorithm

I'm trying to figure out this algorithm that accepts an input of an int and should return an output of the sum of each element in the int.
# Input -> 4321
# output -> 10 (4+3+2+1)
def sum_func(n):
# Base case
if len(str(n)) == 1:
return n
# Recursion
else:
return n%10 + sum_func(n/10)
When Trying to break apart this algorithm this is what I come up with
1st loop -> 1 + 432 = 433
2nd loop -> 2 + 43 = 45
3rd loop -> 3 + 4 = 7
4th loop -> 4 + 4 = 8
How was it able to come up with the result of 10?
Unwinding, it would look like this:
sum_func(4321)
= 1 + sum_func(432)
= 1 + 2 + sum_func(43)
= 1 + 2 + 3 + sum_func(4)
= 1 + 2 + 3 + 4
When trying to understand recursion you'll have to clearly understand what is returned.
In this case function sum_func(n) returns the sum of the digits in it's argument n.
For concrete n task is divided into last_digit_of_n + sum_func(n_without_last_digit).
For example,
sum_func(4321) =
sum_func(432) + 1 =
sum_func(43) + 2 + 1 =
sum_func(4) + 3 + 2 + 1 =
4 + 3 + 2 + 1
Hope this helps.
(As a side note, checking if n has more than one digit using str is a bad idea. Better just to check if n <= 9)
You must reach the base case before the summation occurs:
Iteration 1: 1 + sum_func(432)
Iteration 2: 1 + 2 + sum_func(43)
Iteration 3: 1 + 2 + 3 + sum_func(4) = 1 + 2 + 3 + 4 = 10

Approach and Code for o(log n) solution

f(N) = 0^0 + 1^1 + 2^2 + 3^3 + 4^4 + ... + N^N.
I want to calculate (f(N) mod M).
These are the constraints.
1 ≤ N ≤ 10^9
1 ≤ M ≤ 10^3
Here is my code
test=int(input())
ans = 0
for cases in range(test):
arr=[int(x) for x in input().split()]
N=arr[0]
mod=arr[1]
#ret=sum([int(y**y) for y in range(N+1)])
#ans=ret
for i in range(1,N+1):
ans = (ans + pow(i,i,mod))%mod
print (ans)
I tried another approach but in vain.
Here is code for that
from functools import reduce
test=int(input())
answer=0
for cases in range(test):
arr=[int(x) for x in input().split()]
N=arr[0]
mod=arr[1]
answer = reduce(lambda K,N: x+pow(N,N), range(1,N+1)) % M
print(answer)
Two suggestions:
Let 0^0 = 1 be what you use. This seems like the best guidance I have for how to handle that.
Compute k^k by multiplying and taking the modulus as you go.
Do an initial pass where all k (not exponents) are changed to k mod M before doing anything else.
While computing (k mod M)^k, if an intermediate result is one you've already visited, you can cut back on the number of iterations to continue by all but up to one additional cycle.
Example: let N = 5 and M = 3. We want to calculate 0^0 + 1^1 + 2^2 + 3^3 + 4^4 + 5^5 (mod 3).
First, we apply suggestion 3. Now we want to calculate 0^0 + 1^1 + 2^2 + 0^3 + 1^4 + 2^5 (mod 3).
Next, we begin evaluating and use suggestion 1 immediately to get 1 + 1 + 2^2 + 0^3 + 1^4 + 2^5 (mod 3). 2^2 is 4 = 1 (mod 3) of which we make a note (2^2 = 1 (mod 3)). Next, we find 0^1 = 0, 0^2 = 0 so we have a cycle of size 1 meaning no further multiplication is needed to tell 0^3 = 0 (mod 3). Note taken. Similar process for 1^4 (we tell on the second iteration that we have a cycle of size 1, so 1^4 is 1, which we note). Finally, we get 2^1 = 2 (mod 3), 2^2 = 1(mod 3), 2^3 = 2(mod 3), a cycle of length 2, so we can skip ahead an even number which exhausts 2^5 and without checking again we know that 2^5 = 2 (mod 3).
Our sum is now 1 + 1 + 1 + 0 + 1 + 2 (mod 3) = 2 + 1 + 0 + 1 + 2 (mod 3) = 0 + 0 + 1 + 2 (mod 3) = 0 + 1 + 2 (mod 3) = 1 + 2 (mod 3) = 0 (mod 3).
These rules will be helpful to you since your cases see N much larger than M. If this were reversed - if N were much smaller than M - you'd get no benefit from my method (and taking the modulus w.r.t. M would affect the outcome less).
Pseudocode:
Compute(N, M)
1. sum = 0
2. for i = 0 to N do
3. term = SelfPower(i, M)
4. sum = (sum + term) % M
5. return sum
SelfPower(k, M)
1. selfPower = 1
2. iterations = new HashTable
3. for i = 1 to k do
4. selfPower = (selfPower * (k % M)) % M
5. if iterations[selfPower] is defined
6. i = k - (k - i) % (i - iterations[selfPower])
7. clear out iterations
8. else iterations[selfPower] = i
9. return selfPower
Example execution:
resul = Compute(5, 3)
sum = 0
i = 0
term = SelfPower(0, 3)
selfPower = 1
iterations = []
// does not enter loop
return 1
sum = (0 + 1) % 3 = 1
i = 1
term = SelfPower(1, 3)
selfPower = 1
iterations = []
i = 1
selfPower = (1 * 1 % 3) % 3 = 1
iterations[1] is not defined
iterations[1] = 1
return 1
sum = (1 + 1) % 3 = 2
i = 2
term = SelfPower(2, 3)
selfPower = 1
iterations = []
i = 1
selfPower = (1 * 2 % 3) % 3 = 2
iterations[2] is not defined
iterations[2] = 1
i = 2
selfPower = (2 * 2 % 3) % 3 = 1
iterations[1] is not defined
iterations[1] = 2
return 1
sum = (2 + 1) % 3 = 0
i = 3
term = SelfPower(3, 3)
selfPower = 1
iterations = []
i = 1
selfPower = (1 * 3 % 0) % 3 = 0
iterations[0] is not defined
iterations[0] = 1
i = 2
selfPower = (0 * 3 % 0) % 3 = 0
iterations[0] is defined as 1
i = 3 - (3 - 2) % (2 - 1) = 3
iterations is blank
return 0
sum = (0 + 0) % 3 = 0
i = 4
term = SelfPower(4, 3)
selfPower = 1
iterations = []
i = 1
selfPower = (1 * 4 % 3) % 3 = 1
iterations[1] is not defined
iterations[1] = 1
i = 2
selfPower = (1 * 4 % 3) % 3 = 1
iterations[1] is defined as 1
i = 4 - (4 - 2) % (2 - 1) = 4
iterations is blank
return 1
sum = (0 + 1) % 3 = 1
i = 5
term = SelfPower(5, 3)
selfPower = 1
iterations = []
i = 1
selfPower = (1 * 5 % 3) % 3 = 2
iterations[2] is not defined
iterations[2] = 1
i = 2
selfPower = (2 * 5 % 3) % 3 = 1
iterations[1] is not defined
iterations[1] = 2
i = 3
selfPower = (1 * 5 % 3) % 3 = 2
iterations[2] is defined as 1
i = 5 - (5 - 3) % (3 - 1) = 5
iterations is blank
return 2
sum = (1 + 2) % 3 = 0
return 0
why not just use simple recursion to find the recursive sum of the powers
def find_powersum(s):
if s == 1 or s== 0:
return 1
else:
return s*s + find_powersum(s-1)
def find_mod (s, m):
print(find_powersum(s) % m)
find_mod(4, 4)
2

efficient X within limit algorithm

I determine limits as limit(0)=0; limit(y)=2*1.08^(y-1), y∈{1,2,3,...,50} or if you prefeer iterative functions:
limit(0)=0
limit(1)=2
limit(y)=limit(y-1)*1.08, x∈{2,3,4,...,50}
Exmples:
limit(1) = 2*1.08^0 = 2
limit(2) = 2*1.08^1 = 2.16
limit(3) = 2*1.08^2 = 2.3328
...
for a given x∈[0,infinity) I want an efficient formula to calculate y so that limit(y)>x and limit(y-1)≤x or 50 if there is none.
Any ideas?
or is pre-calculating the 50 limits and using a couple of ifs the best solution?
I am using erlang as language, but I think it will not make much of a difference.
limit(y) = 2 * 1.08^(y-1)
limit(y) > x >= limit(y - 1)
Now if I haven't made a mistake,
2 * 1.08^(y - 1) > x >= 2 * 1.08^(y - 2)
1.08^(y - 1) > x / 2 >= 1.08^(y - 2)
y - 1 > log[1.08](x / 2) >= y - 2
y + 1 > 2 + ln(x / 2) / ln(1.08) >= y
y <= 2 + ln(x / 2) / ln(1.08) < y + 1
Which gives you
y = floor(2 + ln(x / 2) / ln(1.08))

Formula needed: Sort array to array-"snaked"

After the you guys helped me out so gracefully last time, here is another tricky array sorter for you.
I have the following array:
a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
I use it for some visual stuff and render it like this:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Now I want to sort the array to have a "snake" later:
// rearrange the array according to this schema
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
// the original array should look like this
a = [1,2,3,4,12,13,14,5,11,16,15,6,10,9,8,7]
Now I'm looking for a smart formula / smart loop to do that
ticker = 0;
rows = 4; // can be n
cols = 4; // can be n
originalArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
newArray = [];
while(ticker &#60 originalArray.length)
{
//do the magic here
ticker++;
}
Thanks again for the help.
I was bored, so I made a python version for you with 9 lines of code inside the loop.
ticker = 0
rows = 4
cols = 4
originalArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
newArray = [None] * (rows * cols)
row = 0
col = 0
dir_x = 1
dir_y = 0
taken = {}
while (ticker < len(originalArray)):
newArray[row * cols + col] = originalArray[ticker]
taken[row * cols + col] = True
if col + dir_x >= cols or row + dir_y >= rows or col + dir_x < 0:
dir_x, dir_y = -dir_y, dir_x
elif ((row + dir_y) * cols + col + dir_x) in taken:
dir_x, dir_y = -dir_y, dir_x
row += dir_y
col += dir_x
ticker += 1
print newArray
You can index into the snake coil directly if you recall that
1 + 2 + 3 + ... + n = n*(n+1)/2
m^2 + m - k = 0 => m - (-1+sqrt(1+4*k))/2
and look at the pattern of the coils. (I'll leave it as a hint for the time being--you could also use that n^2 = (n-1)^2 + (2*n+1) with reverse-indexing, or a variety of other things to solve the problem.)
When translating to code, it's not really any shorter than Tuomas' solution if all you want to do is fill the matrix, however.

Resources