While going over newboston java tutorial, I am looking at array lessons and wondering why assigning variable in array is ++freq[1+rand.nextInt(6)]. I understand the 1+rand.nextInt(6) part but ++freq, I do not.
Because I come from other script background, I would think freq[roll] = 1+rand.nextInt(6) is the right way(but clearly not right).. can someone explain to me why ++freq[1+rand.nextInt(6)] works here?
Another words,
Aren't I doing
freq[0] = 1+rand.nextInt(6);
freq[1] = 1+rand.nextInt(6);
freq[2] = 1+rand.nextInt(6);
------ continue till
freq[9] = 1+rand.nextInt(6);
??
class apples {
public static void main(String[] args) {
Random rand = new Random();
int freq[] = new int[7];
for ( int roll=1; roll < 10; roll++) {
//++freq[1+rand.nextInt(6)];
freq[roll] = 1+rand.nextInt(6);
}
It's for the increment of value of freq array positioned at the 1+rand.nextInt(6) index. What you're doing is assigning value 1+rand.nextInt(6) to freq[roll]. So you are replacing the value at the position not incrementing it.
Related
Before I start I want to state that I am learning, I am completely new. Here i have added as much detail as possible.
So, I have an array of textures of different colors, and set a Random to randomize the textures, Like this:
Texture[] bubbles;
Random random = new Random();
int lowRange = 0;
int highRange = 3;
int result = random.nextInt(highRange -lowRange) + 1; //my random
ArrayList<Integer> BubbleXs = new ArrayList<>();
ArrayList<Integer> BubbleYs = new ArrayList<>();
#Override
public void create () {
bubbles = new Texture[4];
bubbles[0] = new Texture("blue.png");
bubbles[1] = new Texture("red.png");
bubbles[2] = new Texture("green.png");
bubbles[3] = new Texture("yellow.png");
}
Then I proceed to draw the texture at a random color falling from the top of the screen using a for loop, like this:
#Override
public void render () {
if (BubbleCount < 120) {
BubbleCount++;
} else {
BubbleCount = 0;
makeBubble();
}
public void makeBubble () {
float width = random.nextFloat() * Gdx.graphics.getWidth();
BubbleXs.add((int)width);
BubbleYs.add(Gdx.graphics.getHeight());
}
for (int i=0; i < BubbleYs.size(); i++) {
batch.draw(bubbles[result], BubbleXs.get(i), BubbleYs.get(i));
BubbleYs.set(i, BubbleYs.get(i) -4);
}
and it draws the textures at a a random perfectly, but only once, when its created, I want them to be a new random each time its looped, so its a different one every time one falls. why is it not doing that? what am I missing?
Thanks in advance!
Edit: I checked out this post: Change texture with random
but its not really helping any.
The reason they're all the same is that you assign a value to result only once, when it is initialized, and you never change it. If you want it to change, you need to use your Random to assign another value.
Your formula random.nextInt(highRange -lowRange) + 1 isn't right if you're wanting a random number between lowRange and highRange inclusive. That's giving you a number between lowRange + 1 and highRange + 1. The correct formula would be random.nextInt(highRange - lowRange) + lowRange.
The way to solve this would be create an additional variable for each bubble that stores the random int. You are already keeping a list for each of the two variables you're already storing (x and y). You could theoretically add a third, but it's to the point where you really just need to create a class for each bubble, so you can expand it easily if you add more features.
class Bubble {
int x;
int y;
int textureIndex;
}
Then replace your two array lists with:
ArrayList<Bubble> bubbles = new ArrayList<>();
And your makeBubble method should look like this:
void makeBubble(){
Bubble bubble = new Bubble();
bubble.x = (int)(random.nextFloat() * Gdx.graphics.getWidth());
bubble.y = Gdx.graphics.getHeight();
bubble.textureIndex = random.nextInt(3);
}
And your for loop for drawing them would look like this. I changed your textures array name here to bubbleTextures so bubbles can be used for the list of Bubble objects.
for (Bubble bubble : bubbles) {
batch.draw(bubbleTextures[bubble.textureIndex], bubble.x, bubble.y);
bubble.y -= 4;
}
There are numerous other issues I'm seeing with your code, but I think it would be overwhelming to explain them all. This at least gets you going in the right direction.
Here is the problem:
"Say you have an array for which the ith element is the price of a
given stock on day i.
If you were only permitted to complete at most one transaction (ie,
buy one and sell one share of the stock), design an algorithm to find
the maximum profit."
Here is my solution.
public class Solution {
public int maxProfit(int[] prices) {
int[] sell = new int[prices.length];
for(int i = 0; i<prices.length; i++){
for(int j = 0; j<i; j++){
sell[i] = Math.max(prices[i] - prices[j], sell[i]);
}
}
int sellPrice = prices[0];
int day = 0;
for(int i = 0; i<prices.length; i++){
if(sellPrice < prices[i]){
sellPrice = prices[i];
day = i;
}
}
int buyPrice = prices[0];
for(int i = 0; i<day; i++){
buyPrice = Math.min(buyPrice, prices[i]);
}
return sellPrice - buyPrice;
}
}
I'm not sure if it work, which is not a problem now. The problem is, it always shows Runtime Error at Line 9: (int sellPrice = prices[0];)
and
Line 18: (int buyPrice = prices[0];) as "java.lang.ArrayIndexOutOfBoundsException: 0".
So what's wrong with it? How to fix it? Thank you so much.
The only reason prices[0] would throw an AIOOBE is because the prices doesn't have any prices in it.
For example:
public static void main(String[] args)
{
int[] ints = new int[] {};
System.out.println(ints[0]);
}
Throws this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Main.main(Main.java:7)
Whereas this, works.
public static void main(String[] args)
{
int[] ints = new int[] {93727};
System.out.println(ints[0]);
}
Check if you are not passing a zero length array to your maxProfit method and be sure to initialize the array before using it in your method.
Here is the possibilty:
ArrayIndexOutOfBoundsException
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
The array you passing to this method is empty. That is no elements in that array. The part
equal to the size of the array. (size is 0 and index is zero)
That is the cause in your case.
You're getting an exception probably because the prices array was not instantiated correctly.
Also, your algorithm is not guaranteed to be correct: consider the following set of prices,
$4, $5, $1, $3
The maximum profit made would be 2 dollars, but your algorithm would result in $1.
Here's some correct answers: Maximum single-sell profit
How does your main look like??
Make sure the array prices[] is created and also initialized.
If it is created like int[] prices = new int[] {}; you will see an error saying index out of bound.
Make sure you initialize (from user input or using hard coded values).
If it is from user input make sure that the values are assigned.
Hard Coded one will look like this:
int price[] = {100,200,500,2000,700,500,400};
Hope it helps
leetcode
When prices.lenght = 0, prices[] is null at line 9 and 18.
That's why you got errors.
static int n = -1;
private static int repeatBuffer[] = new int[10];
static {
repeatBuffer[0] = 0;
//and more
repeatBuffer[9] = 9;
}
static public void randomize() {
do {
Random r = new Random();
randomNumber = r.nextInt(20);
} while (!uniqueInt(randomNumber));
Log.e(TAG, "" + randomNumber); //here I need have a unique int
}
private static Boolean uniqueInt(int random) {
for (int i = 0; i < 9; i++) {
if (random == repeatBuffer[i]) {
return false;
}
}
if (++n > 9)
n = 0;
repeatBuffer[n] = random;
return true;
}
Sometimes I'm getting same int twice, I'm wondering where is the problem? And is it even work? I spend quite a lot of time on this, and I give up. I think I need some minor tweaks in code :)
An easier way to get a random int is to create a List of integers List<Integer>, adding it with numbers that you would like to have. Then shuffling the List using Collections.shuffle(list);. Now start reading from the beginning of the list and you will get a unique random int each time.
Just make sure that each time you "read" a number from the list, either remove it from the list or increase the index for where you read.
That's the normal behavior of a random number generator, it's correct to generate repeated numbers as long as the number distribution remains uniform.
If you need a set of unique random numbers, you can generate them inside a loop and ask at every iteration if the newly generated number is present in the set of generated numbers. If not, add it, if yes, keep iterating - until the set has the desired size.
Er, a unique random between 1 and 20? What happens when it runs the 21st time?
Try making a List of the Integers between 1 and 20. Use Collections.shuffle() to shuffle the list. Then pop the first item off the front of the list and use that.
I am fairly new to Java, and I want to generate an array of random (x,y) coordinates of length 'number' that contains no duplicates. x or y values can be repeated, but there must be no repeated (x,y) coordinates. The output does not have to be Points, simply some way of holding x,y values for coordinates.
I can generate an array of random points, and have tried using a Set to ensure there are no duplicate values, but have run into problems. I tried using the condition "while (set.size)" and the 'add' method which should disallow duplicates, to create an output of the correct size which contains unique points.
This is the code:
Set<Point> set = new HashSet<Point>();
Random position = new Random();
Point test=new Point();
do{
test.x=position.nextInt(xx);
test.y=position.nextInt(yy);
//xx and yy are the random number limits called from another part of the code
set.add(test);
}
while (set.size()<number);
List<Object> list = new ArrayList<Object>(set);
Object[] coord = list.toArray();
This outputs an array of the correct length, but every element is the same. Can anyone offer any help?
Thanks
test points to the same variable in space everytime you loop, to fix that create a new instance inside the loop - not just once before it:
Set<Point> set = new HashSet<Point>();
Random position = new Random();
Point test;
do{
test = new Point();
test.x=position.nextInt(xx);
test.y=position.nextInt(yy);
//xx and yy are the random number limits called from another part of the code
set.add(test);
}
while (set.size()<number);
List<Object> list = new ArrayList<Object>(set);
Object[] coord = list.toArray();
You are modifying the same point object. However, since you change X and Y every time, you also changing hash code and equality of the point, so you end up placing the same object multiple times in the set. Interesting case.
try
do{
test = new Point();
test.x=position.nextInt(xx);
test.y=position.nextInt(yy);
//xx and yy are the random number limits called from another part of the code
set.add(test);
}
while (set.size()<number);
Value select Randomly but not repeated
Random rndm = new Random();
String[] selectedNumber = new String[15];
String[] sequanceNumber = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"};
//*****FIRST LOOP START*****//
for(byte a = 0; a < 15;){
int temp = rndm.nextInt(15)+1;
//*****SECOND LOOP START*****//
for(byte b = 0; b < 15; b++){
String s4 = temp+"";
//*****CHECKING CONDITION START*****//
if(s4.equals(sequanceNumber[b]) ){
selectedNumber[a] = s4;
String s1 = sequanceNumber[b];
s1 = s1.replace(s1, " ");
sequanceNumber[b] = s1;
a++;
}
//*****CHECKING CONDITION END*****//
}
//*****SECOND LOOP END*****//
}
//*****FIRST LOOP END*****//
//*****PRINT ALL RANDOM VALUES BUT NOT REPEATED VALUES*****//
System.out.println(Arrays.toString(selectedNumber));
I m generating one random card from array. and assigning it.'
Below is the code..but its is showing an error.
What is the problem?
public void rand() {
String rank[]= {"tclub1.png", "tclub2.png", "tclub3.png", "tclub4.png", "tclub5.png", "tclub6.png", "tclub7.png", "tclub8.png", "tclub9.png", "tclub10.png","tclub11.png", "tclub12.png", "tclub13.png"};
Random randInt = new Random();
int b = randInt.nextInt((rank.length));
showcard1.setBackgroundResource(b);
}
b is an int
so you need rank[b] the array at some point in your code
According to your code maybe it should read
showcard1.setBackgroundResource(rank[b]);
Try changing to int b = randInt.nextInt((rank.length)) - 1; (because rank.length = 13 and your array is indexed from 0 to 12)