Related
question:
Suppose this is the number in my array {1,2,3,4,5,6,7,8}
and each number is a position like ::
1=1 ,2=2 , 3=3, 4=4, 5=5, 6=6, 7=7, 8=8
It is not an array position just the number position. Now i want to remove the number in odd position then it becomes
2,4,6,8 :: 2=1, 4=2, 6=3, 8=4,
Now again i want to remove from the odd position so it becomes 4,8 :: 4=1, 8=2
Now the answer is 8 so how to get this 8
Code:
int [] arr = new int [] {1, 2, 3, 4, 5, 6, 7, 8}; //I am taking certain number in array
System.out.println("Elements of given array present on even position:");
for (int i = 1; i < arr.length; i = i+2) {
System.out.println(arr[i]);
}
must get the value as 8 but in output i get:
2
2
2
2
4
4
4
4
and so on
This will print out even numbers:
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0)
{
System.out.println(arr[i]);
}
}
If you want to remove the odd position elements from the array, then make a new one and use the above code to exclude odd elements like so:
ArrayList<Integer> newArr = new ArrayList<>();
for (int i = 0; i < arr.length; i++)
{
if (i % 2 == 0)
{
newArr.add(arr[i]);
}
}
As I said in my comment, you want the greatest power of 2 :
int max=0;
for (int i=0;i<arr.length;i++) {
int pos = arr[i];
if((pos & (pos-1)) == 0) { // check if pos is a power of 2
max =java.lang.Math.max(max, pos);
}
}
System.out.println(max)
if arr = {1,2,3,4,5,6,7,8}; => output 8
if arr = {1,2,3,4,5,6,7,8,9} => output 8
if arr = {1,2,3,...,20} => output 16
You could use an ArrayList
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0; i<arr.length; i++){
if(i % 2 == 0){ //if divide by 2 gives remainder 0 it is even
list.add(arr[i]);
}
}
arr=list.toArray();//get the array version of the list
Then you could put it in a while loop to do it until there is only one left.
int [] arr = new int [] {1, 2, 3, 4, 5, 6, 7, 8};
while(arr.length>1){
...
}
System.out.println(arr[0]);
Remember that we start counting at 0 so the first position(i=0) would even and the second position(i=1) would be uneven.
Final Code:
int [] arr = new int [] {1, 2, 3, 4, 5, 6, 7, 8};
while(arr.length>1){
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0; i<arr.length; i++){
if(i % 2 == 0){ //if divide by 2 gives remainder 0 it is even
list.add(arr[i]);
}
}
arr=list.toArray();//get the array version of the list
}
System.out.println(arr[0]);
This should do it for you
int [] arr = new int [] {1, 2, 3, 4, 5, 6, 7, 10, 11, 12}; //I am taking certain
System.out.println("Elements of given array present on even position:");
int counter=2;
while(counter<=arr.length){
counter*=2;
}
System.out.println(arr[(counter/2)-1]);
Let me know if this works
For example I have array with length n=3:
for(int i = 0; i < n; i++) {
array[i] = i;
}
So the cases should be:
1. 0
2. 1
3. 2
4. 0 1
5. 0 2
6. 1 2
7. 0 1 2
So the number of cases should be 7 for n = 3.
In my code:
int n = 3;
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = i;
}
int sum = 0;
for (int i = 0; i < n; i++) {
System.out.println(array[i] + " ");
sum++;
for (int j = i; j < n; j++) {
System.out.print(array[j] + " ");
}
System.out.println();
sum++;
}
System.out.println("sum = " + sum);
Output is:
0
0 1 2
1
1 2
2
2
sum = 6
The number 2 is two times so it is wrong and sum is actually = 5. And I don't get cases
4. 0 1
and
5. 0 2
How to count all possible cases?
Sets, not arrays
The first important observance is that you are not using fixed length arrays here but sets of different lengths.
Take a look at your example. You allow
0
1
2
0, 1
0, 2
1, 2
which are not all of size 3.
Also you don't differentiate between
0, 1
1, 0
so order doesn't matter, like in sets.
Power set
That's why you're actually describing power sets here. For the example set {0, 1, 2} its power set is defined as
P({0, 1, 2}) = {
{}, // empty set
{0},
{1},
{2},
{0, 1},
{0, 2},
{1, 2},
{0, 1, 2}
}
Fortunately there exists an easy closed formula for their size. If n is the size of the input set the size of the power set is
2^n
But they also count the empty set, so you will need to -1 if you don't want that:
2^n - 1
Solution
Thus in Java you could write
int Set<Integer> input = ...
int size = (int) Math.pow(2, input.size()) - 1;
and that's all, you don't need to build the contents manually.
But if you're curious and want to build them, take a look at questions like Obtaining a powerset of a set in Java. It's an implementation of the recursive formula shown at Wikipedia.
So, totally inefficient but also working:
int Set<Integer> input = ...
// Build the power-set using the method from linked question
Set<Set<Integer>> power = powerSet(input);
int size = power.size() - 1;
My Title may sound a bit silly, so here is the explanation:
I have an Array
int[] a = new int[] { 1, 2, 3, 4, 5, 6 };
And the output in the End should be like
123321
I already managed to output 123456 and 654321 but I can´t figure out how to output 123321 :(
I am only allowed to use one outer loop and in this loop it is allowed to have a new loop.
I tried different things but I didn´t manage to get it running, can you guys give me a hint please?
What I was thinking about in the beginning:
while(x <=2){
System.out.print(a[x]);
x++;
if(x==2){
while(x>0){
System.out.print(a[x]);
x--;
}
}
}
You should specify what conditions must the output meet.
For iterating to half of the array and then back to the beginning you don't need any inner loop. Try this:
int[] a = new int[] { 1, 2, 3, 4, 5, 6 };
for (int i = 0; i < a.length; ++i){
if (i<a.length/2) System.out.print(a[i]);
else System.out.print(a[a.length-i-1]);
}
The problem with your code is that you go to an infinite loop :
while(x <=2){
System.out.print(a[x]);
x++; // <-- you increment x until it reaches 2
if(x==2){ // <-- x equals to 2
while(x>0){
System.out.print(a[x]);
x--; // <-- you decrement x until it reaches 0
}
} // <-- Wow, 0 <= 2 so re-execute the while loop
You can implement it like this. When you'll go until the middle of the array, the inner loop will get executed until it prints the elements from the current index to 0.
int[] a = new int[] { 1, 2, 3, 4, 5, 6 };
int x = 0;
while(x != a.length/2){ // <-- loop until the middle of the array
System.out.print(a[x]);
x++;
if(x == a.length/2){ // <-- when we reach the middle execute the inner loop
for(int i = x -1; i >= 0; i--) // <-- print the elements of the array from current index to 0
System.out.print(a[i]);
}
}
Just other way with Collections:
List<Integer> first = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6 ));
int half = first.size()/2;
List<Integer> out = new ArrayList<Integer>( first.subList(0, half) );
Collections.reverse( first.subList( 0, half ) );
out.addAll( first.subList( 0, half ) );
System.out.println(out); // [1, 2, 3, 3, 2, 1]
I have been struggling with this java problem for several days now, and now I have to give up. I have been told the answer which should be 5 5 3 3, but I cannot in any way see how it is possible to get that result.
Given the following java method:
public int[] methodName(int[] nums)
{
int largestOdd=0;
for(int i=nums.length-2;i>=0;i--)
{
if (nums[i+1] % 2 != 0 && nums[i+1] > largestOdd)
largestOdd = nums[i+1];
if (nums[i] == 0)
nums[i] = largestOdd;
}
return(nums);
}
What is printed when the following Java statements are executed?
int[] nums = {0,5,0,3};
nums = methodName(nums)
for (int i = 0; i<nums.length;i++)
System.out.print(nums[i] + "");
System.out.println();
It just doesnt make any sense for me that first of all it will start printing "5". In my opinion it should be "3" because nums[2+1] = 3 (last index element)
Second of all why will it print four numbers when the loop in the method only will loop through 3 times until hitting -1 ?
If someone can explain how to get the result in a understandable way, I would be very happy.
Thanks in advance
methodName runs backwards through the array, examining every pair of numbers. In this case, the first pair examined will be (0,3).
As it runs over the pairs, methodName keeps track of the largest odd number seen (it looks at the second number of each pair for this).
Whenever the first number is zero, it sets it to the largest odd number seen so far.
So in this case, it will:
Look at (0,3).
Is 3 odd? Yes. Is it the largest odd number seen so far? Yes. So keep track of 3.
Is 0 zero? Yes. So set it to 3. Now the array is {0, 5, 3, 3}.
Move our indices back by 1 and look at (5, 3).
Is 3 odd? Yes. Is it the largest odd number seen so far? No.
Is 5 zero? No.
Move our indices back by 1 and look at (0, 5).
Is 5 odd? Yes. Is it the largest odd number seen so far? Yes. So keep track of 5.
Is 0 zero? Yes. So set it to 5. Now the array is {5, 5, 3, 3}.
We are already at the beginning of the array, so we can't go back any further.
Return to the main method, and print the contents of the array.
{0,5,0,3}
for(int i=nums.length-2;i>=0;i--) // starts at 0 (index 2) <-> num.length 4 - 2
// runs 3 times num.length(4) - 2 = 0
if (nums[i+1] % 2 != 0 && nums[i+1] > largestOdd)
largestOdd = nums[i+1]; <--> // 3
// if odd and grater than 0
// first iteration largestOdd = 3
if (nums[i] == 0) // still i is index 2 {0, 5, 0, 3} = 0, so true
nums[i] = largestOdd; // nums[i] (index 2) = 3
// after first iteration
{0, 5, 3, 3}
Second iteration do nothing (0 is not odd)
Third iteration, do same as first iteration, making final array
{5, 5, 3, 3}
Next Part
// This method returns the same array you passed into to
public int[] methodName(int[] nums)
{
return(nums);
}
// So
nums = methodName(nums) = {5, 5, 3, 3} The new array produced by the method
you can analyse step by step.
In the for-loop: i starts from 2 to 0;
num = [0,5,0,3]
1.
i = 2; largestOdd = 0; nums[i+1] = nums[3] = 3; nums[i] = nums[2] = 0;
first condition "(nums[i+1] % 2 != 0 && nums[i+1] > largestOdd)" is true
largestOdd = nums[i+1] = 3
second condition (nums[i] == 0) is true
nums[i] = nums[2] = largestOdd = 3
nums = [0,5,3,3];
2.
i=1; largestOdd = 3; nums[i+1] = nums[2] = 3; nums[i] = nums[1] = 5;
first condition is false;
second condition is false;
nums = [0,5,3,3];
3.
i=0; largestOdd = 3; nums[i+1] = nums[1] = 5; nums[i] = nums[0] = 0;
first condition is true
largestOdd = 5;
second condition nums[0] = 0 is true
nums[0] = largestOdd = 5;
nums = [5,5,3,3];
Loop 1 start i=2,nums=[0,5,0,3],largestOdd=0
because:(nums[2+1]=3)/2 !=0 && (nums[2+1]=3)>(largestOdd=0)
so:largestOdd=(nums[2+1]=3)=3
beacuse:(nums[2]=0) ==0
so:nums[2]=(largestOdd=3)=3
Loop 1 end i=2,nums=[0,5,3,3],largestOdd=3
Loop 2 start i=1,nums=[0,5,3,3],largestOdd=3
because:(nums[1+1]=3)/2 !=0 && (nums[1+1]=3)>(largestOdd=3)
so:next
beacuse:(nums[1]=5) !=0
so:next
Loop 2 end i=1,nums=[0,5,3,3],largestOdd=3
Loop 3 start i=0,nums=[0,5,3,3],largestOdd=3
because:(nums[0+1]=5)/2 !=0 && (nums[0+1]=5)>(largestOdd=3)
so:largestOdd=(nums[0+1]=5)=5
beacuse:(nums[0]=0) ==0
so:nums[0]=(largestOdd=5)=5
Loop 3 end i=0,nums=[5,5,3,3],largestOdd=5
END LOOP
I have a problem where I need to find the maximum distance between two different elements in an array.
For example: given an array 4,6,2,2,6,6,4 , the method should return 5 as the max distance.
I am able to solve the problem using two for loops but it is not an optimized solution. Am trying to optimize it by doing it in a single for loop.
here is my current solution:
int [] A = {4,6,2,2,6,6,4};
int N = A.length;
int result = 0;
for (int i = 0; i < N; i++){
for (int j = i; j < N; j++) {
if(A[i] != A[j]){
result = Math.max(result, j - i);
}
}
}
// tried below code but it is not efficient
// for (int i = 0; i < N; i++){
//
// if(A[N-1] != A[i]){
// result = Math.max(result, N-1-i);
// }
// }
System.out.println(result);
How to make this better in terms of time complexity?
Simple (not nested) loop is enough, but two cases should be taken into
account: either the best result is
4,6,2,2,6,6,4
^ ^ - moving first
or
4,6,2,2,6,6,4
^ ^ - moving last
for instance: [4, 2, 4, 4, 4] moving first brings the answer, when in case of [4, 4, 4, 2, 4] moving last should be used.
int first = 0;
int last = A.length - 1;
// 1st case: moving "first"
while (first < last) {
if (A[first] == A[last])
first++;
else
break;
}
int diff1 = last - first;
first = 0;
last = A.length - 1;
// 2nd case: moving "last"
while (first < last) {
if (A[first] == A[last])
last--;
else
break;
}
int diff2 = last - first;
// result is the max between two cases
int result = diff1 > diff2
? diff1
: diff2;
So we have O(N) time complexity.
Edit: Let's proof that at least one of the indexes is either 0 or length - 1. Let's do it by contradiction. Suppose we have a solution like
a, b, c, .... d, e, f, g
^ ..... ^ <- solution indexes (no borders)
Items to the left of c must be d, otherwise we can take a or b indexes and have an improved solution. Items to right of d must be c or we can once again push last index to the right and have a better solution. So we have
d, d, c .... d, c, c, c
^ .... ^ <- solution indexes
Now, since d <> c (c..d is a solution) we can improve the solution into
d, d, c .... d, c, c, c
^ .... ^ <- solution indexes
^ .... ^ <- better solution
We have a contradiction (the supposed solution is not one - we have a better choice) and that's why at least one index must be 0 or length - 1.
Now we have 2 scenarions to test:
a, b, ..... y, z
^ ...... ^ <- moving first
^ ...... ^ <- moving last
We can combine both conditions into if and have just one loop:
int result = 0;
for (int i = 0; i < A.length; ++i)
if (A[i] != A[A.length - 1] || A[0] != A[A.length - 1 - i]) {
result = A.length - i - 1;
break;
}
This can be done in a single loop
Consider this.
The maximum difference between from a index i can be either between start element and i or i and the last element
int main() {
vector<int> v {4, 6, 2, 2, 6, 6, 4};
int start = 0, end = v.size() -1;
int result = 0;
for(int i=0; i< v.size(); ++i)
{
if(v[i] != v[start])
{
result = max(result, i);
}
if(v[i] != v[end])
{
result = max(result, end - i);
}
}
return result;
}
The reason we are able to achieve a O(N) algorithm is because
Consider v = [4, 4, 2, 3, 4, 4]
At index i = 0 we check if we can find the maximum possible distance i.e with the last element but since they are same we can't consider it.
At i = 0 for this array the maximum possible answer would have been 5.
[4, 4, 2, 3, 4, 4]
^
At i = 1 we again check both ends of the array still the same so we move on.
The real savings come here that we do not have to check for every other entry
keeping the start at i = 0
So, at i = 2, we find that the maximum can be obtained with the end of the array
[4, 4, 2, 3, 4, 4]
^ ^ ^
start i end
which is the same as keeping the start constant and keeping a runner loop.