Good day, For example: If I have an nsarray [3, 1, -5, 3, 3, -5, 0, 1, 1, 3]
How do I calculate Missing numbers in my Array:
-4
-3
-2
-1
2
But - No sorting is allowed and must run in linear time O(N)
Well the brute force way would be something like this
a. find the max and min values in the array -5, 3
b. loop multiple times the array form -5 to 3 looking for the specific number (-5, -4, -3, -2, -1, 0 .... 3)
b1. if the number if found break that loop and continue with the next
b2 . if the loop ends without breaking take note of that number
It's inefficient compared to just sorting it, but it runs in a linear way
The idea is to make another array of bools and to check true if that number exist. After you do that, just go through array of bools and if number is false then its missing.
plz use this code
NSArray *a = #[#3, #1, #-5, #3, #3, #-5, #0, #1, #1, #3];
NSNumber *max=[a valueForKeyPath:#"#max.self"];
NSNumber *min=[a valueForKeyPath:#"#min.self"];
int big = [max intValue];
int small = [min intValue];
while (small<=big) {
if ([a containsObject:[NSNumber numberWithInt:small]]) {
}
else
{
NSLog(#"missing number is %d",small);
}
small++;
}
result
If the numbers in the array are consecutive integers, then 'Sort' the array and find the difference between the two consecutive numbers. If it is 1, then the number is not missed. Else, the number has missed.
Related
I need an array where I can store 3 values, and calculate the average of it.
After 3s the array is full, I would like to refresh every value starting from begin [0] of the array. So every 3s the the array is updated and I have the most recent average. For the moment when I add an object the array keeps growing.
This is the code I have at the moment:
//Inside function which loops every second so I can access myValue
self.myArray = [[NSMutableArray alloc] initWithCapacity:3];
[self.myArray addObject:[NSNumber numberWithDouble:myValue]];
for(int i = 0; i < self.myArray.count; i++) {
NSLog(#"Array %d: %#", i, self.myArray[i]);
}
Output
Array 0: 2
Array 1: 4
Array 2: 5
Array 3: 6
Array 4: 1
Just check if the size of your array is larger than 3. If so, remove the oldest element.
Here is a possible implementation:
Alloc and init the array:
self.myArray = [[NSMutableArray alloc] init];
Insert a new object and delete the oldest one:
[self.myArray insertObject:object atIndex:0];
if ( self.myArray.count > 3 )
{
[self.myArray removeLastObject];
}
It looks like you're trying to calculate a running average that gets updated every second. Here's a simple alternative approach that may work for you.
Initialize the average:
runningAverage = myValue;
Inside the loop:
const int WEIGHT = 3;
runningAverage = (runningAverage * (WEIGHT - 1) + myValue) / WEIGHT;
Here's what the output would look like:
Input: 1, 2, 3, 4, 101, 6, 7, 8
(Using an array)
Output: -, -, 2, 3, 36, 37, 38, 7
(Using running average)
Output: 1, 1.33, 1.88, 2.59, 35.4, 25.6, 19.4, 15.6
Other than hardcoding or using the Math module, Is there any way I can find divisors of 60 in Ruby on Rails. Any helper methods/regular expression that I can make use of? Thanks for your help.
One of the easiest ways to achieve this would be to create a list of numbers between 1 and 60, and then only select the ones that divide 60 with no remainder.
To expand on SteveTurczyn's answer, we can do:
(1..60).select { |n| 60 % n == 0 }
The (1..60) part creates an enumerator (which in this case we can think of as an array of the numbers between 1 and 60).
Then you want to take this array, and select only the elements are divisors of 60.
We can use the modulus operator %, which gives us the remainder left over when we divide a number by another (e.g., 5 % 2 returns 1). Of course, if there is no remainder, then we know that the number divided cleanly, and is therefore a divisor of that number (i.e., if a % b == 0, then b is a divisor of a).
So what we want to do, is use the above as a criteria for selecting elements out of the array of numbers between 1 and 60, which we are able to do with the Array#select method.
If we have something, like an array (technically, I think, an Enumerable), we can use #select and a block to pull out only the elements that satisfy whatever criteria we specify in the block.
The { |n| 60 % n == 0 } is the block we are passing to #select, which will return true whenever 60 % n is 0 (each n is an element from the array of numbers 1 through 60). Array#select only returns the elements in the array for which the block evaluates to true- which is how SteveTurczyn's solution works.
This will give you the array of divisors
(1..60).select { |n| 60 % n == 0}
=> [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60]
For small numbers it's okay to use the brute force search, but for large numbers this approach doesn't suite. You can speed up your method significantly by selecting divisors as pairs.
Some examples with benchmarks:
require 'benchmark'
n = 10_000_000
def brute_force(n)
(1..n).select { |i| n % i == 0 }
end
def faster_way(n)
(1..Math.sqrt(n)).each_with_object([]) { |i, arr| (n % i).zero? && arr << i && n/i != i && arr << n/i }
end
Benchmark.bm do |x|
x.report { brute_force(n) }
x.report { faster_way(n) }
end
# Benchmark output
user system total real
0.799491 0.001417 0.800908 ( 0.802341)
0.000580 0.000002 0.000582 ( 0.000581)
As you can see the second approach is 1376 times faster for n = 10_000_000.
i want to generate a series of number through looping.
my series will contain numbers like 0,3,5,8,10,13,15,18 and so on.
i try to take reminder and try to add 2 and 3 but it wont work out.
can any one please help me in generating this series.
You can just use an increment which toggles between 3 and 2, e.g.
for (i = 0, inc = 3; i < 1000; i += inc, inc = 5 - inc)
{
printf("%d\n", i);
}
It looks like the the sequence starts at zero, and uses increments of 3 and 2. There are several ways of implementing this, but perhaps the simplest one would be iterating in increments of 5 (i.e. 3+2) and printing two numbers - position and position plus three.
Here is some pseudocode:
i = 0
REPEAT N times :
PRINT i
PRINT i + 3
i += 5
The iteration i=0 will print 0 and 3
The iteration i=5 will print 5 and 8
The iteration i=10 will print 10 and 13
The iteration i=15 will print 15 and 18
... and so on
I was pulled in with the tag generate-series, which is a powerful PostgreSQL function. This may have been tagged by mistake (?) but it just so happens that there would be an elegant solution:
SELECT ceil(generate_series(0, 1000, 25) / 10.0)::int;
generate_series() returns 0, 25, 50, 75 , ... (can only produces integer numbers)
division by 10.0 produces numeric data: 0, 2.5, 5, 7.5, ...
ceil() rounds up to your desired result.
The final cast to integer (::int) is optional.
SQL Fiddle.
I have created an application in which the user continually rotates the phone about the z-axis (yaw) with the screen of the phone facing upwards. I would like to generate the angle between the two extremes each time the rotation changes direction.
Imagine an array of the following values: [-5,-3,-2, 0, 1, 2, 6, 5, 3, 2,-1,-3,-4,-7,-4,-3,...]. What I would like to do is find the relative maximums and minimums of the array in order to find the differences from one relative minimum to the next relative maximum. In the given array, -5 would be the first relative minimum and then 6 would be the next relative maximum. The difference here would be 11 units. From that relative maximum of 6, the next relative minimum is -7. The difference here would be 13 units. The process would continue on until the end of the array. I would like these difference values to be entered into an array of their own, i.e. [11,13,...]. Would greatly appreciate any assistance!
The way I see this your first value in the array is always your initial relative minimum AND maximum since you have absolutely no basis of comparison from the get-go (unless you prime both relMin and relMax to 0 OR define a range to find your relMin and relMax). With that in mind the logic behind your example itself is flawed given your assumption of using -5 & 6 as the first comparison pair.
Let's use your array and iterate through the array with a For Loop...
[-5,-3,-2, 0, 1, 2, 6, 5, 3, 2,-1,-3,-4,-7,-4,-3,...]
0: relMin = -5, relMax = -5, delta = 0
1: relMin = -5, relMax = -3, delta = 2
2: relMin = -5, relMax = -2, delta = 3
3: relMin = -5, relMax = 0, delta = 5
4: relMin = -5, relMax = 1, delta = 6
5: relMin = -5, relMax = 2, delta = 2
6: relMin = -5, relMax = 6, delta = 11
7:
....
13: relMin = -7, relMax = 6, delta = 13
....
Essentially what you're doing is writing to your output array any time your current delta is not equal to your previous delta. Since a change between relMin and relMax is mutually exclusive (only one of those values can change as you traverse the array) all you have to check for is inequality...
//prime your values
//if it make sense for your purposes prime them both with 0
//this also assumes you have at least 1 value in valueArray
relMin = valueArray[0];
relMax = valueArray[0];
//the following line will always be true if you use valueArray[0] as your relMin and relMax baseline
deltaArray[0] = 0;
for (i = 0; i < [valueArray count]; i++)
{
if (valueArray[i] < relMin)
{
relMin = valueArray[i];
}
if (valueArray[i] > relMax)
{
relMax = valueArray[i];
}
deltaPrevious = deltaArray[[deltaArray count] - 1];
deltaCurrent = relMax - relMin;
if (deltaCurrent != deltaPrevious)
{
deltaArray[deltaArray count] = deltaCurrent;
}
}
My approach to this problem would be to first write an algorithm that detects the indices of the maximums and minimums, and then finds differences from there.
To get the maxes and mins, I would recommend iterating through the array and looking at the difference between the current and the previous and next value. You need to looking at changes in sign of the differences:
A minimum will occur when the differences change from negative to positive, and a maximum will occur when the differences change from positive to negative.
For example, look at this part of your array: [1,2,6,5,3]. The difference from 1 to 2 is positive, from 2 to 6 is positive, but from 6 to 5 is negative. The sign of the differences changed from positive to negative at the 6, so we know it is a maximum.
Note that you also need to include the first and last elements as possible maxes or mins.
Once you get the indices of maximums and minimums, you should be able to get their differences fairly easily.
In a most basic sense, you could iterate through the array, checking to see if the next value is greater than or less than the previous value. Whenever you reach a change (was increasing, now decreasing, or vice versa) you have found a relative max/min (respectively). A for loop to iterate, a boolean flag to check against (whether you were increasing or decreasing) and the obvious knowledge of both your current and previous index in the array to check/store.
I don't quite feel comfortable giving exact code for this since it's very basic and seems very much like a homework question...
I need to round a number, let's say 543 to either the hundreds or the tens place. It could be either one, as it's part of a game and this stage can ask you to do one or the other.
So for example, it could ask, "Round number to nearest tens", and if the number was 543, they would have to enter in 540.
However, I don't see a function that you can specify target place value to round at. I know there's an easy solution, I just can't think of one right now.
From what I see, the round function rounds the last decimal place?
Thanks
To rounding to 100's place
NSInteger num=543;
NSInteger deci=num%100;//43
if(deci>49){
num=num-deci+100;//543-43+100 =600
}
else{
num=num-deci;//543-43=500
}
To round to 10's place
NSInteger num=543;
NSInteger deci=num%10;//3
if(deci>4){
num=num-deci+100;//543-3+10 =550
}
else{
num=num-deci;//543-3=540
}
EDIT:
Tried to merge the above in one:
NSInteger num=543;
NSInteger place=100; //rounding factor, 10 or 100 or even more.
NSInteger condition=place/2;
NSInteger deci=num%place;//43
if(deci>=condition){
num=num-deci+place;//543-43+100 =600.
}
else{
num=num-deci;//543-43=500
}
You may just use an algorithm in your code:
For example, lets say that you need to round up a number to hundred's place.
int c = 543
int k = c % 100
if k > 50
c = (c - k) + 100
else
c = c - k
To round numbers, you can use the modulus operator, %.
The modulus operator gives you the remainder after division.
So 543 % 10 = 3, and 543 % 100 = 43.
Example:
int place = 10;
int numToRound=543;
// Remainder is 3
int remainder = numToRound%place;
if(remainder>(place/2)) {
// Called if remainder is greater than 5. In this case, it is 3, so this line won't be called.
// Subtract the remainder, and round up by 10.
numToRound=(numToRound-remainder)+place;
}
else {
// Called if remainder is less than 5. In this case, 3 < 5, so it will be called.
// Subtract the remainder, leaving 540
numToRound=(numToRound-remainder);
}
// numToRound will output as 540
NSLog(#"%i", numToRound);
Edit: My original answer was submitted before it was ready, because I accidentally hit a key to submit it. Oops.