What is the worst time complexity of the following code ?
The array stores non-repeated integer numbers. In every row, the numbers are stored from smallest to largest. Also, the numbers in row(i+1) are greater than the largest number in row i.
let M = [[1,5,9,11],
[13,17,19,22],
[27,31,33,35],
[37,39,41,43],
[45,47,49,100]]
function Search_Matrix(M,low,high,x){
let C = 4
if(low<=high){
mid = parseInt(low+(high-low)/2)
console.log("mid="+mid)
//console.log("M[mid][0]="+M[mid][0])
if((M[mid][0]<=x) && (M[mid][C-1]>=x)) {
return mid
}else{
if(M[mid][0]>x){
return Search_Matrix(M,low,mid-1,x)
}
if(M[mid][C-1]<x){
return Search_Matrix(M,mid+1,high,x)
}
}
}else{
return -1
}
}
console.log(Search_Matrix(M,0,4,20))
To me, it looks like 'Binary Search' and worst-case complicity should be Theta(logN)
Related
On the Android Studio emulator The user is required to enter a maximum of 10 numbers. When I put in the number 1 the output shows 0 instead of 1 (this is for the min number; the max works perfectly fine) Can anyone please assist me in this problem. I tried using minOf() and max() nothing worked Below is a snippet of my source code:
val arrX = Array(10) { 0 }
.
.
.
.
findMinAndMaxButton.setOnClickListener {
fun getMin(arrX: Array<Int>): Int {
var min = Int.MAX_VALUE
for (i in arrX) {
min = min.coerceAtMost(i)
}
return min
}
fun getMax(arrX: Array<Int>): Int {
var max = Int.MIN_VALUE
for (i in arrX) {
max = max.coerceAtLeast(i)
}
return max
}
output.text = "The Min is "+ getMin(arrX) + " and the Max is " + getMax(arrX)
}
}
}
Is there anything that can be done to get this work?
You're initialising arrX to a bunch of zeroes, and 0.coerceAtMost(someLargerNumber) will always stick at 0.
Without seeing how you set the user's numbers it's hard to say what you need to do - but since you said the user enters a maximum of 10 numbers, at a guess there are some gaps in your array, i.e. indices that are still set to 0. If so, they're going to be counted in your min calculation.
You should probably use null as your default value instead - that way you can just ignore those in your calculations:
val items = arrayOfNulls<Int?>(10)
// this results in null, because there are no values - handle that however you like
println(items.filterNotNull().minOrNull())
>> null
// set values on some of the indices
(3..5).forEach { items[it] = it }
// now this prints 3, because that's the smallest of the numbers that -do- exist
println(items.filterNotNull().minOrNull())
>> 3
can anyone pls tell me the time complexity of this func.
this is for generating all valid parenthesis , given the count of pairs
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
My code is working fine, but im not sure about time complexity of it.
pls help
class Solution {
public List generateParenthesis(int n) {
HashMap<String,Boolean> hm = new HashMap<>();
return generate(hm,n);
}
public static List<String> generate(HashMap<String,Boolean> hm, int n ){
if(n == 1){
hm.put("()",true);
List<String>temp = new ArrayList<>();
temp.add("()");
return temp;
}
List<String>temp = generate(hm,n-1);
List<String>ans = new ArrayList<>();
for(String pat : temp){
for(int i = 0; i < pat.length(); i++){
String newPat = pat.substring(0,i)+"()"+pat.substring(i);
if(!hm.containsKey(newPat)){
hm.put(newPat,true);
ans.add(newPat);
}
}
}
return ans;
}
}
You have two for loops, which each run over m and n elements, it can be written as O(m*n), and be contracted to O(n^2) because m can be equal to n.
Your function is recursively calling itself, making time complexity analysis a bit harder.
Think about it this way: You generate all valid parenthesis of length n. It turns out that the number of all valid parenthesis of length n (taking your definition of n) is equal to the nth catalan number. Each string has length 2*n, So the time complexity is not a polynomial, but O(n*C(n)) where C(n) is the nth catalan number.
Edit: It seems like this question is already answered here.
function test(num){
var root1 = Math.sqrt(num);
var ind=2;
while(ind<=root1){
if (ind%num==0 && IsPrime(ind)==true) {
num=ind;
}
ind++;
}
return num;
}
Hi, in this code the function must return the largest prime factor of a given number, but the function returns the same number
For example: test(123) returns 123
You have two problems:
You want to check if num can be divided by ind, not the other way round. The test for that would be: num % ind == 0.
You should not re-use the num variable for the result. That way you overwrite the original number and the result will be wrong. Declare a new variable, for instance, result.
I've just started learning programming and I'm having a problem understanding a piece of code from a tutorial. Could anyone explain what the Kotlin code below does?
Thank you
fun f(i:Int, list:MutableList<Int>) : Boolean {
for (number in list) {
if (i % number == 0) {
return false
}
}
return true
}
fun main(args:Array<String>) {
val result = mutableListOf<Int>()
for (number in 2..100) {
if (f(number, result)) {
result.append(number)
}
print(result.joinToString())
}
The main method creates a new list of integers. In a loop from 2 to 200 it calls the function f with current number of the loop (number) and the list created.
The function checks if the number handed over can be divided by any number in the list. In case it can be divided, false is returned, else true.
If the number couldn't be divided then the number is stored inside the list.
So it is a simple algorithm to find prime numbers. The list stores all so far found prime numbers. And the function checks if the number can be divided by any of the prime numbers.
f(...) checks whether i divides with any number in the list - if so, returns false.
main(..) loops through all numbers from 2..100 and adds numbers that don't divide with any number previously added to the list.
Basically, it will print all prime numbers between 2..100
I need to write a method that returns me the smallest distance (which is a whole number value) within an Array List called "babyTurtles". There are 5 turtles within this array list and they all move a random distance each time the program is ran.
I've been trying to figure out how to do it for an hour and all I've accomplished is making myself frustrated and coming here.
p.s.
In my class we wrote this code to find the average distance moved by the baby turtles:
public double getAverageDistanceMovedByChildren() {
if (this.babyTurtles.size() == 0) {
return 0;
}
double sum = 0;
for (Turtle currentTurtle : this.babyTurtles) {
sum = sum + currentTurtle.getDistanceMoved();
}
double average = sum / this.babyTurtles.size();
return average;
}
That's all I've got to work on, but I just can't seem to find out how to do it.
I'd really appreciate it if you could assist me.
This will give you the index in the array list of the smallest number:
int lowestIndex = distanceList.indexOf(Collections.min(distanceList));
You can then get the value using this:
int lowestDistance = distanceList.get(lowestIndex);