Java code 1+ issue - java

problem with Java code.
import java.util.Random;
public class arrayTable {
public static void main (String[] args) {
System.out.println("Index\t + Value");
int Array[] = new int[10];
Random Object = new Random();
int Values;
// Assigning random values to each element of array
for(int i=0; i<Array.length;i++) {
Values= (1+Object.nextInt(50));
Array[i] = Values;
}
for(int j=0;j<Array.length;j++) {
System.out.println(j + "\t" + Array[j]);
}
}
}
Here with this code i wrote (1+) next to the object so the index should start at 1, however when ever i run the code at always starts at index 0, and it does not matter if i type 2+ or 3+ pr whatever. Could anyone be helpful with pointing out the problem with the code.
thank you in advance.

i wrote (1+) next to the object so the index should start at 1
You wrote 1+ next to the value not the index!
So, what you were doing was:
array[0] = 50 + 1;
Instead of:
array[0 + 1] = 50;
If you wanted to start from index 1 you should write it here:
Array[i + 1] = Values;
However as you're inside a for loop, you could run into an ArrayIndexOutOfBoundsException, so, a better idea would be:
for(int i=1; i<Array.length;i++) { //Look the "i" was initialized with 1 and not with 0.
REMEMBER: ARRAYS START FROM 0 INDEX
If you want to "skip" the first element, then the above modification to for loop should work, but if you want it to run from 1 to 10 then it's a bad idea, because it should be from 0 to 9
You should also be careful to follow the Java naming conventions:
firstWordLowerCaseVariable
firstWordLowerCaseMethod()
FirstWordUpperCaseClass
ALL_WORDS_UPPER_CASE_CONSTANT
and use them consistently, this will make your code easier to read and understand for you and for us.
Also, try not to name your classes / variables as Java classes names:
Object or Array or List, etc might be wrong choices, also having object lowercase would be a bad idea as it's not descriptive either as suggested by #nicomp on the comments below
but when i type Array [i + 1] it still prints out from index 0, if for example i where to make i dice i would want it to start at index 1, is there no way to do this?
I think you didn't changed the for(int j=0;j<Array.length;j++) { loop, to start from 1
To make a dice I would:
Create the array with 6 slots (starting from 0)
Fill it (1 - 6) like below (inside a for loop):
dice[0] = 1;
dice[1] = 2;
...
dice[5] = 6;
//Example of for loop
for (int i = 0; i < dice.length; i++) {
dice[i] = i + 1;
}
Get a random number (between 0 - 5) called random
Get the value of the array at position random
For example:
random = 3;
//dice[random] = 4;
System.out.println(dice[random]);

Related

How to know the fewest numbers we should add to get a full array

recently I met a question like this:
Assume you have an int N, and you also have an int[] and each element in this array can only be used once time. And we need to design an algorithm to get 1 to N by adding those numbers and finally return the least numbers we need to add.
For example:
N = 6, array is [1,3]
1 : we already have.
2 : we need to add it to the array.
3 : we can get it by doing 1 + 2.
4: 1 + 3.
5 : 2 + 3.
6 : 1 + 2 + 3.
So we just need to add 2 to our array and finally we return 1.
I am thinking of solving this by using DFS.
Do you have some better solutions? Thanks!
Here's an explanation for why the solution the OP posted works (the algorithm, briefly, is to traverse the sorted existing elements, keep an accumulating sum of the preceding existing elements and add an element to the array and sum if it does not exist and exceeds the current sum):
The loop tests in order each element that must be formed and sums the preceding elements. It alerts us if there is an element needed that's greater than the current sum. If you think about it, it's really simple! How could we make the element when we've already used all the preceding elements, which is what the sum represents!
In contrast, how do we know that all the intermediate elements will be able to be formed when the sum is larger than the current element? For example, consider n = 7, a = {}:
The function adds {1,2,4...}
So we are up to 4 and we know 1,2,3,4 are covered,
each can be formed from equal or lower numbers in the array.
At any point, m, in the traversal, we know for sure that
X0 + X1 ... + Xm make the largest number we can make, call it Y.
But we also know that we can make 1,2,3...Xm
Therefore, we can make Y-1, Y-2, Y-3...Y-Xm
(In this example: Xm = 4; Y = 1+2+4 = 7; Y-1 = 6; Y-2 = 5)
Q.E.D.
I don't know if this is a good solution or not:
I would create a second array (boolean array) remembering all numbers I can calculate.
Then I would write a method simulating the adding of a number to the array. (In your example the 1, 3 and 2 are added to the array).
The boolean array will be updated to always remember which values (numbers) can be calculated with the added numbers.
After calling the add method on the initial array values, you test for every Number x ( 1 <= x <= N ) if x can be calculated. If not call the add method for x.
since my explanation is no good I will add (untested) Java code:
static int[] arr = {3,5};
static int N = 20;
//An Array remembering which values can be calculated so far
static boolean[] canCalculate = new boolean[N];
//Calculate how many numbers must be added to the array ( Runtime O(N^2) )
public static int method(){
//Preperation (adding every given Number in the array)
for(int i=0; i<arr.length; i++){
addNumber(arr[i]);
}
//The number of elements added to the initial array
int result = 0;
//Adding (and counting) the missing numbers (Runtime O(N^2) )
for(int i=1; i<=N; i++){
if( !canCalculate[i-1] ){
addNumber(i);
result++;
}
}
return result;
}
//This Method is called whenever a new number is added to your array
//runtime O(N)
public static void addNumber( int number ){
System.out.println("Add Number: "+(number));
boolean[] newarray = new boolean[N];
newarray[number-1] = true;
//Test which values can be calculated after adding this number
//And update the array
for(int i=1; i<=N; i++){
if( canCalculate[i-1] ){
newarray[i-1] = true;
if( i + number <= N ){
newarray[i+number-1] = true;
}
}
}
canCalculate = newarray;
}
Edit: Tested the code and changed some errors (but rachel's solution seems to be better anyway)
It is a famous problem from dynamic programming. You can refer to complete solution here https://www.youtube.com/watch?v=s6FhG--P7z0
I just found a possible solution like this
public static int getNum(int n, int[] a) {
ArrayList<Integer> output = new ArrayList<Integer>();
Arrays.sort(a);
int sum = 0;
int i = 0;
while(true) {
if (i >= a.length || a[i] > sum + 1) {
output.add(sum + 1);
sum += sum + 1;
} else {
sum += a[i];
i++;
}
if (sum >= n) {
break;
}
}
return output.size();
};
And I test some cases and it looks correct.
But the one who write this didn't give us any hints and I am really confused with this one. Can anybody come up with some explanations ? Thanks!

Understanding Array code

I am learning java, I just want to make sure I am understand this line of code properly. It is as follows:
public class DataStructure {
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
public DataStructure() {
for (int i = 0; i < SIZE; i++) {
arrayOfInts[i] = i;
}
}
The line I am not sure about is:
arrayOfInts[i] = i;
Is this saying that in the array, index 0 will produce an int value of 0, and index 2 will produce an int value of 2, and so on...?
Just to be clear, because I know this can be confusing, i is an int. By doing:
arrayOfInts[i] = i;
You are finding the i index. Where i is an int. So, if i is 7, it will be the 6th number of the array. Why not the 7th? Because it starts at 0:
(From the java docs)
So, lets say i is 7, right? It will be the 6th number. THAT IS IMPORTANT, and hopefully saves you lots of time with arrays.
Yes, you are correct. arrayOfInts[i] = i; means that at index i of the array arrayOfInts, the value is set to the integer i. So at index 0, it will have a value of 0; index 1 will have a value of 1 and so on. I hope this helps!
Rather than "produing" a value, as you stated, you are assigning a value to that index in the Array. If you were to go through the loop iteratively and wrote down each statement's outcome it would look like this if we use the logical statement arrayOfInts[i] = i
// first iteration
arrayOfInts[0] = 0;
i = i + 1;
// second iteration
arrayOfInts[1] = 1;
i = i + 1;
// third iteration
arrayOfInts[2] = 2;
i = i + 1;
So on and so forth. At the end of the iteration you will have a completely assigned Array that ends in the result
arrayOfInts = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]
Also always keep in mind as you learn more programming techniques and languages that in computer science we start counting at 0 instead of 1. It took me quite a while to get that through my head.

How to insert a number into an array in java

Ok I am trying to do the following using an array.
Say I have one array
1 4 3 7 8
and at index 1 I want to place a 2 to get the following
1 2 4 3 7 8
How do I do this I think I have to make one array to keep everything before the index, one array to keep everything after the index.
And the add one more element to the array with everything before the index. The create a new longer array with everything before the index and everything after the index.
But I cannot seem to do it. This be what I tried.
//this program will test out how to replace an array with more stuff
public class Raton
{
public static void main(String[] args)
{
int[] gato={1,4,3,7,8};
int[] perro = new int[gato.length+1];
int[] biggie = new int[gato.length];
int index=2; //store item index 2
System.out.println("the contents of gato are ");
for(int i=0; i<gato.length;i++)
{
System.out.println(gato[i]);
}
for(int i=0;i<gato.length;i++)
{
if(i<index)
{
perro[i]=gato[i];
}
else
{
int red=0;
biggie[red]=gato[i];
red++;
}
}
//put two in the new place
for(int i=0;i<perro.length;i++)
{
System.out.println(" \n the contents of peero are " + perro[i]);
}
for(int i=0; i<biggie.length;i++)
{
System.out.println("\nthe contents of biggie are " + biggie[i]);
}
}
}
First you need to get both the new number and new index.
int newNumber = 2;
int newIndex = 1;
Create the new array with size+1 of old array
int[] gato = {1,4,3,7,8}; //old array
int[] perro = new int[gato.length+1]; //new array
Then keep track of of two counters. j for old array and i for new array.
int j = 0;
for(int i = 0; i<perro.length; i++){
if(i == newIndex){
perro[i] = newNumber;
}
else{
perro[i] = gato[j];
j++;
}
}
Here's a test run. This solution is assuming you have a constraint where you can only use arrays (not ArrayList or any other prebuilt classes in Java)
Use an ArrayList<Integer> instead of arrays, they allow easy insertion of new elements, and arraylists allow that at specific indices too.
int[] gato={1,4,3,7,8};
List<Integer> list = new ArrayList<>(Arrays.asList(gato));
list.add(1, 2);
I haven't tested this code, but something similar should do the trick.
public class Raton {
public static void main(String[] args) {
int[] originalArray = {1,4,3,7,8};
int[] modifiedArray = new int[originalArray.length + 1];
int index = 2;
for(int i = 0; i < (originalArray.length + 1); i++) {
if(i==1) {
modifiedArray[i] = index;
}
else if(i < 1){
modifiedArray[i] = originalArray[i];
}
else {
modifiedArray[i] = originalArray[i-1];
}
}
}
}
Try to look at the "before" and "after" arrays:
Before
┌─┬─┬─┬─┬─┐
│1│4│3│7│8│
└─┴─┴─┴─┴─┘
0 1 2 3 4
After
┌─┬─┬─┬─┬─┬─┐
│1│2│4│3│7│8│
└─┴─┴─┴─┴─┴─┘
0 1 2 3 4 5
One thing you already noticed is that you need a target array that is 1 bigger than the original array. That's correct.
But you have several problems in your program.
You copy all the parts that are before the index to perro. Since perro is your target array (the one bigger than the original), you have to make sure that everything gets copied to it. But instead, you only copy the parts that are before the index.
You want to place the 2 at index 1. But you wrote index=2. This means that both the 1 and 4 will be copied to perro consecutively. Your perro will look like this:
┌─┬─┬─┬─┬─┬─┐
│1│4│0│0│0│0│
└─┴─┴─┴─┴─┴─┘
0 1 2 3 4 5
and this means that you didn't put the 2 in the place you wanted it. That place is taken by the 4.
You try to copy the numbers after the index to biggie. But you are doing this using red. And in each iteration of the loop, you set red=0 again. So the only place in biggie that will change is 0, and that place will get all the numbers, and the last one will stay. So your biggie will be:
┌─┬─┬─┬─┬─┐
│8│0│0│0│0│
└─┴─┴─┴─┴─┘
0 1 2 3 4
You don't put the 2 anywhere!
You don't copy things from biggie to perro so you don`t get all the parts of the array together.
So let's look at our before and after arrays again:
Before
┌─┬─┬─┬─┬─┐
│1│4│3│7│8│
└─┴─┴─┴─┴─┘
0 1 2 3 4
After
┌─┬─┬─┬─┬─┬─┐
│1│2│4│3│7│8│
└─┴─┴─┴─┴─┴─┘
0 1 2 3 4 5
So first, we have to remember that the index we want to change is 1, not 2. Now look at the after array. You notice that there are three types of numbers:
Ones that stayed in the same place (the 1)
Ones that were added (the 2)
Ones that moved one place to the right (4,3,7,8)
How do we know which of the original numbers "stay" and which ones "move"? It's easy. The ones whose index is less than index (remember, it's 1!), that is, the one at index 0, stays.
All the others (including the one that is in the index itself!) have to move to a new place. The place is their old index + 1.
So your program should look like this:
Prepare an array whose size is one bigger than the original (like your perro).
Loop on all the indexes in the old array. Suppose the loop variable is i.
If i is less than the index, copy the number at index i from the original array to the new array at the same index, that is, at i.
For all other cases, copy the number at index i from the original array to the new array, but moved by one place. That is, i+1. There is no need for another variable or a ++ here.
When you finish that loop, your array will look like:
┌─┬─┬─┬─┬─┬─┐
│1│0│4│3│7│8│
└─┴─┴─┴─┴─┴─┘
0 1 2 3 4 5
Now don't forget to put your actual 2 there, at the index index!
Note: please give your variables meaningful names. I'm not sure, perhaps the names are meaningful in your native language, but biggie and red seem to be words in English, but they don't help us understand what these variables do. Try to use variable names that describe the function of the variable. Like original, target, temporary, nextIndex etc.
I think this is a clean and simple solution :
public static void main(String[] args) {
int[] gato = {1, 4, 3, 7, 8};
int index = 2; //store item index 2
System.out.println("the contents of gato are ");
for (int i = 0; i < gato.length; i++) {
System.out.println(gato[i]);
}
gato = Arrays.copyOf(gato, gato.length + 1);
for (int i = gato.length - 1; i > index; i--) {
gato[i] = gato[i - 1];
}
//put the element in the array
gato[index] = 2;
for (int i = 0; i < gato.length; i++) {
System.out.println(gato[i]);
}
}

ArrayIndexOutOfBoundsException when looping

I'm pretty much a noob to programming but i have researched all over the place and cant find an answer. im using eclipse and every time i run my program it says:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at computer.guess(game1player2.java:24)
at game1player2.main(game1player2.java:39)
Here's my code:
import java.util.Scanner;
class computer{
int g = 0;
int[] compguess = new int[g];
void guess(){
int rand;
while(0 < 1){
int i;
rand = (int) Math.ceil(Math.random()*10);
for (i = 1; i < compguess.length; i++){
if(rand == compguess[i]){
break;
}
}
if(i > compguess.length){
g++;
rand = compguess[g];
System.out.println(compguess[compguess.length]);
}
}
}
}
public class game1player2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
computer computer1 = new computer();
for(int a = 0; a < 2; a++){
computer1.guess();
for(int n = 0; n <= computer1.compguess.length; n++)
System.out.println(computer1.compguess[n]);
}
{
input.close();
}
}
}
i am now really confused, i am trying to make a computer generate a random number 1-10, but if it is already in the array generates another one.
int g = 0;
int[] compguess = new int[g];
Your array is size 0, so you have no valid entries.
Since you initialized g as zero, your array compguess has a length of zero. Next when you enter your for loop you assign 1 to i which will allow you to enter into the if condition at the end of guess which will try to access element compguess[1] but this cannot exist because the array is of size zero.
You will run into problems if you do not correct the following.
Change: for(int n = 0; n <= computer1.compguess.length; n++)
To: for(int n = 0; n < computer1.compguess.length; n++)
If your array length is 8 then the last item in the array will be index 7, but the <= tells the loop to grab item index 8.
Your compguess has a length of 0, and you are starting your for loop with i = 1, wich is already greater than 0.
compguess is a zero-length array. If you try to index it, you will fall out of the array and hence the ArrayIndexOutOfBoundsException
If your intent is to make the array longer and add a new item to the end of it, you can't do that. I'm guessing that this is what you were trying to do here:
rand = compguess[g];
First of all, if the language did allow it, you'd want to write it the other way:
compguess[g] = rand;
because you're trying to put a value into a new element of the array, not read from the array. This would actually work in some languages (JavaScript, Perl, others). In Java, however, when you create an array object with something like new int[], the size is fixed. You can't make it longer or shorter.
You probably want to use an ArrayList, which does let you create an array that you can make longer. See this tutorial.

Array gets overwritten for no apparent reason

Problem
I have written a loop in which I fill an array with Sum objects. Everything works fine, but as soon as the loop gets to the next iteration it overwrites the first index of the array.
What have I tried
I tried to see if maybe my problem resides in a different piece of code (such as my Sum class). But could not find anything that would disturb the loop.
I tried to find other variables with the same name (even in other methods, since I was desperate) and see if I maybe changed my iterator somewhere else. I couldn't find anything related to that.
I tried looking around on the internet and SO to find something related to accidentally overwriting arrays but couldn't find anything either.
Code
public Task(Object[] parameters)
{
this.number_of_sums = Integer.parseInt((String)parameters[0]);
this.variables_per_sum = Integer.parseInt((String)parameters[1]);
this.sum_parameters = new Object[this.variables_per_sum];
this.sums = new Sum[this.number_of_sums];
int z = 0;
for(int i = 0; i < this.number_of_sums; i++)
{
int x = 0;
for(int j = (2 + z); j < ((this.variables_per_sum + 2) + z); j++)
{
this.sum_parameters[x] = parameters[j];
x++;
}
this.sums[i] = new Sum(this.sum_parameters);
System.out.println("Index 0: "+sums[0]); //1st iteration: 1 + 1 //2nd iteration: 2 - 1
System.out.println("Index 1: "+sums[1]); //1st iteration: null //2nd iteration: 2 - 1
z += this.variables_per_sum;
}
}
Expectations
I'm expecting the output of 1 + 1 and 2 - 1. I am however getting the following: 2 - 1 and 2 - 1 when I'm done.
If anyone spots anything I'm doing wrong or would like to see more information or code on my side please say so. Thanks in advance.
I'm going to assume the Sum class doesn't store its sum, but instead computes it from the array it was constructed with whenever it's needed.
It looks like all the Sum objects will share the same array -- you're passing the same reference every time you construct a Sum. Furthermore, every time you loop over j you overwrite the contents of that array.
So when everything is done, all the sums are the same.
You should be able to get around this by giving each Sum a different sum_parameters:
public Task(Object[] parameters)
{
this.number_of_sums = Integer.parseInt((String)parameters[0]);
this.variables_per_sum = Integer.parseInt((String)parameters[1]);
this.sums = new Sum[this.number_of_sums];
int z = 0;
for(int i = 0; i < this.number_of_sums; i++)
{
Object[] sum_parameters = new Object[this.variables_per_sum];
int x = 0;
for(int j = (2 + z); j < ((this.variables_per_sum + 2) + z); j++)
{
sum_parameters[x] = parameters[j];
x++;
}
this.sums[i] = new Sum(sum_parameters);
System.out.println("Index 0: "+sums[0]); //1st iteration: 1 + 1 //2nd iteration: 2 - 1
System.out.println("Index 1: "+sums[1]); //1st iteration: null //2nd iteration: 2 - 1
z += this.variables_per_sum;
}
}
Each one of your Sum objects is constructed with this.sum_parameters as a parameter:
this.sums[i] = new Sum(this.sum_parameters);
When sum_parameters is modified in each iteration of the outer loop, it changes internally in the objects constructed around references to it.
You should make an internal copy of sum_parameters in each Sum object.

Categories