Suppose I have one list which always has the count of even number. Now I want to segregate the list with different group indexes with below conditions,
1) First element (1st element) with one index (EX: 1)
2) Next two elements with same index (Ex: 2nd, 3rd element with index 2,
4th and 5th element with index 3)
3) Last element(6th element) with index 4
I tried with nested for loops to achieve the same, but didn't get the expected output.
Any help is appreciated.
Sample Input:
[2,3,53,52,33,12,44,66]
Sample Output:
2 - 1
3 - 2
53 - 2
52 - 3
33 - 3
12 - 4
44 - 4
66 - 5
I have implemented this using the two additional variables z and count, I am
incrementing z only if the count%2 is 0, and at-last we need to check if the
size-1 is equal to the i variable for the third condition.
Also, for the first condition I am printing the arraylist value at first index and z variable value at i iff the i counter value is 0.
Please see the below code that I have simulated for your input list that I
have added manually ! Please use the link to test :
http://rextester.com/ESYF23501
import javafx.collections.ArrayChangeListener;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> a= new ArrayList<Integer>();
a.add(2);
a.add(3);
a.add(53);
a.add(52);
a.add(33);
a.add(12);
a.add(44);
a.add(66);
int i = 0;
int z = 2;
//Count to group the middle number by checking its value with respect to mod 2
int count = 0;
for(i = 0; i < a.size(); i++)
{
if(i == 0 )
{
z = i+1;
System.out.println(""+a.get(i)+" " + "" +z+"" );
}
if(i > 0 && i != (a.size() -1))
{
//Increament z if the count is even so that we print the group for two times
if(count%2 == 0)
{
z++;
}
System.out.println(""+a.get(i)+"" +" "+ ""+z+"" );
count ++;
}
if(i == a.size() -1 )
{
z++;
System.out.println(""+a.get(i)+"" +" "+ ""+z+"" );
}
}
}
}
This should work correctly if I understood your question right:
System.out.println(elements.get(0) + " - 1"); // Prints the first number, which has the value of 1
int value = 2; // Value corresponding to the number
for (int i = 1; i < elements.size(); i++) { // Loops through the list starting at second element (index of 1)
System.out.println(elements.get(i) + " - " + value); // Prints the number and the value
if (i % 2 == 0) value++; // Increases the value every two loops
}
It starts by printing out the first number and 1, which as you described always corresponds to each other. Then it loops through the list of numbers starting at the second number (i = 1), and prints out each number and the corresponding value. The value increases every two loops, which is every time the loop number is divisible by 2 (i % 2).
Related
Candy Love
There are N children coming to the party and you have decided to distribute candies as return gift to those children. Children are numbered from 1 to N. You are given an array A which defines the maximum number of candies which can be given to any child. There are restrictions on number of candies which can be given to any child :
Each child should be given at least one candy.
The maximum candies which can be given to ith child is A[i].
The collective success of party is given by a function S which is calculated as follows :
function S():
Array C denotes the number of candies given to each child
sum = o
for i = 2 to N:
sum = sum a abs(c[i]-[i-1])
return sum
Now as the host of party you want to maximize the success of party. So distribute the candies in such a way which maximizes the success of party. Output the maximum value of success which can be obtained.
>##Sample Input##
You will be given N denoting the number of children in party and next line will consist of N space separated integers denoting the maximum candies which can be given to any child.
>##Sample Output##
Print the maximum success value of party which can be obtained.
>##Constraints##
2 <= N <= 10^5
1 <= A[i] <= 10^9
>##Sample Input 1##
3
1 2 4
>##Sample Output 1##
3
>##Sample Input 2##
6
3 10 15 10 3 10
>##Sample Output 2##
45
>##Explanation 1##
One of the ways to get success value as 3 is giving {1,2,4} candies to children respectively.
>##Explanation 2##
One of the ways to get success value as 45 is giving {1,10,1,10,1,10} candies to children respectively.
-to maximize the sum of differences each value X of the array should be changed to either 1 or X
import java.io.*;
class Test
{
static int maximumDifferenceSum(int arr[], int N)
{
int dp[][] = new int [N][2];
for (int i = 0; i < N; i++)
dp[i][0] = dp[i][1] = 0;
for (int i = 0; i< (N - 1); i++)
{
//dp[i][0] stores the maximum value of sum using first i elements if ith array value is modified to 1
dp[i + 1][0] = Math.max(dp[i][0],
dp[i][1] + Math.abs(1 - arr[i]));
//dp[i][1] stores the maximum value of sum using first i elements if ith array value is kept as a[i]
dp[i + 1][1] = Math.max(dp[i][0] +
Math.abs(arr[i + 1] - 1),
dp[i][1] + Math.abs(arr[i + 1]
- arr[i]));
}
return Math.max(dp[N - 1][0], dp[N - 1][1]);
}
public static void main (String[] args)
{
int arr[] = {3,10,15,10,3,10};
int N = arr.length;
// output will be 45
System.out.println( maximumDifferenceSum(arr, N));
}
}
there is such a question. I have a method that reads the bytes from a file into an array, and the method that searches for the longest byte sequence in this array.
private int element;
private int lastElement;
private int length;
private byte[] readByteFromFile(File name) throws IOException {
return Files.readAllBytes(name.toPath());
}
private void searchByte(byte[] byteMass) {
for (int i = 0; i < byteMass.length; i++) {
int count = 0;
for (int j = i + 1; j < byteMass.length; j++) {
if (byteMass[i + count] == byteMass[j]) {
if (count >= length) {
length = count + 1;
element = i;
lastElement = j - count;
}
count++;
} else {
count = 0;
}
}
}
}
Suppose that my file contains such a sequence of numbers:
444478126354444
In the case of processing, my method will deduce that the first occurrence was at 0, and the second at 11 and length of sequence = 4
But if I have such a sequence
133333444478126354444
Then my method will deduce that the first occurrence was at 1, and the second at 2, and the length of the sequence 4
How it can be fixed, that the method to continue to work correctly?
It is not tested. Don't have IDE infront of me.
The changes from the original code are. The second loop iterates one element less. If the next element is not equel to the previous then the loop exits.
private void searchByte(byte[] byteMass) {
int maxLength = 0
int element;
for (int i = 0; i < byteMass.length; i++) {
int count = 0;
for (int j = i + 1; j < byteMass.length-1; j++) {
if (byteMass[i] == byteMass[j]) {
if (count > length) {
maxLength = count;
element = i;
}
count++;
} else {
break;
}
}
}
If you haven't already I think it's very important to trace out the logic of your code!!! It's really important that you attempt to do this before asking for help. If you rely on others to work out your own logic, you won't make much progress as a programmer.
That being said, let's dive in and follow your code when it runs with the problem input (this isn't actual code, we're just looking at the values as the program runs)
byteMass = 133333444478126354444
(byteMass.length = 21)
length = 0
0 (i) < 21 (byteMass.length): true
count = 0
1 (j) < 21: true
1 (byteMass[0 (i + count)]) == 3 (byteMass[1 (j)]): false
count = 0
2 (j) < 21: true
1 (byteMass[0 (i + count)]) == 3 (byteMass[2 (j)]): false
count = 0
3 (j) < 21: true
1 == 3: false
it continues on like this, but something interesting happens when j = 12
12 (j) < 21: true
1 (byteMass[0 (i + count)]) == 1 (byteMass[12 (j)]): true
0 (count) >= 0 (length): true
length = 1 (count + 1)
element = 0 (i)
lastElement = 12 (j - count)
count = 1
This, to me at least, looks like unexpected behavior! We want to count repeated numbers, but this 1 is 11 digits away from the previous 1! We can fix this by editing the inner for loop like this
for (int j = i + 1; j < byteMass.length && byteMass[i] == byteMass[j]; j++) {
This way, the inner loop breaks as soon as byteMass[i] == byteMass[j] evaluates to false. now let's restart our process with the new inner for loop
byteMass = 133333444478126354444
(byteMass.length = 21)
length = 0
0 (i) < 21 (byteMass.length): true
count = 0
1 (j) < 21 && 1 (byteMass[0 (i)]) == 3 (byteMass[1 (j)]): false
1 (i) < 21: true
count = 0
2 (j) < 21 && 3 (byteMass[1 (i)]) == 3 (byteMass[2 (j)]): true
0 (count) >= 0 (length): true
length = 1 (0 (count) + 1)
element = 1 (i)
lastElement = 2 (2 (j) - 0 (count))
count = 1 (0 (count) + 1)
3 (j) < 21 && 3 (byteMass[2 (1 (i) + 1 (count))]) == 3 (byteMass[3 (j)]): true
1 (count) >= 1 (length): true
length = 2 (1 (count) + 1)
element = 1 (i)
lastElement = 2 (3 (j) - 1 (count))
This seems like unexpected behavior to me, but I won't fix it because I don't know how: I have no idea what element and lastElement represent. The code continues on like this until j = 6:
6 (j) < 21 && 3 (byteMass[5 (1 (i) + 4 (count))]) == 4 (bteMass[3 (j)]): false
2 (i) < 21: true
count = 0
3 (j) < 21: true
3 (byteMass[2 (2 (i) + 0 (count))]) == 3 (byteMass[3 (j)]): true
length = 1 (0 (count) + 1)
element = 2 (i)
lastElement = 3 (3 (j) - 1 (count))
count = 1 (0 (count) + 1)
This once again continues in the same fashion until j = 6. At this point hopefully you can see why your program isn't working as expected. But I still haven't answered the question of how to fix it. I don't really understand your thought process on how to solve this problem but I'll share with you my own
First of all we need to break the problem into smaller chunks!
You can do that any way you want to but here's my way: Our goal is to find the longest repeated pattern. Well in order to do that we need to figure out
when a number repeats itself and how many times it repeats itself
if that specific number repeated itself that specific amount of times anywhere else in the sequence. If it does, we'll need to save the amount of times it repeats itself
Then we'll repeat the process but only save the data if the number of repeats is larger than the saved data
It's actually a kind of complex problem and will probably be easier to solve with helper functions to be honest. I hope this helps!
I want to get two numbers whose product is equal to a given number. Below is my code but it throws an ArrayIndexOutOfBoundsException and I don't know why.
package com.sample;
public class ProductCheck {
public static void main(String[] args) {
// TODO Auto-generated method stub
int numArray[] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int temp = numArray[0];
for (int i = 0; i <= numArray.length; i++) {
if (temp * numArray[i + 1] == 27) {
System.out.println("The two numbers are " + temp + " and " + numArray[i + 1]);
} else {
temp = numArray[i + 1];
}
}
}
}
In this case it should print 3 and 9 as the product of these two numbers is equal to 27, but it doesn't work. Could anybody please point out why? Thanks in advance.
Your algorithm is incorrect, because it would never find a pair unless its members are at adjacent indexes. In other words, if you look, say, for 30, it would find 5 and 6, because they are next to each other; however, it wouldn't find 3 and 9, because there are other numbers between them.
To solve this problem correctly, you need two nested loops: one to pick the first number, and the other one to pick the second number to be multiplied. Then you would check the product in the inner loop, and print the result if the match is found.
for (int i = 0 ; i != numArray.length ; i++) {
for (int j = i+1 ; j != numArray.length ; j++) {
// Use i and j as indexes of the two numbers to be multiplied.
// Do your checking here, and print the result.
}
}
Note: You get ArrayIndexOutOfBoundsException because your loop condition is incorrect: the loop should stop when you reach numArray.length-1, because you access numArray[i + 1].
The exception occurs because your i loops from 0 to numArray.length, which is 10. But as you may know, arrays are zero based, so the largest index is 9. Putting 10 in there will certainly throw an exception. Looping to numArray.length - 1 doesn't work either because you are accessing i + 1, which will be 10 again. So you need numArray.length - 2 for it to not throw an exception.
Not throwing an exception doesn't mean it outputs the right thing though. You seem to be only looking at number pairs like (4,5), (5,6) etc. You will never check 3,9 like this.
Another approach is to output as soon as you find a number that is divisible by 27:
for (int i = 2 ; i < 27 ; i++) {
if (27 % i == 0) {
System.out.println("Found the two numbers: " + i + " and " + 27 / i);
break;
}
}
The Question was:
You are given a binary matrix (i.e. each element of matrix is either 0 or 1) of size n × n. You want to re-arrange 1's in such a way that they form a rectangular region. Note that the rectangular region should be made of only 1's, and all the 1's of the entire matrix should be in this rectangular region.
For achieving rectangular region, you can swap any two elements of the matrix. Please find out the minimum number of swaps needed. If it is not possible to re-arrange 1's in the desired way, please print -1.
Input
First line of the input contains a single integer T denoting number of test cases.
Description of T test cases follows.
First line of each test case will contain a single integer n denoting dimension of matrix.
Each of next n lines will contain n space separated integers denoting the ith row of the matrix.
Output
For each test case, print a single line containing a single integer denoting minimum number of swaps needed or -1 depending on the situation.
Example
Input:
2
2
0 1
1 0
2
1 1
1 0
Output:
1
-1
Explanation
Example case 1. You can swap 1 of second row first column with 0 of first row first column.
After the swap, matrix will look as follows.
1 1
0 0
Here all the 1's form a rectangular region of dimension 1 × 2. In this case, 1 swap will be needed.
Note that you can also swap 1 at first row second column with 0 at second row second column too.
Matrix after this swap will be following.
0 0
1 1
So you need 1 swap in this case too.
So overall, you need 1 swap.
Example case 2. There is no way to create a rectangular region containing 3 1's in a matrix of dimension 2 × 2, hence answer is -1.
My Algorithm [Edit]
First i am Taking Number of Cases from user
Then the order of matrix [will be of nxn order].
So logic is that if matrix is 1x1 then it will simply print 0
else while taking input from user [that will be only 1 or 0] i am counting 1's because the logic i develop that when in a matrix of odd order the 1's will be even then it cannot be arranged in rectangular form.and for even order of matrix if 1's are odd , not arrange able .
Next i am traversing each index if i find one then i move to next element else i try to find 1 in the same colomn if dont find than i am breaking loop showing -1 that it is not arrange able in rectangular form
Than after arranging a row i check the next row whether it is already arranged or not if it is than i break everything and moves to next case
n rectangular form
My Solution
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
static long startTime;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numberOfOnes = 0;
int T = scanner.nextInt();
for (int t = 1; t <= T; t++) {
int n = scanner.nextInt();
int loopCounter, swapCounter = 0;
boolean rowContainsZero = false;
int array[][] = new int[n][n];
boolean reject = true;
//Worst and the most simpler conditions
if (n == 1) {
System.out.print("0");
exitingSystem();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
array[i][j] = scanner.nextInt();
if (array[i][j] == 1) {
numberOfOnes++;
}
}
}
if (n % 2 == 0 && numberOfOnes % 2 != 0) {
System.out.println("-1");
if (t == T) {
exitingSystem();
}
continue;
} else if (n % 2 != 0 && numberOfOnes % 2 == 0) {
System.out.println("-1");
if (t == T) {
exitingSystem();
}
continue;
}
// System.out.println("Here i am");
//From here swaping processes will take the place
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (array[i][j] == 1) {
continue;
} else if (array[i][j] == 0) {
loopCounter = i;
reject = true;
while (loopCounter < n) {
if (array[loopCounter][j] == 1) {
int temp = array[loopCounter][j];
array[loopCounter][j] = array[i][j];
array[i][j] = temp;
reject = false;
swapCounter += 1;
break;
}
loopCounter++;
}
if (rowContainsZero) {
System.out.println("" + swapCounter);
break;
}
if (reject == true) {
System.out.println("-1");
break;
} else {
for (int m = i + 1; m < n; m++) {
for (int k = 0; k < n; k++) {
if (array[m][k] == 0) {
rowContainsZero = true;
} else {
rowContainsZero = false;
break;
}
}
}
}
} else {
System.out.println("0's and 1's were Expected :(");
exitingSystem();
}
}
if (reject == true) {
break;
}
}
}
}
public static void exitingSystem() {
System.exit(0);
}
}
BUT THE CODECHEF COMPUTER SAYING WRONG ANSWER + They allowed to take input from keyboard too
I think your algorithm isn't fully correct.
I think the following is a counter-example for your step 4 / odd order (n=3) and even number of ones (numberOfOnes=4):
1 1 0
1 1 0
0 0 0
This should give 0.
Similar for n=4 and numberOfOnes=3:
1 1 1 0
0 0 0 0
0 0 0 0
0 0 0 0
This should give 0 as well.
I haven't yet deeply analyzed your steps 5 and 6.
Here are some more examples:
1 1 1 0
1 1 0 0
1 1 1 0
1 1 0 0
This should give -1, as from 10 ones you can only form rectangles of the form 2*5 or 1*10, which both don't fit into the 4*4 frame.
1 1 1 0
1 1 0 0
1 1 1 0
1 0 0 0
This should give 1, as by moving the lower-left 1 two palces up and right, you get a 3*3 rectangle.
This is not the way you are trying to solve problem. Suppose you have
0 0 1
0 1 1
0 0 1
This is a perfect example of solveable matrix but you can't simply use random swap and then acquire result. You need to use A* search algorithm with manhatten distance.
Make a priority queue
Define manhatten distance.
Create a function which creates succesors of each board. Like if i have above board then it will give you a collection of boards back:
0 0 1
0 1 1 ==> colection
0 0 1
0 1 1
0 0 1
0 0 1
0 0 1
0 0 1
0 1 1
0 1 0
0 1 1
0 0 1
0 0 1
0 1 1
0 1 0
Description of A:*
an initial lis to store visited boar so that you don't visit them again.
i will call MinPriority queue a pq
`insert the initial_board in pq
while(!pq.isEmpty() && !foundGoal(pq.min)) //You find goal when your
manhatten distance is 0.
board = pq.delMin(); //you have to override the distance method in
priority queue so it will return you that board whoms manhatten
distance is smallest.
for(boards b :board.getSuccesors(); // give you collection of boards.
if(notvisited(b,vistiedList)) // so that you don't come in same state again and
again.
pq.insert(b);
visitedList.add(b);`
In first year i had to solve 8-puzzle and you can solve this way however you can also use hamming distance but that's not efficient and here is 8-puzzle code(with A* implementation).
As the title suggests, I have code for a Fibonacci series and my goal is to replace multiples of numbers (3, 5, 7 and combinations of them) in the series with a word. I was suggested to use a flag in my if loop to check for the printed phrase, and if the phrase is printed, to skip that number. Essentially, what I want the output to look like is:
1 1 2 skip 8 13 skip 34 55
(this is replacing multiple of three only, for now).
Instead, what I am getting is:
1 1 2 3 skip5 8 13 21 skip34 55
Here is my code as of now:
int febCount = 50;
long[] feb = new long[febCount];
feb[0] = 1;
feb[1] = 1;
for (int i = 2; i < febCount; i++) {
feb[i] = feb[i - 1] + feb[i - 2];
}
for (int i = 0; i < febCount; i++) {
System.out.print(feb[i] + ((i % 10 == 9) ? "\n" : " "));
if (feb[i] % 3 == 0)
System.out.print("skip");
}
Any and all help is appreciated!
Let's walk through the code you have provided and attempt to understand why it's not working.
//The first thing we do is setup the loop to iterate through the fib numbers.
//This looks good.
for (int i = 0; i < febCount; i++) {
//Here we print out the fibonacci number we are on, unconditionally.
//This means that every fibonacci number will be printed no matter what number it is
//we don't want that.
System.out.print(feb[i] + ((i % 10 == 9) ? "\n" : " "));
//After we print the number, we check to see if it is a multiple of three.
//maybe we should be waiting to print until then?
if (feb[i] % 3 == 0)
System.out.print("skip");
}
Now that we have walked through the code, we can propose a new solution.
Let's try updating the loop so that it wait's to print the fibonacci number until AFTER we've checked to see if it meets our conditions.
for (int i = 0; i < febCount; i++) {
if (feb[i] % 3 == 0 || feb[i] % 5 == 0 || feb[i] % 7 == 0) { //check if multiple of 3 5 or 7
System.out.println(" Skip ");
} else { //if it's not a multiple, then print the number
System.out.println(" " + feb[i]);
}
}