I am very new to Java and am currently learning about arrays. Our homework this week is to
"Write a program that declares an array "alpha" of 50 elements of type "double". Initialize the array so that the first 25 elements are equal to the square of the index variable and the last 25 elements are equal to three times the index variable"
My question is this. Is the value in the element at an index position considered the index variable. For example if alpha[2] = 3 would 3 be the index variable, and in reading the assignment I would then square 3.
The other thought that I would have is that I have to square the index number [0],[1],[2]...
Thank you for any input, and I apologize if this is in the wrong area.
Thank you for the input so far. What I am trying to get to is what exactly is an "Index Variable"
Here is what I did
// Import various packages to be used in the program
import java.util.*;
import java.lang.*;
public class module5
{
static Scanner console = new Scanner(System.in);
public static void main (String[] args)
{
// Declare an array called alpha with 50 pre-defined elements
double []alpha = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50};
// Process the first 25 elements
for (int i = 0; i < 25; i++) {
// Square the first 25 elements
alpha[i] = Math.pow(alpha[i], 2);
}
// Process the second set of 25
for (int i = 25; i >= 25 && i < 50; i++) {
// Multiply by 3
alpha[i] = alpha[i] * 3;
}
for (int i = 0; i < alpha.length; ++i) {
System.out.print(alpha[i]);
if (i % 10 == 9) {
System.out.println();
} else {
System.out.print(" ");
}
}
}
}
No. In alpha[2] = 3 2 is the index variable, and 3 is the value being indexed. The other thought that I would have is that I have to square the index number [0],[1],[2] Correct.
alpha[0] = 0 * 0;
alpha[1] = 1 * 1;
alpha[2] = 2 * 2;
// ...
alpha[25] = 3 * 25;
// ...
alpha[49] = 3 * 49;
You are expected (I think) to use a loop with a conditional (but you might also use two separate loops with different initial and terminal conditions) to do these assignments.
You are dealing with int(s), so use an int[]. Something like,
int[] alpha = new int[50];
Then you might use a single for loop like,
for (int index = 0; index < alpha.length; index++) {
if (index < 25) {
alpha[index] = index * index;
} else {
alpha[index] = index * 3;
}
}
or two loops like
for (int index = 0; index < 25; index++) {
alpha[index] = index * index;
}
for (int index = 25; index < alpha.length; index++) {
alpha[index] = 3 * index;
}
or using a ternary (conditional operator ? :) and a loop like
for (int index = 0; index < alpha.length; index++) {
alpha[index] = index * ((index < 25) ? index : 3);
}
The index of an array element is the number in the brackets, [].
In the example, alpha[2] = 3, 2 is the index and 3 is the variable stored at index 2.
Also remember that for arrays, index 2 means that it is the third position in the array because the first index is position 0.
For this exercise, you would declare an index variable, i, and iterate through the array such that alpha[0] = 0, alpha[1] = 1, alpha[2] = 4, ... alpha[i] = i*i
Related
I'm new to coding and have been set a challenge of creating an method that prints out a multiplication array.
My code is as follows...
public class TimesTableArray
{
public static void main(String[] args)
{
int size = 12;
int number = 3;
}
private static int [] getTimesTable(int size, int number)
{
int[] timesTable = new int[size];
for (int i = 0; i < size; i++)
{
timesTable[i] = number * (i +1);
}
return timesTable;
}
}
I get the following output...
3
6
9
12
15
18
21
24
27
30
33
0
I need the 12th item to read 36, not 0. I know it's to do with the index reads from 0 to 11, but I don't know how to amend my code to make this so.
Please could someone guide me on how to do this?
You have a classic "off by one" error.
If you start at 1, then you INCLUDE the size, and have to subtract one to get the Index:
for (int i = 1; i <= size; i++)
{
timesTable[i - 1] = number * i;
}
If you start at 0, then you EXCLUDE the size, and have to add one when you multiply:
for (int i = 0; i < size; i++)
{
timesTable[i] = number * (i + 1);
}
You're going to have people swear up and down that one is correct and the other is wrong. This is down to preference. Do what "makes sense" to you.
In the population loop, you are iterating from 1 rather than 0 but you do not offset the terminal condition. I would rewrite you loop to follow the standard pattern rather than trying to bake in the offset. So...
for (int index = 0 ; index < size ; ++index) { ... }
This will allow the index to line up naturally in the assignment. Apply the offset in the calcuation.
timesTable[index] = number * (index + 1);
So you get...
private static int[] getTimesTable(int size, int number) {
int[] timesTable = new int[size];
for (int i = 0; i < size; i++) {
timesTable[i] = number * (i+1);
}
return timesTable;
}
You are having an off-by-one error. Since you want to have an array of 12 answers, starting with 1, your loop range has to be from 1 to 12 inclusive. Therefore:
private static int [] getTimesTable(int size, int number)
{
int[] timesTable = new int[size];
for (int i = 1; i <= (size); i++)
{
timesTable[i-1] = number * i;
}
return timesTable;
}
The reason why your last index was zero, is because numeric array indexes are initialized to zero after instantiation (new int[size]).
I have an ArrayList which contain 10 elements and a variable int = 12. Now I want to count how many elements are in array and if are less than 12 to start to count again from 0 and stop to index 2 and remove it, until I will have one element in my array. I tried the following:
int j = 12;
int l = 0;
// Here I check if j is less than array.size
while (j < array.size()) {
for (int i = 0; i < array.size(); i++) {
if (j == i + 1) {
array.remove(i);
}
}
}
// Here is for j greater than array.size
while (array.size() != 1) {
for (int i = 0; i < array.size(); i++) {
l = j - array.size();
if (l < array.size()) {
array.remove(l);
}
}
}
System.out.println(array);
UPDATE:
MyArray = {1,2,3,4,5,6,7,8,9,10};
int=12;
MyArray contain just 10 elements, but I want to delete the index with number 12, as long as index 12 does not exist I should start to count again from zero, and the number 12 is at index 2, That's why I should delete the index with number 2. The second iteration MyArray will contain just 9 elements, and again 12-9=3, I should delete the index with number 3, until I will have just one element in MyArray
Instead of looping twice through the array to remove the last n elements until the length of the list equals j, you could simply use:
while (j < array.size()) {
array.remove(j - 1);
}
If you always want to remove index 2, you could do:
while (array.size() >= 3) { // otherwise you will get a ArrayIndexOutOfBoundsException
array.remove(2);
}
However, you will have two elements left in your ArrayList instead of 1 (at index 0 and 1). You cannot delete ìndex 2 at that point, because it is not a valid index any longer.
Thus, you could either remove index 0/1 afterwards or what I think you want to achieve:
while (array.size() >= 2) { // otherwise you will get a ArrayIndexOutOfBoundsException
array.remove(1);
}
Then only one element will remain in your list at index 0.
Edit: for the update of your question it is
int originalSize = array.size();
while (array.size() >= originalSize - j) { // otherwise you will get a ArrayIndexOutOfBoundsException
array.remove(originalSize - j);
}
However, you will always be left with size - j items in your list. You cannot remove index 3, for example, until you have only one element in your list.
An answer to the updated question:
When you have a list of length 10 and you want to delete the "12th element" you can use the modulo operator:
ArrayList<...> someList = ...;
int toDelete = 12;
int deleteInRange = toDelete % someList.size();
someList.remove(deleteInRange);
The modulo operator will deliver the rest of the integerdivision 12 / 10 (toDelete % someList.size())
You can use this code snippet in a loop in order to remove multiple elements.
If you always want to remove index 2, you could do:
l = j - array.size();
Change this line as below:
int sum = 0;
sum = l - array.size();
if (sum > 0) {
array.remove(sum);
} else {
sum = array.size() - l;
array.remove(sum);
}
I would like to fill a 3x3 2D array with values 1,2,3.
I need each number to appear for a given times.
For example:
1 to appear 2 times
2 to appear 4 times
3 to appear 3 times
What I need is to store this numbers to array in a random position.
For Example:
1,2,2
3,2,2
1,3,3
I already did this in a simple way using only 2 different numbers controlled by a counter. So I loop through the 2D array and applying random values of number 1 and number 2.
I'm checking if the value is 1 and add it in the counter and the same with number 2. if one of the counter exceeds the number I have set as the maximum appear times then it continues and applies the other value.
Is there any better approach to fill the 3 numbers in random array position?
See code below:
int [][] array = new int [3][3];
int counter1 =0;
int counter2 =0;
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
array[i][j] = (int)random(1, 3); //1,2
if (arrray[i][j]==1) {
counter1++;
} else if (array[i][j] ==2) {
counter2++;
}
//if it is more than 5 times in the array put only the other value
if (counter1>5) {
array[i][j] = 2;
}
//if it is more than 4 times in the array put only the other value
else if (counter2>4) {
array[i][j] = 1;
}
}
}
I finally did this according to this discussion:
How can I generate a random number within a range but exclude some?, with 1D array for tesing, but it does not always works.
Please see attached code:
int []values = new int[28];
int counter1=0;
int counter2=0;
int counter3=0;
for (int i=0; i<values.length; i++) {
if (counter1==14) {
ex = append(ex, 5);
}
if (counter2==4) {
ex =append(ex, 6);
}
if (counter3==10) {
ex =append(ex, 7);
}
values[i] = getRandomWithExclusion(5, 8, ex);
if (values[i]==5) {
counter1++;
} else if (values[i] ==6) {
counter2++;
} else if (values[i] ==7) {
counter3++;
}
}
int getRandomWithExclusion(int start, int end, int []exclude) {
int rand = 0;
do {
rand = (int) random(start, end);
}
while (Arrays.binarySearch (exclude, rand) >= 0);
return rand;
}
I would like to fill the 1D array with values of 5,6 or 7. Each one a specific number. Number 5 can be added 14 times. Number 6 can be added 4 times. Number 7 can be added 10 times.
The above code works most of the times, however somethimes it does not. Please let me know if you have any ideas
This is the Octave/Matlab code for your problem.
n=3;
N=n*n;
count = [1 2; 2 4; 3 3];
if sum(count(:,2)) ~= N
error('invalid input');
end
m = zeros(n, n);
for i = 1:size(count,1)
for j = 1:count(i,2)
r = randi(N);
while m(r) ~= 0
r = randi(N);
end
m(r) = count(i,1);
end
end
disp(m);
Please note that when you address a 2D array using only one index, Matlab/Octave would use Column-major order.
There are a ton of ways to do this. Since you're using processing, one way is to create an IntList from all of the numbers you want to add to your array, shuffle it, and then add them to your array. Something like this:
IntList list = new IntList();
for(int i = 1; i <= 3; i++){ //add numbers 1 through 3
for(int j = 0; j < 3; j++){ add each 3 times
list.append(i);
}
}
list.shuffle();
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
array[i][j] = list.remove(0);
}
}
You could also go the other way: create an ArrayList of locations in your array, shuffle them, and then add your ints to those locations.
I'm trying to create a method that will search through a 2d array of numbers. If the numbers add up to a certain sum, those numbers should remain and all of the other numbers should be changed to a 0. For example, if the desired sum is 7 and a row contains 2 5 1 2, the result should be 2 5 0 0 after the method is implemented. I have everything functioning but instead of keeping all of the numbers that add up to the sum, only the last number is retained. So, I am left with 0 5 0 0 . I think I need another array somewhere but not sure exactly how to go about implementing it. Any ideas?
public static int[][] horizontalSums(int[][] a, int sumToFind) {
int[][] b = new int[a.length][a[0].length];
int columnStart = 0;
while (columnStart < a[0].length) {
for (int row = 0; row < a.length; row++) {
int sum = 0;
for (int column = columnStart; column < a[row].length; column++) {
sum += a[row][column];
if (sum == sumToFind) {
b[row][column] = a[row][column];
}
}
}
columnStart++;
}
return b;
}
In your example you use 2 5 1 1, would 0 5 1 1 also be a valid response? Or do you just need to find any combination? A recursive function may be the best solution.
If you just need to scan through the array and add up the numbers until the sum is reached then just add a for loop to copy the previous values from the array to the new array when the sum is found. Something like:
if (sum == sumToFind)
{
for (int i= 0; i<= columnStart; i++)
{
b[row][i] = a[row][i];
}
}
if (sum == sumToFind)
{
for (int i= columnStart; i<= column; i++)
{
b[row][i] = a[row][i];
}
}
A minor tweak was all it needed. If you have columnStart and column like in the other answer, it only finds the first number of the series.
I'm working on this code in my program right now and it seems that the problem is with the line where I stop the inner loop of the 2nd dimension.
this is a sample output of the array
9 6 6
7 6 4
4 8 5
when i run this code the output is:
4 4 6
5 6 6
7 8 9
my expected output is:
4 4 5
6 6 6
7 8 9
a digit:"6" is not in the correct place. Its because when I try to run the part where there is a nested for loop above a for loop, it only runs once and so it only checks the 1st column instead of getting to the third column where 6 is. The problem is I need to limit that loop in only reading the highest numbers from row#0 column#0 to row#2 column#0.
How do I solve this problem?? I thought of using a one dimensional array and put all two dimensional array elements and sort it there then put it back to the two dimensional array and print it again but that wouldn't make my code solve the needed process of sorting two dimensional array.
public static void sortArray(){
int x = len-1, y = len-1;
int iKey=0,jKey=0;
int cnt=0;
do{
cnt++;
if(y==-1){
x--;
y=len-1;
}
System.out.println(cnt+".)"+x+"-"+y);
int hi = -1;
for(i = 0;i <= x; i++)
for(j = 0;j <= y; j++){
if(twodiArray[i][j]>hi){
hi = twodiArray[i][j];
iKey = i;
jKey = j;
}
}
int temp = twodiArray[iKey][jKey];
twodiArray[iKey][jKey] = twodiArray[x][y];
twodiArray[x][y] = temp;
//dispArray();
y--;
}while(cnt<9);
}
The problem is in your loops where you search max element. Suppose you have array 5x5 and x=1 and y=1. Then you loop will check only following elements: [0][0], [0][1], [1][0], [1][1]. But it should also check [0][2], [0][3], [0][4].
With you previous code you only checked following cells:
XX...
XX...
.....
.....
.....
But you need to check these:
XXXXX
XX...
.....
.....
.....
So you need something like this:
for(i = 0;i <= x; i++) {
int upper; // How many elements we need to check on current row.
if (i != x) {
upper = len - 1; // We are not in last row, so check all elements.
} else {
upper = y; // On the last row we need to check only elements up to y.
}
for(j = 0;j <= upper; j++){
if(twodiArray[i][j]>hi){
hi = twodiArray[i][j];
iKey = i;
jKey = j;
}
}
}
My code checks every row fully until last one.
EDIT
If you use:
for (int i = 0; i <= x; i++) {
for (int j = 0; j <= y; j++) {
...
}
}
then you iterate only on recangle with upper left corner in (0,0) and right bottom cornar in (y,x). E.g. x = 4, y = 3:
XXX...
XXX...
XXX...
XXX...
......
But your goal is to do every row before last one fully. So check 0-th, 1-st and 2-nd rows fully and 3 elements from 3-rd row. My code does it. upper show how many values from row we need to check for all rows except last one it's equals to len - 1 (check full row). For last one it's y.
Your swap code (starting with int temp = twodiArray) is outside the main iteration loop. It needs to be moved inside the innermost loop.
BTW, you can do the swap without storing the indices.
Personally, to save myself some confusion, I would think of it as if it were a 1D array.
// I'm assuming that columnCount and rowCount are stored somewhere
public int getNthElement(int index) {
int colIndex = index % columnCount;
int rowIndex = (index - colIndex) / rowCount;
return twodiArray[rowIndex][colIndex];
}
public void setNthElement(int index, int value) {
int colIndex = index % columnCount;
int rowIndex = (index - colIndex) / rowCount;
twodiArray[rowIndex][colIndex] = value;
}
public void sortArray(int[][] array) {
int elementCount = rowCount * columnCount;
int curIndex = elementCount - 1;
while (curIndex >= 0) {
int highestIndex = -1;
int highestValue = 0;
for (int i = 0; i <= curIndex; i++) {
int nthValue = getNthElement(i);
if (nthValue > highestValue) {
highestIndex = i;
highestValue = nthValue;
}
}
int swapValue = getNthElement(curIndex);
setNthElement(curIndex, highestValue);
setNthElement(highestIndex, swapValue);
curIndex--;
}
}
You can see that I still use the 2D array and never use an actual 1D array, but this code indexes into the array as if it were a 1D array. (Hopefully that is valid in your professor's eyes)