I'm trying to find the least common multiple of an array of integers, e.g. if there are 2 numbers given (7, 3) then my task is to find the LCM of the numbers 3 through 7 (3,4,5,6,7 in that case).
My solution would be to add the maximum number to a new variable (var common) until the remainders of all of the numbers in the array (common % numBetween[i]) equal 0. There are more efficient ways of doing this, for example applying the Euclidean Algorithm, but I wanted to solve this my way.
The code:
function smallestCommons(arr) {
var numBetween = [];
var max = Math.max.apply(Math, arr);
var min = Math.min.apply(Math, arr);
while (max - min !== -1) {
numBetween.push(min);
min += 1;
} //this loop creates the array of integers, 1 through 13 in this case
var common = max;
var modulus = [1]; //I start with 1, so that the first loop could begin
var modSum = modulus.reduce(function (a, b) {
return a + b;
}, 0);
while (modSum !== 0) {
modulus = [];
for (var i = 0; i < numBetween.length; i++) {
modulus.push(common % numBetween[i]);
}
if (modSum !== 0) {
common += max;
break; //without this, the loop is infinite
}
}
return common;
}
smallestCommons([1,13]);
Now, the loop is either infinite (without break in the if statement) so I guess the modSum never equals 0, because the modulus variable always contains integers other than 0. I wanted to solve this by "resetting" the modulus to an empty array right after the loop starts, with
modulus = [];
and if I include the break, the loop stops after 1 iteration (common = 26). I can't quite grasp why my code isn't working. All comments are appreciated.
Thanks in advance!
I may be false, but do you actually never change modSum within the while-loop? If so, this is your problem. You wanted to do this by using the function .reduce(), but this does not bind the given function, so you have to call the function each time again in the loop.
Related
I'm kind of stuck, I don't know how to make the second loop to start 1 position above the first loop in Kotlin.
I have an array (named myArray) with 10 elements, I need to Write a Kotlin program that prints the number that has the most consecutive repeated number in the array and also prints the number of times it appears in the sequence.
The program must parse the array from left to right so that if two numbers meet the condition, the one that appears first from left to right will be printed.
Longest: 3
Number: 8
fun main() {
val myArray: IntArray = intArrayOf(1,2,2,4,5,6,7,8,8,8)
for((index , value) in myArray.withIndex()){
var inx = index + 1
var count = 0
var longest = 0
var number = 0
for((inx,element) in myArray.withIndex()) {
if(value == element ){
count+=
}
}
if(longest < count){
longest = count
number = value
}
}
}
I'm against just dropping answers, but it is quite late for me, so I'll leave this answer here and edit it tomorrow with more info on how each part works. I hope that maybe in the meanwhile it will help you to gain some idea to where you might be going wrong.
val results = mutableMapOf<Int, Int>()
(0..myArray.size - 2).forEach { index ->
val current = myArray[index]
if (current == myArray[index + 1]) {
results[current] = (results[current] ?: 1) + 1
}
}
val (max, occurrences) = results.maxByOrNull { it.value } ?: run { println("No multiple occurrences"); return }
println("Most common consecutive number $max, with $occurrences occurrences")
Alternatively if the intArray would be a list, or if we allowed to change it to a list myArray.toList(), you could replace the whole forEach loop with a zipWithNext. But I'm pretty sure that this is a HW question, so I doubt this is the expected way of solving it.
myList.zipWithNext { a, b ->
if (a == b) results[a] = (results[a] ?: 1) + 1
}
The task was to find the recurrence relation for this function and then find the complexity class for it as well. Provided is my work and the function. My question is, I feel like I'm missing some step in the recurrence relation and complexity class. Is this correct? The following code is in JavaScript.
function divideAndConquerSum(x){
if(x.length<1){
return 0;
}
if(x.length == 1){
return x[0];
}
var third = Math.floor((x.length-1)/3);
var next = (third *2)+1;
var y = x.slice(0, third+1);
var z = x.slice(third+1, next+1);
var a = x.slice(next+1, x.length);
return divideAndConquerSum(y)+divideAndConquerSum(z)+divideAndConquerSum(a);
}
///
work:
Checks if the array has length of zero...this is a constant time so : +1
Checks if the array has a length of 1, if so then return. Also constant time: +1
Splits the array into 3 The functionis is also constant no matter the size of n: +1
Function then adds its self three times but each time is a recursive call of 1/3 the size of n: 3T(1/3)
1+1+1+ 3T(1/3)
3T(1/3)
calls itself so we can define the relation as
3T(1/3)
9T(1/9)
27T(1/27)
this pattern can shown as
3log3n
so we have
1+1+1+ 3log3n
which is a complexity class of
O(log n)
is this right?
Try to understand running time of below algorithm for problem; Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results
This is a simple BFS solution that generates all possible strings by removing "(" or ")".
public List<String> removeInvalidParentheses(String s) {
List<String> ret = new LinkedList<>();
Set<String> visited = new HashSet<>();
Queue<String> queue = new LinkedList<>();
queue.add(s);
while (!queue.isEmpty()) {
String current = queue.poll();
if (isValidParentheses(current)) {
ret.add(current);
}
if (ret.size() > 0) continue;
for (int i = 0; i < current.length(); i++) {
if (current.charAt(i) == '(' || current.charAt(i) == ')') {
String next = current.substring(0, i) + current.substring(i + 1);
if (!visited.contains(next)) {
visited.add(next);
queue.offer(next);
}
}
}
}
return ret;
}
public boolean isValidParentheses(String current) {
int open = 0;
int close = 0;
for (char c : current.toCharArray()) {
if (c == '(') open++;
else if (c == ')') close++;
if (close > open) return false;
}
return open == close;
}
It starts with generate n possible strings and next level it generate all strings with size n-1 length, and n-2 length, etc .. for )()( example
)()( len n
()( ))( ()( )() n-1
() (( () n-2
each level it checks all possible strings with n-level length.
given this - I was having hard to time figure out how to finalize the running time of this algorithm. How do I generalize this algorithm and analyze the complexity?
For the worst case, lets try with input as ((((. As per the logic above, it will push (((( in the queue, checking that this is invalid. So it would generate 4 more possible substrings of length 3 pushing them inside the queue. Again, on processing that queue elements, it would again generate more strings of length 2 for each substring of length 3, then for two and then end. We are assuming that T(1) = 1.
If you try to make a recurrence relation for the above logic, it would be
T(n) = nT(n-1) + 1, which can be written as
= `n((n-1)T(n-2) + 1) + 1` and so on.
On solving it completely, we would get T(n) = n! + n(n-1)/2 + 1 which would be O(n!).
Hence, I think the time complexity would be of order O(n!)
For more details on how to solve the recurrence relation T(n) = nT(n-1) + 1, please refer:
this post on its solution
So i've tried interpreting this pseudocode a friend made and i wasn't exactly sure that my method returns the right result. Anyone who's able to help me out?
I've done some test cases where e.g. an array of [2,0,7] or [0,1,4] or [0, 8, 0] would return true, but not cases like: [1,7,7] or [2,6,0].
Array(list, d)
for j = 0 to d−1 do
for i = 0 to d−1 do
for k = 0 to d−1 do
if list[j] + list[ i] + list[k] = 0 then
return true
end if
end for
end for
end for
return false
And i've made this in java:
public class One{
public static boolean method1(ArrayList<String> A, int a){
for(int i = 0; i < a-1; i++){
for(int j = 0; j < a-1; j++){
for(int k = 0; k < a-1; k++){
if(Integer.parseInt(A.get(i)+A.get(j)+A.get(k)) == 0){
return true;
}
}
}
}
return false;
}
}
Thanks in advance
For a fix to your concrete problem, see my comment. A nicer way to write that code would be to actually use a list of Integer instead of String, because you will then want to convert the strings back to integers. So, your method looks better like this:
public static boolean method(List<Integer> A) {
for (Integer i : A)
for (Integer j : A)
for (Integer k : A)
if (i + j + k == 0)
return true;
return false;
}
See that you don't even need the size as parameter, since any List in Java embeds its own size.
Somehow offtopic
You're probably trying to solve the following problem: "Find if a list of integers contains 3 different ones that sum up to 0". The solution to this problem doesn't have to be O(n^3), like yours, it can be solved in O(n^2). See this post.
Ok, so here is what I believe the pseudo code is trying to do. It returns true if there is a zero in your list or if there are three numbers that add up to zero in your list. So it should return true for following test cases. (0,1,2,3,4,5), (1,2,3,4,-3). It will return false for (1,2,3,4,5). I just used d=5 as a random example. Your code is good for the most part - you just need to add the ith, jth and kth elements in the list to check if their sum equals zero for the true condition.
I brute-forced summing of all primes under 2000000. After that, just for fun I tried to parallel my for, but I was a little bit surprised when I saw that Parallel.For gives me an incorrect sum!
Here's my code : (C#)
static class Problem
{
public static long Solution()
{
long sum = 0;
//Correct result is 142913828922
//Parallel.For(2, 2000000, i =>
// {
// if (IsPrime(i)) sum += i;
// });
for (int i = 2; i < 2000000; i++)
{
if (IsPrime(i)) sum += i;
}
return sum;
}
private static bool IsPrime(int value)
{
for (int i = 2; i <= (int)Math.Sqrt(value); i++)
{
if (value % i == 0) return false;
}
return true;
}
}
I know that brute-force is pretty bad solution here but that is not a question about that. I think I've made some very stupid mistake, but I just can't locate it. So, for is calculating correctly, but Parallel.For is not.
You are accessing the variable sum from multiple threads without locking it, so it is possible that the read / write operations become overlapped.
Adding a lock will correct the result (but you will be effectively serializing the computation, losing the benefit you were aiming for).
You should instead calculate a subtotal on each thread and add the sub-totals at the end. See the article How to: Write a Parallel.For Loop That Has Thread-Local Variables on MSDN for more details.
long total = 0;
// Use type parameter to make subtotal a long, not an int
Parallel.For<long>(0, nums.Length, () => 0, (j, loop, subtotal) =>
{
subtotal += nums[j];
return subtotal;
},
(x) => Interlocked.Add(ref total, x)
);
Many thanks to all of you for your quick answers
i changed
sum += i;
to
Interlocked.Add(ref sum,i);
and now it works great.