How to store this pattern in Java arraylist? - java

I want to store the below array pattern in List, I am not understanding how to implement this as it has alternate increment.
Increment the number by 399.
Increment by 1
and continue the above 2 steps for a certain length of numbers.
If someone can guide me for the logic with simple OOPs concepts
0, 400, 401, 800, 801, 1200, 1201, 1600, 1601, 2000

You could also do something like this:
//add the first item outside of the loop, so that you can access the previous item within it
list.add(1)
//loop through the list in increments of 2
for (int i = 1; i < length; i += 2) {
list.add(list.get(i - 1) + 399);
list.add(list.get(i) + 1);
}

Figured it out, this is what I wrote now, and it workds
int pages = 8;
List<Integer> numArray = new ArrayList<Integer>();
numArray.add(0);
boolean incrementFlag = false;
int i = 400;
for (int j = 0; j < (pages-1); j++) {
numArray.add(i);
if (incrementFlag)
i += 399;
else
i += 1;
incrementFlag = !incrementFlag;
}

Related

How can I decrease the brightness of a new image by 50 units in 2D arrays of String using if statement in Java?

import java.util.Arrays;
public class Combining {
public static void main(String[] args) {
int[][] imageData={{100,90,255,80,70,255,60,50},
{255,10,5,255,10,5,255,255},
{255,255,255,0,255,255,255,75},
{255,60,30,0,30,60,255,255}};
//First, we want to crop the image down to a 4x6 image, removing the right 2 columns. Declare and initialize a new 2D array of integers with 4 rows and 6 columns called `newImage`.
int[][] newImage = new int[4][6];
//Now that you have your empty image, use nested **for** loops to copy over the data from the original image to the new image, make sure not to include the cropped out columns.
for (int i = 0; i < imageData.length; i++) {
for (int j = 0; j < imageData[i].length - 2; j++) {
newImage[i][j] = imageData[i][j];
}
}
System.out.println(Arrays.deepToString(newImage));
//You want to decrease the brightness of the new image by 50 units. The way this works is that for every integer in the new 2D array, we will subtract the value by 50. Remember that the value range for the pixel is 0-255, so if the result tries to go below 0, just set it equal to 0.
if (imageData[i][j] - 50 < 0) {
newImage[i][j] = imageData[i][j] - 50;
} else {
newImage[i][j] = 0;
}
System.out.println(Arrays.deepToString(newImage));
}
}
Below is the question I have.
We want to decrease the brightness of the new image by 50 units. The way this works is that for every integer in the new 2D array, we will subtract the value by 50. Remember that the value range for the pixel is 0-255, so if the result tries to go below 0, just set it equal to 0.
Below is the hint to the question.
Remember to check if the value minus 50 is less than 0 when iterating through the elements of the new image: if(newImage[row][column]-50<0). If that condition is true, then set the element to equal 0 else subtract 50 from the element.
Below is code I have tried to solve the question.
//You want to decrease the brightness of the new image by 50 units. The way this works is that for every integer in the new 2D array, we will subtract the value by 50. Remember that the value range for the pixel is 0-255, so if the result tries to go below 0, just set it equal to 0.
if(imageData[i][j] - 50 < 0) {
newImage[i][j] = imageData[i][j] - 50;
} else {
newImage[i][j] = 0;
}
System.out.println(Arrays.deepToString(newImage));
}
}
I keep getting syntax error in the console that cannot find symbol i and j.
Combining.java:23: error: cannot find symbol
if(imageData[i][j] - 50 < 0) {
^
for the first part of your code
the for loop can be replaced with this
for (int i = 0; i < 4; i++) {
System.arraycopy(imageData[i], 0, newImage[i], 0, 4);
}
check the api for more detail about this method arraycopy
by the way your code will work but this is just another way
now for the issue
Combining.java:23: error: cannot find symbol
if(imageData[i][j] - 50 < 0) {
i and j in the for loop are only defined inside the loop body
local variable are defined and accessible only from where they defined so for example
int[][] newImage = new int[4][6];
for (int i = 0; i < 4; i++) {
System.arraycopy(imageData[i], 0, newImage[i], 0, 4); // only i defined here
}
\\here you can only access imageData and newImage but not i as i out of the scope
for local variable the scope determined by the { }
check this to get more details about variable scope
so either to define i and j outside the for loop like
int i, j = 0;
for (; i < imageData.length; i++) {
for (; j < imageData[i].length - 2; j++) {
newImage[i][j] = imageData[i][j];
}
}
or do the subtraction inside the for loop
for (int i = 0; i < imageData.length; i++) {
for (int j = 0; j < imageData[i].length - 2; j++) {
newImage[i][j] = imageData[i][j];
if (imageData[i][j] - 50 >= 0) {
newImage[i][j] = imageData[i][j] - 50;
} else {
newImage[i][j] = 0;
}
}
by the way the logic with your if is not right you should check the above version
also you can do it using that
newImage[i][j] -= 50;
newImage[i][j] = newImage[i][j] >= 0 ? newImage[i][j] : 0;

Gnomesort only works for first two strings

I need to implement a gnomesort to sort strings on how close they are to the string input. I measure this difference with the Levenshtein-algoritm.
The algoritm works fine but only with if I have two strings in the database. It then sorts it fine, but if there are more than two strings, it just prints them in the order they are in the database. I really can't find the problem
public static void retrieveFromDatabase(String string)
{
String[] sq = new String[database.size()];
database.toArray(sq);
int r = 0, index = 1, y = 2, tmp1 = 0;
String tmp2;
int[] ds = new int[sq.length];
for (int i = 0; i < database.size(); i++) {
ds[i] = sortLevenshtein(string, database.get(i), false);
}
for(index = 1; index < ds.length; index++) // gnomsort
{
if(ds[index - 1] <= ds[index] )
{
++index;
}
else
{
tmp1 = ds[index];
tmp2 = sq[index];
ds[index] = ds[index - 1];
sq[index] = sq[index - 1];
ds[index-1] = tmp1;
sq[index-1] = tmp2;
index--;
if (index == 0)
index++;
}
}
System.out.println("Best matches: ");
for(r=0; r<Math.min(3,sq.length); r++)
{
System.out.println(ds[r] + "\t" + sq[r]);
}
}
The problem
Your gnome sort is not sorting correctly when there are more than two elements to sort.
In your problematic case your ds contains 1, 1, 0 from the outset. In your for loop index is 1. You see that the elements at indices 0 and 1 are in the correct order (both elements are 1), so you increment index to 2 in the if statement. Next your for loop also increments index, so it is now 3. 3 is not less than ds.length (also 3), so the loop terminates.
I don’t know gnome sort, so I can’t tell you the fix. What I can tell you is that manipulating your for loop control variable — index in your code — inside the for loop is the sure way to code that is hard to understand and very hard to find errors in. I never ever do that.
for(index = 1; index < ds.length; index++) // OK: loop control variable is incremented here
{
if(ds[index - 1] <= ds[index] )
{
++index; // No-no: incrementing loop control variable, dangerous
}
else
{
tmp1 = ds[index];
tmp2 = sq[index];
ds[index] = ds[index - 1];
sq[index] = sq[index - 1];
ds[index-1] = tmp1;
sq[index-1] = tmp2;
index--; // No-no: decrementing loop control variable, problematic
if (index == 0)
index++; // No-no: incrementing loop control variable
}
}

Shuffling an arraylist in java

Using an ArrayList, I need to subdivide a deck into two sections, one top section, and one bottom section. The top section will be the front of the ArrayList arr. If the size of the ArrayList arr happens to be odd, the top section size must be one more than the bottom section. Below you will see a few more specifications, there seems to be a slight logic error, but I'm having trouble figuring out where. As you can see, I have pretty much all of the code written and I feel as though this should be working. I need to shuffle without using collections.
for(int i =0; i<topHalf.size();i++){
topHalf.size() will return 0 because you have no elements in it yet. When you initialize it you are just allocating a size for the underlying array but the arraylist will have a size of 0...
As an aside you could use the sublist method.
// divide by two and round up
int middle = (int)(arr.size() / 2.0f + 0.5f);
ArrayList<Battleable> topHalf = arr.sublist(0, middle);
ArrayList<Battleable> bottomHalf = arr.sublist(middle, arr.size());
The easiest way is to use the 'sublist' method. You can do:
Double middle = Math.ceil(new Double(arr.size())/2);<br>
topHalf = arr.subList(0, middle.intValue());<br>
bottomHalf = arr.subList(middle.intValue(), arr.size());
The only change I would have made is adding a ternary operator to (simplify?) the code a little bit:
ArrayList<Battleable> topHalf = new ArrayList<Battleable>();
int topSize = arr.size() % 2 == 0 ? arr.size()/2 : (arr.size()/2)+1;
for(int i = 0; i < topSize; i++) {
topHalf.add(i, arr.get(i));
}
ArrayList<Battleable> bottomHalf = new ArrayList<Battleable>();
int count = topHalf.size();
int bottomSize = arr.size() - topHalf.size();
for(int i = 0; i < bottomSize; i++) {
bottomHalf.add(i, arr.get(count));
count++;
}
int x = 0, y = 0;
int end = arr.size();
for(int i = 0; i < end; i++) {
if(I % 2 == 0) {
arr.add(i, topHalf.get(x));
x++;
} else {
arr.add(i, bottomHalf.get(y));
y++;
}
}

Handling ArrayList out of bounds exception Java

My program will be creating a two dimensional grid / ArrayList. It will search for all boxes around a specific box and return their elements. However if the box is at an edge it may not have any surrounding boxes in the grid. So we will try to access an empty slot in an arrayList, possibly slot -1.
Is there anyway I can write some code like this in Java:
ArrayList arr = new ArrayList();
//add 5 elements to arr
for(int i = 0; i<10; i++){
if(arr.get(i) is out of bounds){
System.out.println("No elements here");
else{
System.out.println(arr.get(i));
}
You can check to see if i is outside the array bounds.
if i >= arr.size();
Though a better solution would be to loop over the contents of the array with a for each loop like so:
for (Object i : arr){
// Do something
}
You need boundary control check. For instance, if you need to loop around the neighbors of a point x, y, you could do
// assuming that you're checking around point x and y
// here you set minI, maxI
int minI = Math.max(0, x - 1);
int maxI = Math.min(listMax - 1, x + 1);
for (int i = minI; i <= maxI; i++) {
// here you set minJ and maxJ
int minJ = Math.max(0, y - 1);
int maxJ = Math.min(innerListMax - 1, y + 1);
for (int j = minJ; j <= maxJ; j++) {
// do your stuff here
}
}

Java lotto simulation

I am writing a program simulating a lotto draw of six numbers between 1 and 45, a sample output is 3 7 12 27 43 28. But what I am trying to do is count the number of times adjacent numbers appear, for example 1 4 5 29 26 41 is a positive answer because 5 comes after 4.
What is the best way of doing that?
I have tried examples such as :
int adjacent=0;
for(int i =0; i<6; i++)
{
int t = test[i]+1;
test[i]=(int)(45*Math.random())+1;
if(test[i]==t)
adjacent++;
System.out.print(test[i]+" ");
}
This does not work.
What am I doing wrong?
I think you just have an order of operations problem
int adjacent=0;
for(int i =0; i<6; i++)
{
//test[i] hasn't been set yet
int t = test[i]+1;
test[i]=(int)(45*Math.random())+1;
//this comparison doesn't make a whole lot of sense
if(test[i]==t)
adjacent++;
System.out.print(test[i]+" ");
}
Change it around to something like this:
int adjacent=0;
for(int i =0; i<6; i++)
{
test[i]=(int)(45*Math.random())+1;
int t = -1;
//Make sure this comparison only happens after the second iteration
//to avoid index out of bounds
if ( i != 0 )
{
//Set t to the last number + 1 instead of trying to predict the future
t = test[i-1] + 1;
}
//Now this comparison makes a little more sense
//The first iteration will compare to -1 which will always be false
if(test[i]==t)
adjacent++;
System.out.print(test[i]+" ");
}
This can be further simplified to just this:
int adjacent=0;
for(int i =0; i<6; i++)
{
test[i]=(int)(45*Math.random())+1;
if(i != 0 && test[i]==(test[i-1]+1))
adjacent++;
System.out.print(test[i]+" ");
}
After you generate your 6 numbers and put them into an array. Use Arrays.sort(). You can then compare adjacent array entries.
You should also avoid using Random to generate you 6 numbers, because it can generate duplicates. This may or may not accurately simulate your lotto draw. Quoi's answer has a good suggestion for this.
I think you should shuffle it and take any five. Collections#Shuffle would help you, It permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood.
List<Integer> list = ArrayList<Integer>();
list.add(1);
list.add(2);
Collections.shuffle(list);
Random rnd = new Random();
Integer[] result = new Integer[5];
result[0] = list.get(rnd.getNextInt(45));
result[1] = list.get(rnd.getNextInt(45));
result[2] = list.get(rnd.getNextInt(45));
result[3] = list.get(rnd.getNextInt(45));
result[4] = list.get(rnd.getNextInt(45));
It always gives you random values, then you should sort it to arrange it in order, say ascending.
Arrays.sort(result);
now you can write a loop to find out adjacent number.
int adjacent = 0;
for(int i=1; i<result.length;i++){
int prev = result[i-1];
int now = result[i];
if(prev+1 == now)
adjacent++;
}
You need to separate the generation of unique (hence the HashSet below to insure identity) random selections, sorting them, and then determining adjacency:
import java.util.HashSet;
import java.util.Arrays;
public class Lotto
{
public Lotto()
{
}
/**
* #param args
*/
public static void main(String[] args)
{
Lotto lotto = new Lotto();
lotto.randomizeSelections(5);
}
private void randomizeSelections(int numOfArrays)
{
for(int i = 0; i < numOfArrays; i++)
{
int[] selArry = new int[6];
//to insure that each random selection is unique
HashSet<Integer> idntySet = new HashSet<Integer>();
for(int j = 0; j < 6;)
{
int rndm = (int)(45 * Math.random()) + 1;
//add selection to the array only if it has not been randomized before
if(!idntySet.contains(rndm))
{
selArry[j] = rndm;
j++;
}
}
//sort the array for determing adjacency
Arrays.sort(selArry);
for(int j = 0; j < 6; j++)
{
int sel = selArry[j];
boolean isAdjcnt = (j > 0 && (sel == selArry[j - 1] + 1)) ? true : false;
System.out.println(i + "." + j + ".random = " + sel);
if(isAdjcnt) System.out.println("\tAdjacent");
}
}
}
}

Categories