Can anybody help me generate two different random numbers in two ranges? I've tried:
var a = Random.nextInt(S)
var b = Random.nextInt(K)
if (a == S || b == K){
a = S-1
b = K-1
}
(word,a,b)
But this generates some numbers that are not in the specified ranges.
From the docs on Random:
def nextInt(n: Int): Int
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
By the method contract, nextInt will always return a value from 0 to n - 1, so your condition a == S || b == K will always be false.
Related
Could someone explain to me the logic behind this hashMap algorithm? I'm getting confused about how the algorithm receives the total sum. I'm starting to learn about algorithms, so it's a little confusing for me. I made comments in my code to pinpoint each line code, but I'm not sure I'm grasping logic correctly. I'm just looking for an easier way to understand how the algorithm works to avoid confusing myself.
//**calculate Two Number Sum
func twoNumberSum(_ array: [Int], _ targetSum: Int) -> [Int] {
//1) initilize our Array to hold Integer Value: Boolean value to store value into hashTable
var numbersHashMap = [Int:Bool]()
//2) create placeHolder called number that iterates through our Array.
for number in array {
//3) variable = y - x
let match = targetSum - number
//4) ??
if let exists = numbersHashMap[match], exists {
//5) match = y / number = x
return [match, number] //
} else {
//6) Store number in HashTable and repeats
numbersHashMap[number] = true
}
}
return []
}
twoNumberSum([3,5,-4, 8, 11, 1, -1, -6], 10)
// x = Number
// y = Unknown *Solve for Y*
Sure, I can walk you through it. So we have a list of numbers, are we are trying to find two numbers that add together to make the specified target. To do this, for each number x, we check if (target - x) is in the list. If it is not, then we add x to the list. If it is, then we return x and (target - x).
Step 4 in your code is the part where we check if (target - x) is in the list. To see why this makes sense, let's walk through an example.
Say we have [2, 3, -1] and our target is 1. In this case, we first consider x = 2 and check our hashmap for (target - x) = (1 - 2) = -1. Since -1 is not in the hashmap, we add 2 to the hashmap. We then consider x = 3 and check for (1 - 3) = -2. Again, -2 is not in the hashmap, so we add it. Now we check x - -1. In this case, when we check (target - x) = (1 - (-1)) = 2, 2 is in the hashmap. Intuitively, we have already "seen" 2, and know that 2 and -1 can be added to get our value.
This is what provides the speed optimization over checking every two numbers in the list.
Can anybody please help me how this code works,
I am not getting it by myself, some help would be greatly appreciated.
Prime number in scala using recusion:
def isPrime(n: Int): Boolean = {
def isPrimeUntil(t: Int): Boolean =
if (t<=1) true
else n%t != 0 && isPrimeUntil(t-1)
isPrimeUntil(n/2)
}
The number n is prime if and only if there's no number t such that t != 1, t!= n, n % t = 0.
So, if you find some number from 2 to n-1 such that n % t = 0, n is composite, otherwise it is prime.
One more thing, you may see that there's no need to search for divisors among the numbers greater than n/2.
So, all the algorithm does is checks n % d for each t from n/2 to 2. As soon as it is found, the algorithms stops ans says it's composite (returns False). Otherwise it gets to t = 1 and assures the number is prime (returns True).
Just to mention, it's enough to consider the numbers from ceil(sqrt(n)) to 2, which results in better time complexity (O(sqrt(n)) vs O(n)).
isPrime(7) --> isPrimeUntil(3) --> (3 <= 1)? no
(7%3 != 0)? yes
isPrimeUntil(2) --> (2 <= 1)? no
(7%2 != 0)? yes
isPrimeUntil(1) --> (1 <= 1)? yes
isPrime(7) is true. No divisor was found between 1 and 7/2.
isPrime(9) --> isPrimeUntil(4) --> (4 <= 1)? no
(9%4 != 0)? yes
isPrimeUntil(3) --> (3 <= 1)? no
(9%3 != 0)? no
isPrime(9) is false. Found that 9 is divisible by 3.
If you have a local Scala REPL, you should paste this function in there and play around with it. If not, there's always Scastie. I made a Scastie snippet, in which I changed the formatting to my liking, added comments and a demo range.
There are examples of Scala that make it look almost like Malbolge. This one is not that bad.
Let's follow it through with a composite number like 102. Calling isPrime(102) causes isPrimeUntil(51) to be invoked (as 51 is half 102). Since 51 is greater than 1, the nested function calculated 102 % 51, which is 0, so, by "short-circuit evaluation" of logical AND, the nested function should return false.
Now let's try it with 103. Calling isPrime(103) causes isPrimeUntil(51) to be invoked (as 51 is half 103 and the remainder of 1 is simply discarded). Since 51 is greater than 1, the nested function calculated 103 % 51, which is 1, so the nested function calls itself as primeUntil(50). Since 50 is greater than 1, the... so on and so forth until calling itself as primeUntil(1). Since t == 1, primeUntil returns true and the recursion stops.
This gives the wrong answer for negative composite numbers. Plus, as others have mentioned, it is inefficient to start the recursion at n/2. This would be an improvement:
def isPrime(n: Int): Boolean = {
def isPrimeUntil(t: Int): Boolean = {
if (t <= 1) true else n % t != 0 && isPrimeUntil(t - 1)
}
isPrimeUntil(Math.floor(Math.sqrt(Math.abs(n))).toInt)
}
Hmm... it's still giving the wrong answer for −1, 0, 1. But hopefully now you understand this function.
CodeWars challenges again. Today I have a problem with this one:
"Your task is to split the chocolate bar of given dimension n x m into small squares. Each square is of size 1x1 and unbreakable. Implement a function that will return a minimum number of breaks needed.
For example, if you are given a chocolate bar of size 2 x 1 you can split it to single squares in just one break, but for size 3 x 1 you must do two breaks.
If input data is invalid you should return 0 (as in no breaks are needed if we do not have any chocolate to split). Input will always be a non-negative integer."
For some reason, the output is constantly 0 no matter what sides of the chocolate bar I provide.
What I've already tried:
object breakChocolate {
var result = 0
def breakChocolate(n: Int, m: Int) = {
var t = n*m
var i =0
def breaking(y:Int): Unit ={
if (t ==0 || t ==1)
result = i
else {
breaking(t%2)
i +=1
}
}
result
}
}
Here are the tests:
Test Results:
TestCases
breakChocolate(5, 5) should return 24
Test Failed
0 was not equal to 24
Stack Trace
Completed in 38ms
breakChocolate(7, 4) should return 27
Test Failed
0 was not equal to 27
Stack Trace
Completed in 1ms
Completed in 76ms
To solve this problem you don't need recursion at all. Consider the special case of chocolate plate: (1 x n). To divide this plate completely you need (n-1) breaks. Now you have plate m x n. To divide it into m pieces of form (1 x n) you need (m-1) breaks. So the total number of breaks is
(m-1) + m*(n-1) ~
m - 1 + m*n - m ~
m*n - 1
If I'm reading the Scala correctly, you've got the basic algorithm wrong.
This is actually a very simply problem, something similar to the old puzzle: if you have 55 teams playing in a single-elimination tournament, obviously some of them have to get byes in the first round, so there won't be a perfect even bracket. So how many total games will be played?
The answer: 54. Regardless of how the bracket is made, it's a single-elimination tourney. Every game reduces the number of remaining teams by one. So to get 55 participants down to one winner, 54 games will have to be played.
There is a similar argument to be made for your chocolate bar. At some point, you have p pieces of chocolate in front of you. Whichever one you select to break, you have taken 1 from the pile and put back 2, which means that the pile now has p + 1 pieces. So for every split you add one piece to the pile. This should lead directly to an answer...
...which may actually be wrong because of the need to return 0 in some cases, but it should be easy to special-case that.
You get 0 because you are not running breaking.
If you want to use recursion, one option could be to use a tail recursive function.
First decrement a checking it is greater than 1 to get the number of "horizontal" breaks to get the slices. Add 1 to the accumulator while looping.
Then decrement b checking it is greater than 1 to get the number of "vertical" breaks. This time add the starting "horizonal" value because that is the number of times you actually have to break the slices.
object breakChocolate {
def breakChocolate(n: Int, m: Int): Int = {
def breaking(a: Int, b: Int, acc: Int = 0): Int = {
if (a > 1) breaking(a - 1, b, acc + 1)
else if (b > 1) breaking(a, b - 1, acc + n)
else acc
}
breaking(n, m)
}
}
Scala demo
You can use this code instead:
function breakChocolate(n,m) {
if(n > 0 && m > 0) {
return n * m - 1;
} else {
return 0;
}
}
I am trying to do an assignment in JES a student jython program. I need to convert our student number taken as a string input variable to pass through our function i.e.
def assignment(stringID) and convert it into integers. The exact instructions are:
Step 1
Define an array called id which will store your 7 digit number as integers (the numbers you set in the array does not matter, it will be over written with your student number in the next step).
Step 2 Your student number has been passed in to your function as a String. You must separate the digits and assign them to your array id. This can do this manually line by line or using a loop. You will need to type cast each character from stringID to an integer before storing it in id.
I have tried so many different ways using the int and float functions but I am really stuck.
Thanks in advance!
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
I had to do some jython scripting for a websphere server. It must be a really old version of python it didn't have the ** operator or the len() function. I had to use an exception to find the end of a string.
Anyways I hope this saves someone else some time
def pow(x, y):
total = 1;
if (y > 0):
rng = y
else:
rng = -1 * y
print ("range", rng)
for itt in range (rng):
total *= x
if (y < 0):
total = 1.0 / float(total)
return total
#This will return an int if the percision restricts it from parsing decimal places
def parseNum(string, percision):
decIndex = string.index(".")
total = 0
print("decIndex: ", decIndex)
index = 0
string = string[0:decIndex] + string[decIndex + 1:]
try:
while string[index]:
if (ord(string[index]) >= ord("0") and ord(string[index]) <= ord("9")):
times = pow(10, decIndex - index - 1)
val = ord(string[index]) - ord("0")
print(times, " X ", val)
if (times < percision):
break
total += times * val
index += 1
except:
print "broke out"
return total
Warning! - make sure the string is a number. The function will not fail but you will get strange and almost assuredly, useless output.
I implemented a Fibonacci function in Scala and it works fine however when I enter 50 it takes a long time to compute it because it has to calculate the 2 previous integers each time. I found a function that keeps the 2 previous numbers. However, can somebody tell me how to write this function to make it accept 2 integers instead of 3 and return the last 2 numbers to compute the Fibonacci at a particular index x. Thanks!
def fastFib(x: Long ): Long = {
def fast(x:Long , a:Long, b:Long):Long =
if (x<=0) a+b
else fast(x-1,b,a+b)
if (x<2) 1
else fast(x-2,0,1)
}
You can cache the intermediate results, then you never recompute the same result twice
Here is the code
//this supposed to contains all the value when initialized
//initialized with 0 for all value
val cache = Array [Int] (101);//0 to 100
cache(1)==1;//initial value
cache(2)=1;//initial value
def fibonacciCache(n:Int) : Int = {
if (n>100)
{
println("error");
return -1;
}
if (cache(n)!=0)//means value has been calculated
return cache(n);
else
{
cache(n)=fibonacciCache(n-1)+fibonacciCache(n-2);
return cache(n);
}
}
Hope that helps