I'm having difficulty understand how to write this array. I need it to out-print 10x5 (50 elements total), and have the first 25 elements equal to the sqrt of the index that it is in, and the last 25 to equal 3 * the index. Yes, this is homework but I'm not asking for you to do it for me, I just need help! I'm getting errors when using Math saying that I cant use double and the double array together. Here is what I have so far:
public class snhu4 {
public static void main(String args[]) {
double alpha[][] = new double[10][5];
double[] sum, sum2;
for (int count=0; count<=25;count++) {
alpha[count]= Math.sqrt(count);
}
for (int count=26; count<=50;count++) {
alpha[count]= count *3;
}
for (int count=0; count<=50;count++) {
System.out.print(alpha[count]);
}
}
}
Because alpha is a multidimensional array, you can't refer to its elements like a normal array.
int myarray[][] = new int[2][2];
In the above example, the array myarray is multidimensional. If I wanted to access the second element in the first array, I would access it like this:
int myint = myarray[0][1];
You are trying to access a multidimensional array by using the access for a normal array. Change
alpha[count]
to
alpha[0][count]
or similar.
Read here for more information on multidimensional arrays.
you defined alpha as a 2D array with lets say 10 items in the first dimension and 5 in the second, and 5x10 is 50 elements.
When using your array to assign values to these elements, u must call upon the array using 2 indices, one for each dimension:
alpha[i][j] = /*double value*/; //with 0<=i<=9 and 0<=j<=4
So the first 25 elements going from left to right in dimension order is going to be:
[0to9][0] and [0to9][1] and [0to4][2]
the next 25 will be
[4to9][2] and [0to9][3] and [0to9][4]
from then on i cannot give you the answers to your homework, but the loops should look like this:
int j;
for(int i = 0; i<25; i++)
{
j=i/10; //integer division will return 0 for i<10, 1 for 10<i<20, etc..
alpha[i%10][j] = Math.sqrt(i);
}
and you can figure out the rest
The 10x5 appears to be an output constraint, not a design constraint.
You are using Java, so use Java constructs, not C-language constructs;
specifically store the values in a List not an array.
Here are some hints:
List<Integer> valuesList = new ArrayList<Integer>();
for (int index = 0; index < 25; ++index)
Integer currentValue = Math.sqrt(index);
valuesList.add(currentValue);
for (int index = 25; index < 50; ++index)
Integer currentValue = index * 3;
valuesList.add(currentValue)
int count = 1;
for (Integer current : valuesList)
if ((count % 5) == 0) // write a newline.
System.out.print(current);
++count
Related
I need to arrange numbers of a given size (provided by user at runtime), to 3 dimensional array to represent these numbers in real 3D space.
For example if user enters 7 then I need to create an array of size 2,2,2 and arrange the first 7 numbers given by user into the array starting from position 0,0,0 .
The cube should always be smallest possible for example cube of size 2 can contain 2*2*2 = 8 values. And need a function that can take input numbers and return 3D integer array with values inserted from input array (input[0] will become result[0][0][0] and so on).
int input[7] ;
int[][][] result = bestFunction(int[] input) {...}
I have implemented with 3 nested for loops by checking each value at a time.
Is there a better or faster approach to implement it?
Do a Math.floor(Math.cbrt(val)) to get the dimension size.
I think we can reduce it to level 1 nesting, or using two loops, using a string input for the z-axis values.
for(int i = 0; i<size; i++)
for(int j = 0;j<size;j++)
arr[i][j]= Arrays.stream(sc.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
where Scanner sc = new Scanner(System.in); if you're taking in user input.
Three for loops would be O(n) as long as you break right after the last element of the input is put in.
int[][][] func(int[] input) {
int size = (int) Math.ceil(Math.cbrt(input.length));
int[][][] result = new int[size][size][size];
int x = 0;
loop: for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
for (int k = 0; k < size; k++) {
result[i][j][k] = input[x++];
if (x == input.length)
break loop; //Finish processing
}
}
}
return result;
}
I'm not allowed to use methods from any class except String and IO Class
So my code snippet is:
String line = reader.readLine();
while (line != null) {
String[] elements = line.split(",");
// Array could be too big if there are multiple occurances of
// the same number
// Array length + 1 because I can't use the 0 and with a input line of
// 1,2,3 for example would be the length 3 but I would have the
// numbers 0,1,2 in the Array as my index.
String[][] placeholderMatrix = new String[elements.length+1][elements.length+1];
for(int i = 0; i < elements.length-1; i++){
placeholderMatrix[(int)elements[i]][(int)elements[i+1]] = 1;
}
line = reader.readLine();
}
In the File I'm getting are only numbers like that: 1,2,3,4,5,8,7,4
So in my splitted String Array are only Numbers but now if I want to use them as my index for my Matrix(placeholderMatrix)
My problem is in my for loop where I want to use them as my Index I can't use them because it is a String Array. Normally I would use Integer.parseInt but I'm not allowed to :/
Any ideas on how I can implement them as my Index? and any Idea how I can get the perfect length of my Matrix? Because If I get the following numbers: 1,2,2,2,3 My Matrix should only have the numbers:
0 1 2 3
1
2
3
But if I'm using elements.length+1 for the length of my Matrix I would get the numbers 0 1 2 3 4 5
Hope you could understand my problem. Sorry for my bad english and Thanks in advance.
Edit: SO i got another problem with that. If I implement the method(parseInt) of Dici and am using it in the line "placeholderMatrix[parse(elements[i])][parse(elements[i+1])] = 1;" I'm getting the error ArrayOutOfBounce because my defined Array is just the length of my splitted String Array elements. But if I define it with Integer.MAX_VALUE as my length I get a memory error because it is too big. Any ideas?
Edit2: My Task:
I have to take a row of Numbers seperated by ",". (I will split it with the String split method to get only the numbers) Now I have to create a Matrix(2 dimensional Array) and look for the number at the index i of my new String Array and the number at the index i + 1 and have to take the first Number as my column and th second as my row (or vice versa) and implement at that point a 1. Now are my Numbers I will get from 1 to Integer.MAX_VALUE so I would have to create such a big Matrix but this isn't possible because I get the MemoryError.
Error: java.lang.OutOfMemoryError: Requested array size exceeds VM limit
at Test.main(Test.java:29)
To understand what I have to do: http://de.wikipedia.org/wiki/Adjazenzmatrix the image at the right but for numbers from to Integer.MAX_VALUE so my 2D Array has to be defined with the length of Integer.MAX_VALUE?
Edit:
So Dici asked for an example:
My Sequence could be: 1,2,5,4
So my Matrix should be:
Hope this is what you wanted Dici
But the numbers I can get from the sequence are 1 to Integer.MAX_VALUE
For converting strings to integers, you can simply implement your own integer parser, it is not complicated. You can start with this and improve it if needed.
public int parseInt(String s) {
int n = 0;
int pow = 1;
for (int i=s.length() - 1 ; i>=0 ; i--) {
String si = String.valueOf(s.charAt(i);
if (si.matches("[0-9]")) {
n += pow*(s.charAt(i) - '0');
pow *= 10;
} else if (si.matches("+|-") && i == 0)
n *= s.charAt(i) == '+' ? 1 : -1;
else
throw new NumberFormatException();
}
return n;
}
Then, I'll handle the second part of your problem. If Integer.MAX_VALuE is one of your input values, you cannot possibly allocate an Integer.MAX_VALUE x Integer.MAX_VALUE matrix. What you need to do is assign contiguous ids to your input values and record the ids in a map so that you can access easily the index of the matrix corresponding to one node value. Here is an example to get you to understand :
public void someMethod() {
int id = 0;
Map<Integer,Integer> idMap = new HashMap<>();
String[] split = reader.readLine().split(",");
int [] nodes = new int[split.length];
for (int i=0 ; i<nodes.length ; i++) {
nodes[i] = parseInt(split[i]);
if (!idMap.containsKey(nodes[i]))
idMap.put(nodes[i],id++);
}
// the map is now constructed, it should probably be stored in an attribute
int[][] placeholderMatrix = new int[nodes.length][nodes.length];
for(int i = 0; i < nodes.length; i++){
if (i > 0) placeholderMatrix[idMap.get(nodes[i])][idMap.get(nodes[i-1])] = 1;
if (i < nodes.length-1) placeholderMatrix[idMap.get(nodes[i])][idMap.get(nodes[i+1])] = 1;
}
}
There are other ways to do it, let me know if this solution is ok
You could do something like:
String keyword = "1,2,3,4,5,8,7,4";//input line from file
String replacedKeyword = keyword.replaceAll("[^\\d]", "");//except numbers replace all. Assuming one digit numbers only.
String[][] placeholderMatrix = new String[replacedKeyword.length()+1][replacedKeyword.length()+1];
char keys[] = replacedKeyword.toCharArray();
for (int i = 0; i<keys.length - 1; i++) {
placeholderMatrix[keys[i] - '0'][keys[i + 1] -'0'] = "1";
}
I couldn't really understand what you want exactly. but, if that going to help a simple method to convert String number to int:
int toInt(String number) {
int num = 0;
for (int i=0; i<number.length(); i++) {
num = num*10 + (number.charAt(i)-'0');
}
return num;
}
Right, so I have a 2 part sorting algorithm. It's all based on an array of 14 random integers. For example:
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
Now, the first thing I'm trying to figure out how to do is to count how many a certain number exists in the original array. So, we know that 1 exists once, and 2 exists four times in the original array. But as easy as it is to visually see this, what if we don't have access to the original array. So I need to craft a method that will count how many of each number 1-9 exists and put this in a new array called count. So that index 0 in count would represent the integer 1 and would have a value of 1. Index 1 will represent the integer 2 and have a value of 4. And so on and so forth. Here is what I've got so far but I'm stuck. Sorting is pretty challenging for me.
public static void main(String[] args)
{
// int[] countFinal = {1,4,1,2,1,0,1,2,2}; // The number of times a number 1-9 appears in a[].
// int[] sortedFinal = {1,2,2,2,2,3,4,4,5,7,8,8,9,9}; // What we need as a final product.
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
//int[] count = {};
int[] sorted = {};
countHowMany(a, 1);
countHowMany(a, 2);
countHowMany(a, 3);
countHowMany(a, 4);
countHowMany(a, 5);
countHowMany(a, 6);
countHowMany(a, 7);
countHowMany(a, 8);
countHowMany(a, 9);
}
public static int countHowMany(int[] array, int value)
{
// Gathering a count for how many times a number 1-9 exists and adding it to count[];
int howManyCount = 0;
for (int i = 0; i < array.length; i++)
{
if (array[i] == value)
{
howManyCount++;
}
}
System.out.println(howManyCount);
count = new int[9];
count[howManyCount];
System.out.println(Arrays.toString(count); // Testing the input
return howManyCount;
}
It appears to count the number of times an item in the array exists properly. Now I just gotta figure out how I can add that value into a new array count[] and do it for each countHowMany(). This is the part I'm stuck on.
Once I have figured out count[] I can use it to create sorted[]. Now what sorted is supposed to do is take the data from the original array and count[] and create a new array that sorts it in ascending order and allows duplicates. So, since 1 occurs once and 2 occurs four times, the new array would be sorted[] = {1, 2, 2, 2, 2, ...}
It's a relatively small program and a small amount of integers, so it's ok that I create array's as necessary. The key being that I'm limited to using arrays and cannot use say ArrayLists for this.
You don't need to count each value individually. You can just iterate through the entire array and increment your counters for each element as you encounter it.
int counts = new int[20]; // Choose a value that's bigger than anything in your array.
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
for (int value : a) {
counts[value]++;
}
If you don't know what the largest value in your array is likely to be, you're better to use either a Map to store the counts, or some kind of List that you increase the size of as needed.
You're better off just going through the array once and incrementing a counter for each value that might appear:
int counts[] = new int[10];
for (int n: array)
counts[n]++;
That's enough to put the count for each n in counts[n]. You can then read the values out of your count[] array.
You might not have come across this syntax for a for loop over an array, by the way. It's equivalent to
int counts[] = new int[10];
for (int i=0; i<array.length; i++) {
int n = array[i];
counts[n]++;
}
but it's less verbose.
Your method may as well be void, since you're not doing anything with the returned values of your countHowMany function. This will accomplish what you want:
public static void main(String[] args)
{
int[] a = {9,2,4,8,9,4,3,2,8,1,2,7,2,5};
//count the instances of each number in the array
int[] count = new int[9];
for(int i = 0; i < count.length; i++)
count[i] = countHowMany(a, i+1);
//put the values in the sorted array
int[] sorted = new int[a.length];
int position = 0; // stores the place in the array to put the new digit
for(int digit = 0; digit < 9; digit++)
{
for(int inst = 0; inst < count[digit]; inst++)
{
sorted[position] = digit + 1;
position++;
}
}
System.out.println(Arrays.toString(sorted));
}
The issue with your code is that you were trying to create the count array in each call of the countHowMany method, but this array is destroyed once the method finishes. The method calls should just return the counts, and then those returns should be put into the count array from outside the method. Note, however, that there are other ways to count the number of instances of each value, as noted by other answers.
Help! I have this school assignment that wants me to write a method to find the area of rectangles (an array of ints) by multiplying width (an ArrayList) by length (an array of doubles). I'm very very new to coding; I've tried for over five hours to get this working, but I keep doing things wrong and I simply can't get it right. This is the code for the method that I've written:
public void calcRectangleArea(int index, ArrayList width, double[] length, int[] area)
{
double temp = length[index];
for(index = 0; index < length.length; index++)
{
for(index = 0; index < width.size(); index++)
{
Object widthObj = (int)width.get(index);
area[index] = temp * widthObj;
}
}
}
The full starter code we were given is here, if you need more context (it's commented): http://pastie.org/pastes/916496
Thank you so much for any help you can give me in writing this method. I've been working for hours and I just can't get it...
The length of the array and size of the arraylist should be same , And you have to change the method logic a bit, Have a look at the below code snippet
public static int[] calcRectangleArea(List<Double> width, double[] length)
{
int[] area=new int[length.length];
for(int index = 0; index < length.length; index++)
{
area[index] = (int) (length[index]*width.get(index));
}
return area;
}
Call this method passing width arraylist and length array. It will return area array of ints
You dont really need two loops here. Assuming that width[1] correlates to length[1] you can just loop through both collections at the same time in the same loop.
This should work (i haven't written a line of java in ~2 years so it may not be 100%)
public void calcRectangleArea(int index, ArrayList width, double[] length, int[] area)
{
//assuming length.length == width.size
for(index = 0; index < length.length; index++)
{
int anArea = (int)(width.get(index) * length[index]);
area[index]=anArea;
}
}
again the code above assumes the size of the collections are the same.
Firstly, you don't need to assign temporary variables:
double temp = length[index];
...
Object widthObj = (int)width.get(index);
Since you will only reference them once. Reference them directly instead:
area[index] = length[index] * (int)width.get(index);
Secondly, your for loops are unneeded, and they are declared wrong. You're trying to increment the index (and twice nonetheless) that was passed to the function which will cause problems. If you were to use nested for loops, you would declare a new iterator variable for each of them:
for (int i = 0; i < something; i++) {
for (int j = 0; j < somethingElse; j++) {
doSomething();
}
}
However in this case you don't even need them.
In addition, you should not have created an Object when you wanted to cast an int:
Object widthObj = (int)width.get(index);
should have been
int width = (int)width.get(index);
However again, this line is unnecessary, and you shouldn't be casting to int this early.
Ultimately, all you need to do is the one line:
area[index] = (int)(length[index] * width.get(index));
Yes, this is homework, but I need some help with it. I have been able to make it sort through the highest number, but none of the numbers are correct after that. List of numbers: http://pastebin.com/Ss1WFGv1
Right now, we are learning arrays, so is this simply trying to shoot a fly with a cannonball?
package hw2;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class HW2 {
public static ArrayList<Integer> nums1 = new ArrayList<Integer>();
public static int size = 0;
public static void main(String[] args) throws Exception {
ArrayList<Integer> sortedNums = new ArrayList<Integer>();
readFile();
System.out.println("Name: Jay Bhagat" + "\n" + "Email: xxxxxx");
size = nums1.size();
for(int l = 0; l<=10;l++){
nums1.set(sortThis(nums1, l), 90009);
System.out.println("\n\n");
}
// for (int k = 0; k <= size - 1; k++) {
// System.out.println("Number " + (k + 1) + sortedNums.get(k));
//
// }
}
public static void readFile() throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("L:\\numbers.txt"));
while (reader.readLine() != null) {
nums1.add(Integer.parseInt((reader.readLine())));
}
reader.close();
}
public static int sortThis(ArrayList<Integer> current, int offset) {
int j = 0;
int tempNum = 0;
int curNum = 0;
int finalIndex = 0;
int prevIndex = 0;
int curIndex = 0;
for (j = 0; j < size-offset; j++) {
curIndex = j;
nums1.trimToSize();
curNum = current.get(j);
//Thread.sleep(1000);
if(curNum!=90009){
if (curNum > tempNum) {
tempNum = curNum;
System.out.println(tempNum);
prevIndex = j;
finalIndex = prevIndex;
}
if (curNum < tempNum) {
finalIndex = prevIndex;
}
}
}
return finalIndex;
}
}
An approach that lets you make just one pass through the list and doesn't require sorting:
Declare an array of 5 integers: int[] largest = new int[5];
Put the first 5 elements in the ArrayList into largest.
Starting with the 6th element, look at each element N in the ArrayList, and if N is larger than any element in largest, throw out the smallest number currently in largest and replace it with N.
If you need to exclude duplicates, the algorithm can be modified easily (just skip over any ArrayList element that's already in largest).
Why not use Collections.sort(List list) or Arrays.Sort(arr). This will save much of effort. Or is it part of your task?
Assuming your collection is sorted, and you want the last 5 elements, try this out:
for (int i = sortedNums.size() - 5; i < sortedNums.size(); ++i) {
System.err.println(sortedNums.get(i));
}
How I would go about doing this:
Create a temporary ArrayList, as a copy of the initial one.
After each largest element is found, remove it from the temporary ArrayList and add it to your 5 largest numbers
Repeat until complete
edit* This does not require your elements to be sorted, and has a fairly poor efficiency as a result
I assume you do not have the liberty to use sort and suchlike, considering this is a homework. So here is outline of an algorithm that you can try to implement
create an array of five integers (we will keep this sorted)
for each element in the list
find the index of the element in the array that it is greater than
if no such element exists in the array (i.e. it is smaller than all elements in the array)
continue on to the next element in the list
else
push all elements in the array to one index below, letting them fall off the
edge if need be (e.g. if the number in list is 42 and the array has
45 and 40 at index 3 and 2 respectively then
move arr[1] to arr[0], and arr[2] (40) to arr[1] and set arr[2] = 42)
end if
end for
At the end the array will have the five elements
I will leave one question for you to answer (it is important): what should you set the array to initially?
You only need two lines of code:
Collections.sort(nums1);
List<Integer> high5 = nums1.subList(nums1.size() - 5, nums1.size());
If you must "do it yourself", the simplest way to sort is a bubble sort:
iterate over the list
swap adjacent numbers if they are in the wrong order
repeat n times
Not efficient but very easy to code.