I am trying to fill an array in two nested loops however for each second pPiece[] i want to give it a k attribute of 0 or 1 every second pPiece[] respectively
For example -
pPieces[0] = new Piece(0,pcName,1);
pPieces[1] = new Piece(1,pcName,1);
pPieces[2] = new Piece(0,pcName,1);
pPieces[3] = new Piece(1,pcName,1);
etc....
What i have
private Piece pPieces[] = new Piece[8];
for(int j=0; j<pCount; j++) //pCount = 4
{
for(int k=0; k<pcCount; k++) //pcCount = 2
{
String pcName = "Piece " + (allocation());
pPieces[j+k] = new Piece(k,pcName,1);
}
}
Doing it this way results in pPieces[] index being over written 4 times, i think. Is it possible to properly fill this array which should have 8 objects stored in it with every second 'k' equaling 0 or 1 respectively?
The issue in your current solution is that j+k will get the same value multiple times during the two loops:
for(int j=0; j<pCount; j++) //pCount = 4
{
for(int k=0; k<pcCount; k++) //pcCount = 2
{
String pcName = "Piece " + (allocation());
pPieces[j+k] = new Piece(k,pcName,1);
}
}
For example, when j = 0 and k = 1, you will have j + k = 1. But you will also have that when j = 1 and k = 0.
The problem comes from the fact that you're incrementing the variable j by steps of 1 when you should increment it by steps of pcCount; and the related issue is that j should go to pCount*pcCount and not pCount only.
for(int j=0; j<pCount*pcCount; j+=pcCount) //<--- j+=pcCount here, not j++
{
for(int k=0; k<pcCount; k++)
{
String pcName = "Piece " + allocation();
pPieces[j+k] = new Piece(k,pcName,1);
}
}
As a side-note, consider using more descriptive variable names instead of pCount and pcCount.
Refactor your code as follows, The issues is pPieces[j+k] = new Piece(k,pcName,1);
Your j+k => 0,1,1,2,2,3,3,4
Corrected Code
private Piece pPieces[] = new Piece[8];
int count=0;
for(int j=0; j<pCount; j++) //pCount = 4
{
for(int k=0; k<pcCount; k++) //pcCount = 2
{
String pcName = "Piece " + (allocation());
pPieces[count++] = new Piece(k,pcName,1);
}
}
Indeed, j+k will be overlapping. But 2j+k does not.
You need to replace by :
private Piece pPieces[] = new Piece[8];
for(int j=0; j<pCount; j++) //pCount = 4
{
for(int k=0; k<pcCount; k++) //pcCount = 2
{
String pcName = "Piece " + (allocation());
pPieces[2*j+k] = new Piece(k,pcName,1);
}
}
}
The % operator can be of use here:
private Piece pPieces[] = new Piece[8];
for(int j = 0; j < pPieces.length; j++) {
String pcName = "Piece " + (allocation());
pPieces[j] = new Piece(j % 2,pcName,1);
}
The % (modulus) operator returns the remainder of integer division.
e.g.
0 % 2 = 0
1 % 2 = 1
2 % 2 = 0
3 % 2 = 1
Creating an alternation of 1 and 0.
Related
For this particular problem I am attempting to remove redundant elements in an sorted array and replace them all with 0s at the end of the array. For example, if I had an array consisting of the int elements
1,3,3,4,4,5,6,6,7
My output array should be
1,3,4,5,6,7,0,0,0
My first attempt at the problem was to create a swapper in order to push all the 0s to the end of the list after removing the elements, but it won't seem to push the zeros to the end of the list. Here is my code.
public void implode(int[] ary)
{
int swapper = -1;
int[] newARY = new int[ary.length];
int current = -1;
for (int i = 0; i < ary.length; i++)
{
if (current != ary[i])
{
newARY[i] = ary[i];
current = ary[i];
}
}
for (int i = 0; i < ary.length; i++)
{
if (ary[i] == 0)
{
if (ary[i + 1] != 0)
{
swapper = ary[i + 1];
ary[i] = swapper;
ary[i + 1] = 0;
}
}
}
ary = newARY;
for (int i = 0; i < newARY.length; i++)
{
System.out.print(newARY[i] + " ");
}
}
The array im testing it with is,
int[] aryIn2 = {1, 1, 2, 3, 4, 4, 5, 6};
However, when outputting the imploded array, I receive this one.
1 0 2 3 4 0 5 6
Is there something I am missing?
Thanks in advance.
not an answer to your problem, but using (if possible) java streams can shorten your way:
int[] arr = {1,3,3,4,4,5,6,6,7};
// distinct
List<Integer> list = Arrays.stream(arr).distinct().boxed().collect(Collectors.toList());
// pad with zero's
while(list.size() < arr.length) {
list.add(0);
}
// display
System.out.println(list.stream().map(String::valueOf).collect(Collectors.joining(",")));
will output
1,3,4,5,6,7,0,0,0
Two issue with you code that I observed.
1) Your swapper logic is performing swapping on a different array than the one in which you had done modification earlier
2) You need to have this logic in a bubble-sort way, i.e. loop inside a loop
Below is a working modified sample code of your method. I have modified only the second for-loop logic
public void implode(int[] ary) {
int swapper = -1;
int[] newARY = new int[ary.length];
int current = -1;
for (int i = 0; i < ary.length; i++) {
if (current != ary[i]) {
newARY[i] = ary[i];
current = ary[i];
}
}
for (int i = 0; i < newARY.length - 1; i++) {
if (newARY[i] == 0 && newARY[i + 1] != 0) {
for (int j = i; (j + 1) < newARY.length; j++) {
swapper = newARY[j + 1];
newARY[j] = swapper;
newARY[j + 1] = 0;
}
}
}
for (int i = 0; i < newARY.length; i++) {
System.out.print(newARY[i] + " ");
}
}
In this first loop:
for (int i = 0; i < ary.length; i++) {
if (current != ary[i]) {
newARY[i] = ary[i];
current = ary[i];
}
}
You fill newARY with elements in ary with duplicated value turns to 0:
newARY: 1 0 2 3 4 0 5 6
However, in the second loop:
for (int i = 0; i < ary.length; i++)
{
if (ary[i] == 0)
{
if (ary[i + 1] != 0)
{
swapper = ary[i + 1];
ary[i] = swapper;
ary[i + 1] = 0;
}
}
}
You're modifying your original ary array. So the newARY is not updated.
However, your attempt to push 0 to the end of array also fail if there are more than two 0s consecutive. And it is also vulnerable to ArrayOutOfBoundIndexException since you try to read ary[i+1] without restriction on i
One simple and straight forward way to push 0s to the end of the array is to create new array with non-0s elements and fill 0s later:
int[] result = new int[ary.lenght];
int resultIndex = 0;
for (int i = 0; i < newARY.length; i++) {
if (newARY[i] != 0) {
result[resultIndex++] = newAry[i];
}
}
for (int i = resultIndex; i < newARY.length; i++) {
result[i] = 0;
}
// Print result array
Hint: Using above strategy, you can simplify your code. No need to create immediate array newARY. Just loop over the original array, push unique elements to the result array, then fill any slot left with 0s.
I would like to know, which is fast way to write/read in an int array.
Here my Java code: I have three int arrays, two in read access and one int array in write access.
for(int j = h20 ; j < h21 ; j++){
for(int i = w20 ; i < w21 ; i++){
if( int_color == arr3[j*h31 + i] ) continue; //condition
arr1[(j+decY)*w11 + i+decX] = arr2[j*w21 + i];
}
}
My code is a classic 2D array loop, there are just one special condition to check.
Is it other way to write this code to decrease processing time?
Thx.
You can reduce the amount of calculations, if you separate them by variables. In your case, any calculation that relies on j alone doesn't have to be inside the inner loop because the result won't change for the rest of the loop. Instead, calculate the values outside and only use the result in the inner loop.
for(int j = h20 ; j < h21 ; j++){
int tmp1 = j*h31;
int tmp2 = (j+decY)*w11 + decX;
int tmp3 = j*w21;
// j won't change inside here, so you can simply use the precalculated values
for(int i = w20 ; i < w21 ; i++){
if( int_color == arr3[tmp1 + i] ) continue; //condition
arr1[tmp2 + i] = arr2[tmp3 + i];
}
}
Edit: If you want to reduce this even more, you could rewrite the calculation for tmp2:
(j+decY)*w11 + decX ==> j*w11 + decY*w11 + decX
Then, you could extract the decY*w11 + decX into its own variable outside the first loop.
int tmp0 = decY*w11 + decX;
for(int j = h20 ; j < h21 ; j++){
int tmp1 = j*h31;
int tmp2 = j*w11 + tmp0;
int tmp3 = j*w21;
// j won't change inside here, so you can simply use the precalculated values
for(int i = w20 ; i < w21 ; i++){
if( int_color == arr3[tmp1 + i] ) continue; //condition
arr1[tmp2 + i] = arr2[tmp3 + i];
}
}
But this will save you only one addition per iteration, so I don't think it's worth the extra effort.
Removing calculations, especially multiplications might help.
For arr3 this would be:
final int icolor = int_color;
final int ix3 = h20 + w20;
final int dx3 = h31 + h21 - h20;
for (int j = h20; j < h21; ++j) {
for (int i = w20 ; i < w21 ; ++i) {
assert ix3 == j*h31 + i;
if (icolor != arr3[ix3]) {
arr1[(j+decY)*w11 + i+decX] = arr2[j*w21 + i];
}
++ix3;
}
ix3 += dx3;
}
Whether this is really worthwile one needs to test.
Depending on the frequency of the condition, one might think of using System.arraycopy for consecutive ranges of i.
rob = response.getJSONObject();
array = rob.getJSONArray("data");
fr = new ArrayList();
int count = array.length();
for (int i = 0; i < array.length(); i++) {
friend = array.getJSONObject(i);
fr.add(friend.get("name"));
}
Here fr is my array list.
I want to select first 50 result from output names.
Then next 50 result from output and then next 50, so on until all response ends.
Is there any way I can do that ? Itrate or For loop ?
for(int i = 0; i<fr.size(); i++){
System.out.print(fr[i]+",")
if(i%5==0) System.out.println();
}
Tried above code but result in untable some time it select one some time all .
Are you looking for this?
for (int i = 0; i < fr.size(); i++) {
System.out.print(fr[i]+",");
if ((i + 1) % 50 == 0) { // You have to use i + 1 because otherwise the modulo logic won't work
System.out.print("\n");
}
}
I'm trying to write a program that prints all substrings of entered string. For example if user enter "rum" the output will be this:
r
u
m
ru
um
rum
import java.util.Scanner;
public class AllSubStrings
{
public static void main(String[]args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = in.next();
String sub = "";
for(int i=0; i<str.length(); i++)
{
for(int a=0; a<str.length() ; a++)
{
if(i+a+1>str.length())break;
sub = str.substring(a,i+a+1);
System.out.println(sub);
}
}
}
}
This program works perfectly but since we didn't learn how to use "break" in classes, i'm looking for something different. Any idea apart from "break" are welcome.
Thanks in advance.
You can use this while loop cycle instead of for:
int a = 0;
while (a < str.length && i + a < str.length()) {
sub = str.substring(a, i + a + 1);
System.out.println(sub);
a++;
}
Also it is possible to replace break with return statement
Calculate how many possible substrings there can be for a certain length. For example, length 1 = 1 substring, length 2 = 3, length 3 = 6, and so on.
Then loop for that many times. There should be a generic formula you can use for no matter how long of an input string.
You don't need a break to do this task.
int len = str.length();
for (int i = 0; i < len; i++) {
for (int j = i; j < len; j++) {
System.out.println( str.substring( i, j + 1 ) );
}
}
You can have two conditions in the for loop
for(int a = 0; a < str.length() && i + a < str.length(); a++)
{
sub = str.substring(a,i+a+1);
System.out.println(sub);
}
Note that i + a + 1 <= str.length() is the same as i + a < str.length()
Ok i'm going to show my code and my input and output, Its very strange the value of my array seems to change from one line to the next.
import java.io.*;
class chefAndNewRecipe
{
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
BufferedReader r = new BufferedReader(new FileReader("/home/jer/Documents/chef.txt"));
int testCases = Integer.parseInt(r.readLine());
int numGuesses =0 ;
for (int i=0; i<testCases; i++)
{
int ingredients = Integer.parseInt(r.readLine());
String quantity = r.readLine();
String arr[] = quantity.split(" ");
int[] numIngredients = new int[arr.length];
for (int j =0; j< ingredients; j++)
{
String temp = arr[i];
numIngredients[i] = Integer.parseInt(temp);
System.out.println("This is numIngredients index: " + j + " and value " +numIngredients[i]);//print array location and value
}
System.out.println("numIngredients[0]:" + numIngredients[0]); // should be 2 and is
System.out.println("numIngredients[1]:" + numIngredients[1]); // should be 2 and is 0??
for (int k = 0; k< numIngredients.length; k++)
{
if (numIngredients[k] <2)
{
System.out.println("Value of numIngredients[k]: " + numIngredients[k]);// print value of numIngredients
System.out.println("-1");
}
else
{
numGuesses += numIngredients[k];
}
}
System.out.println(numGuesses);
}
}
}
my input is:
2
2
2 2
1
6
And my output is:
This is numIngredients index: 0 and value 2
This is numIngredients index: 1 and value 2
numIngredients[0]:2
numIngredients[1]:0
Value of numIngredients[k]: 0
-1
2
ingredients: 1
The value of numIngredients[1] changes from 2 to 0 from one line to the next, I can't understand whats going on.
Using long variable names is useful even for loop variables - you are seem to be using i instead of j:
for (int j = 0; j < arr.length; j++) // <== possibly arr.length is what you need.
{
String temp = arr[j]; // <=== was i, same next line
numIngredients[j] = Integer.parseInt(temp);
System.out.println(
"This is numIngredients index: " + j + //<== j this line
" and value " + numIngredients[j]); // <== again, was using [i]
}
Using currentIngredient instead of j possibly could help with finding an error.