Method doesn't work - java

For my assignment, I have to use methods to find the number of patterns in an array. The pattern is counted when the sum of adjacent numbers in an array is more than 7.
I have to use 2 methods, 1 being insertNumbers to create an array and another being computePattern to count the patterns.
However, the pattern printed out doesn't match the array printed out. Here is the code.
As this is an assignment, I would rather not get answers but answers on which part of my code is wrong, and how do I fix it.
EDIT: Here is a sample output.
Sample output #1: Array: 2 7 2 3 1 5 7 4 3 6
Number of patterns: 3
public static int[] insertNumbers()
{
//Declaring the array.
int randomArray[] = new int[10];
//Setting random numbers into the array.
for (int k = 0;k < randomArray.length;k++)
{
int i = (int)((Math.random()*9)+1);
randomArray[k] = i;
}
//Returning array into other methods.
return randomArray;
}
public static int computePattern()
{
int a = 0;
int b = 1;
int pattern = 0;
int[] randomArray = insertNumbers();
//Computing the number of patterns.
for (;a<=8 && b<=9;)
{
if (randomArray[a] + randomArray[b]>7)
{
pattern++;
}
a+=2;
b+=2;
}
return pattern;
}
public static void main(String[] args)
{
int pattern = computePattern();
int[] randomArray = insertNumbers();
//Printing out the contents of the array.
System.out.print("Array : " );
for(int i = 0; i < 10; i++)
{
System.out.print(+randomArray[i] +" ");
}
System.out.println(" ");
//Printing out the number of patterns.
System.out.println("Number of patterns: "+pattern);
}

You are computing pattern for a different array, and in main you are printing different array (you are calling insertNumbers twice basically). See here:
int pattern = computePattern(); // First time computePatter generates one array
int[] randomArray = insertNumbers(); // Another array is generated here
Also, doesn't seem your pattern counting is correct. Hint: does it compare elements with indexes 1 and 2?

Remove this line from your main function
int[] randomArray = insertNumbers();
You are calling the function insertNumbers again after computing the pattern.

You should do the compute pattern part this way
{
int a;
int pattern = 0;
int[] randomArray = insertNumbers();
//Computing the number of patterns.
for (a=1;a<9;a++)
{
if (randomArray[a] + randomArray[a-1]>7)
{
pattern++;
}
}
return pattern;
}
And you definitely calling insertNumbers Twice. You should call it once in main and send that array to computePattern.
int[] randomArray = insertNumbers();
int pattern = computePattern(randomArray);

Related

How to find all possible numbers with a Recursion method

i want to write a Recursion method that prints all possible arrangements for these
numbers , the integers 1 to 9
arranged randomly in a grid of three rows and three column.for example :
6 2 1
5 4 7
3 9 8
sorry i don't have any code , because it's very hard to me.
public class Test {
public static void main (String[] args){
String x = "123456789";
System.out.println(test(x,0));
}
public static String test(String x , int y){
if(x.length()==1)return "";
return x.charAt(y)+test(x.substring(y),y);
}
There are many ways to implement something like this, this is one example. I will use int[] instead of String for convenience sake:
public static void main(String[] args) {
nextPermutation(new int[9], 0, new boolean[9]);
}
public static void nextPermutation(int[] perm, int index, boolean[] alreadyUsed) {
if(index == perm.length) {
//the permutation is complete
//you can store it or print it
} else {
for(int i = 0 ; i < alreadyUsed.length ; i++) {
if(alreadyUsed[i]) continue;
perm[index] = i+1;
boolean[] newAlreadyUsed = Arrays.copyOf(alreadyUsed, alreadyUsed.length);
newAlreadyUsed[i] = true;
nextPermutation(Arrays.copyOf(perm, perm.length), index+1, Arrays.copyOf(newAlreadyUsed, newAlreadyUsed.length));
}
}
}
This will generate all possible combinations of 1-9. The idea of the algorithm is that you keep track of which digits you already used, run through a loop and select all available digits.
Note that it's important to pass copies of perm and alreadyUsed, otherwise you will just pass the same array and overwrite previous permutations.
pass values ​​to an array, randomize and create a loop to generate the matrix.
loop: make a generic loop starting to generate matrix with i0 , j0 like position i1 , j1 of matrixand add the values of array
int j = 0;
for( int i = 0; i <= YOURARRAY.length(); i++)
{
System.out.println( i POSITIONOFARRAY );
j+1
}

How to add to array without ArrayIndexOutOfBoundsException?

Can anyone answer this question?
public class AddingArray {
public static void main(String[] args){
int arry1[] = {2,3,4,5,6,7,9};
int arry2[] = {4,3,7,9,3,5};
for(int i = 0; i <arry1.length; i++){
int result = arry1[i] + arry2[i];
System.out.println("Result "+result);
}
}
}
Whenever I try executing the above code I get the error Exception in
thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at
basics.AddingArray.main(AddingArray.java:9)
But,my output should be like this 6,6,11,14,9,12,9
As people have mentioned, one of yours arrays is literally shorter than the other. Take two blocks and overlay them over only one block. The second (in this case index 1 block) would fall into the abyss, because the block that was supposed to catch it never existed.
I would make sure both of them are of the same size. If you do want to leave em as they are, I would do this:
int result = 0;
try
{
for(int i = 0, length = array2.length; i < length; i++)
{
result = array1[i] + array2[i];
System.out.println("Result is: " + result);
}
catch(Exception e)
{
System.out.println("You tried to do something that resulted in an error");
System.out.println("Your previous result was: " + result);
}
}
SO, assuming that I still recall how to do basic arrays, what this code will do is that it will catch any errors thrown by your code.
Let's make this as simple and understandable as possible, with no fancy annotations:
You have two int arrays, of not equal lengths, and you wish to add the index-paired numbers to an array of the sums. However, if one of the arrays does not have any more numbers, the value of the longest array will be the result.
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
You need to determine the length of the longest array. You can do this with a Math.max()-method, where you give the length of each array as parameters:
int biggestArrayLength = Math.max(arry1.length, arry2.length);
Then, instead of for(int i=0;i<arry1.length;i++){, you write:
for(int i=0;i<biggestArrayLength;i++){
Now it doesn't matter which of the two arrays is the biggest one.
Inside the loop, I would define two ints, representing a value from each of the two arrays:
int value1 = arry1[i];
int value2 = arry2[i];
however, this will give an error when the smallest array does not have any more elements. We need to check if the array actually has an element with index i. index numbers in arrays start with 0. so if the length is 7, the 7 elements will have index numbers from 0-6. In other words, only index numbers that are lower (and not equal) to length, is valid numbers:
int value1 = 0;
int value2 = 0;
if(arry1.length > i){
value1 = arry1[i];
}
if(arry2.length > i){
value2 = arry2[i];
}
int result = value1 + value2;
System.out.println("Result "+result);
}
}
}
Now, if you need to put these in a third array, say named sumArray, this would be the complete code:
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
int biggestArrayLength = Math.max(arry1.length, arry2.length);
int[] sumArray = new int[biggestArrayLength];
for(int i=0;i<biggestArrayLength;i++){
int value1 = 0;
int value2 = 0;
if(arry1.length > i){
value1 = arry1[i];
}
if(arry2.length > i){
value2 = arry2[i];
}
int result = value1 + value2;
sumArray[i] = result;
System.out.println("Result "+result);
}
}
}
It is because your loop will go from 0 to 6 (which is the array1.length - 1) and your array2 only has 6 elements (so from 0 to 5).
So when you are accessing arry2[6]; It will give you the java.lang.ArrayIndexOutOfBoundsException.
You could change your for loop to go to the length of the smallest array:
for(int i = 0; i < arry2.length; i++){ /*Do what you want */ }
Or add an element in array2, but that is yours to decide since I do not know your requirements.
Because arry1 is longer than arry2 when you make the last iteration through the loop arry2[i] returns null because there is no element to return.
either do:
if(arry2[i] != null) {
//run your adding code
}
or change your arrays to be the same size
Edit: The reason it is not working properly is because you are using the length of the largest array as the conditional within the for loop. This condition allows you to attempt to access the 2nd array at a location that does not exist, which is why you are getting an ArrayIndexOutOfBoundsException.
Can we stop the downvoting?
End edit----
If you want to add up all of the elements in the array use this code.
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
int result = 0;
for(int i=0;i<arry1.length;i++){
result+=arry1[i];
}
for(int j=0; j < array2.length; j++){
result += array2[j];
}
System.out.println("Result: "+ result);
}
}
if you are trying to sum individual elements as you loop you can do the following. This will properly handle 2 arrays of different length regardless of which one is longer.
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
int result = 0;
for(int i=0;i<arry1.length;i++){
result=arry1[i];
if(i < array2.length){
result += array2[i];
}
System.out.println("Result: "+ result);
}
for(int j = i; j < array2.length; j++){
System.out.println("Result: "+ array2[j]);
}
}
}

How to check the object of type int[] of an arraylist?

I'm trying to find out particular elements in my ArrayList (arrayOne). Each element should be an int[]. I've tried System.out.println(arrayOne), which compiles but gives a irregular and strange number "[[I#370968]".
I've also tried System.out.println(arrayOne[0]) but it won't compile and emits the error
Array required but java.util.ArrayList found.
Given is the following code, with {1,12,3,13,123,2} passed to eg:
import java.util.ArrayList;
public class arrayTest {
private ArrayList<int[]> arrayOne;
public arrayTest(int[] eg) {
int[] xy = new int[2];
arrayOne = new ArrayList<int[]>(eg.length);
for (int i = 0; i < eg.length; i++) {
int sv = String.valueOf(eg[i]).length();
if (sv == 1) {
xy[0] = 0;
xy[1] = eg[i];
arrayOne.add(xy);
}
else if (sv == 2) {
System.out.println("two digits");
// TODO add code to make xy[0] = the first
// digit of eg and xy[1] = the second digit
}
else {
System.out.println("too many digits");
// and throw error accordingly
}
System.out.println(arrayOne);
}
}
}
How do make sure and print out the int array at arrayOne[0]
Given the code above if (sv == 2) and i want to split each individual number into an int[] with [0] being the first digit and [1] being the second digit how would i get the int value of each individual digit.
Use Arrays.toString(yourArray); to print out arrays in human readable form.
First of all, the string [I#370968 is displayed because you are trying to print an int[], which is actually an object. Because this object does not override the object's toString() method, that method is derived from the Object class. The Object.toString() implementation, which prints the class name (in this case [I, because it is an int array), then an # sign, and then the hash code of the object.
Your ArrayList contains a number of int[]s. Because an ArrayList is not an array (the one with the square brackets, like int[]), you can't call an element on it as if it were an array. In short, you cannot call arrayOne[someDesiredIndex].
In order to get an element from the ArrayList, call get(int index) on it; it returns the desired int[]. As already pointed out by another answer, you can use Arrays.toString(int[]) to print it in a human readable form.
To answer your questions:
You can retrieve the first index (0) of the first array inside arrayOne with the following code: arrayOne.get(0)[0].
The following code should work:
private static int[] intToArray(int n) {
String str = String.valueOf(n);
int length = str.length();
int[] ints = new int[length];
for (int i = 0; i < length; i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
return ints;
}
Above method puts each digit into the next array position (it also works with digits greater than 99). With this method you can easily get each individual digit:
int[] digits = intToArray(47);
int a = digits[0]; // Will be 4
int b = digits[1]; // Will be 7
So this is the class rewritten:
public class Rewrite {
private ArrayList<int[]> arrayOne = new ArrayList<int[]>();
public Rewrite(int[] eg) {
for (int i = 0; i < eg.length; i++) {
int length = String.valueOf(eg[i]).length();
switch (length) {
case 1:
this.arrayOne.add(new int[] { 0, eg[i] });
break;
case 2:
this.arrayOne.add(intToArray(eg[i]));
break;
default:
throw new IllegalArgumentException("Number " + eg[i] + " has too many digits");
// Or display the error or something.
}
System.out.println(Arrays.toString(this.arrayOne.get(i)));
}
}
private static int[] intToArray(int n) {
String str = String.valueOf(n);
int length = str.length();
int[] ints = new int[length];
for (int i = 0; i < length; i++) {
ints[i] = Integer.parseInt(str.substring(i, i + 1));
}
return ints;
}
public static void main(String[] args) {
Rewrite r = new Rewrite(new int[] { 47, 53, 91, 8 });
}

Creating multiple nested loops to generate two numbers that move through the length of a Array

As the title reads, I have been thinking about creating multiple nested loops that aim to achieve one purpose. Move two generated random numbers between 0-9 through each possible possition of an array.
For example, App generates first number (fNum) 1 and second number (sNum) 6. It then moves these numbers in the array which containts ABC. However firstNum and secondNum will need to also try all the possible combinations, so each one will need to be different with each loop.
-1ABC6
-A1BC6
-AB1C6
-ABC16
-ABC61
-AB6C1
-A6BC1
-6ABC1
-A6B1C
-A61BC
-A16BC
-A1B6C
-A1BC6
and so on...
I beleive the best way will be to create a method for generating a counter, which increments the numbers which I can call.
private int getNextNumber(int num) {
if (num == 0) {
return num;
} else {
num++;
}
if (num < 10) {
return num;
} else {
return -1;
}
}
Then I will need multiple nested loops... I have decided to go for several loops which will go infinitly.
while (j < maxlen) {
//J = 0 and maxlen = length of text so in this case 3 as it is ABC
//Add two numbers and check against answer
while (fNum != -1 || sNum != -1) {
//incrememnt numbers
fNum = getNextNumber(fNum);
System.out.println(fNum);
sNum = getNextNumber(sNum);
System.out.println(fNum);
}
String textIni = "ABC";
int lenOfText = textIni.length();
char[] split = textIni.toCharArray();
for (int i = 0; i < lenOfText; i++) {
//here it will look at the length of the Text and
//try the possible positions it could be at....
//maybe wiser to do a longer loop but I am not too sure
}
}
Since you don't need to store all possible combinations, we will save some memory using only O(n) storage with an iterative solution. I propose you a basic implementation but don't expect to use it on large arrays since it has a O(n³) complexity.
public static void generateCombinationsIterative(List<Integer> original, int fnum, int snum) {
int size = original.size();
for (int i=0 ; i<=size ; i++) {
List<Integer> tmp = new ArrayList<>(original);
tmp.add(i,fnum);
for (int j=0 ; j<=size + 1 ; j++) {
tmp.add(j,snum);
System.out.print(tmp + (i == size && j == size + 1 ? "" : ", "));
tmp.remove(j);
}
}
}
For your culture, here is an example of a recursive solution, which takes a lot of memory so don't use it if you don't need to generate the lists of results. Nevertheless, this is a more general solution that can deal with any number of elements to insert.
public static List<List<Integer>> generateCombinations(List<Integer> original, Deque<Integer> toAdd) {
if (toAdd.isEmpty()) {
List<List<Integer>> res = new ArrayList<>();
res.add(original);
return res;
}
int element = toAdd.pop();
List<List<Integer>> res = new LinkedList<>();
for (int i=0 ; i<=original.size() ; i++)
// you must make a copy of toAdd, otherwise each recursive call will perform
// a pop() on it and the result will be wrong
res.addAll(generateCombinations(insertAt(original,element,i),new LinkedList<>(toAdd)));
return res;
}
// a helper function for a clear code
public static List<Integer> insertAt(List<Integer> input, int element, int index) {
List<Integer> result = new ArrayList<>(input);
result.add(index,element);
return result;
}
Note that I did not use any array in order to benefit from dynamic data structures, however you can call the methods like this :
int[] arr = { 1,2,3 };
int fnum = 4, snum = 5;
generateCombinationsIterative(Arrays.asList(arr),fnum,snum);
generateCombinations(Arrays.asList(arr),new LinkedList<>(Arrays.asList(fnum,snum));
Note that both methods generate the combinations in the same order.

Count how many times an element occurs in an array - Java

I recently made a very simple practice program in Python, that takes user input and rolls dice. The code is:
import random
import sys
import math
def roll(rolls, sides, results):
for rolls in range(1, rolls + 1):
result = random.randrange(1, sides + 1)
print result
results.append(result)
def countf(rolls, sides, results):
i = 1
print "There were", rolls, "rolls."
for sides in range(1, sides + 1):
if results.count(i) != 1:
print "There were", results.count(i), i,"s."
else:
print "There was", results.count(i), i
i = i + 1
if i == sides:
break
rolls = input("How many rolls? ")
sides = input("How many sides of the die? ")
results = []
roll(rolls, sides, results)
countf(rolls, sides, results)
(actually this is part of a larger program, so I had to cut'n'paste bits, and I might have missed something out).
And so I decided to translate that to Java. Notice the algorithm here: get random number, print it, append it to an array, then count the amount of each number in the array at the end, and print out that value. Problem is, I don't know how to do the equivalent of someArray.count(someIndex) in Java syntax. So my Java program looks like this so far:
import java.util.*;
public class Dice {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random();
int[] results = new int[TIMES_TO_ROLL];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt(6);
System.out.println(result);
results[i] = result;
}
}
public static int getInt(String prompt) {
System.out.print(prompt + " ");
int integer = input.nextInt();
input.nextLine();
return integer;
}
}
So can someone help me with the array counting code? I understand that this might not be a defined method, since Python is higher level after all, so I could make my own array counting method, but I was wondering if Java, like Python, has a predefined one.
EDIT: I managed something like this:
public static int arrayCount(int[] array, int item) {
int amt = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == item) {
amt++;
}
else {
amt = amt;
}
}
return amt;
}
EDIT: Just out of interest, assuming I use Command prompt to run my Java program and Python.exe (command prompt console for Python), which one will be faster (in other words, for the same code, which language has better performance?)?
You could use a HashMap to store the result.
If the new number is not in your map you add it with "1" as initial value.
If it exists your put "+1" to the current map value.
To display the values you just have to iterate on you entries in a for each loop.
The solution is to transform your array to a List and then use the Collections.frequency method:
List<Integer> resultList = Arrays.asList(results);
int freq = Collections.frequency(resultList, 4);
Also you could use ArrayList from the very beginning saving you the transformation:
List<Integer> result = new ArrayList<Integer>();
// add results
int freq = Collections.frequency(result, 4);
See the Collections documentation here
EDIT: If performance is an issue (as suggested in the comments) then maybe you want to use each index of the array as a counter, as follows:
Random flip = new Random(SIDES);
int[] counters = new int[SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
counters[result] = counters[result]+1;
}
Notice that you no longer need to count at the end since you've already got all the counters in the array and there is no overhead of calculating the hash.
There are a couple libraries that will do this for you:
Google Guava's MultiSet
Apache Common's Bag
But for something so simple, you may consider an extra library a bit excessive.
You can also do this yourself with an int[]. Assuming your dice is using whole numbers, have the number rolled refer to the index into the array, and then increment the value at that index. When you need to retrieve the value for a given number, look up its value by the index.
private static final int NUMBER_DICE_SIDES = 6;
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random(NUMBER_DICE_SIDES);
int[] results = new int[NUMBER_DICE_SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
System.out.println(result);
results[result]++;
}
for(int i = 0; i < NUMBER_DICE_SIDES; ++i) {
System.out.println((i+1)+"'s: " + arraysCount(results, i));
}
}
public static int arrayCount(int[] array, int item) {
return array[item];
}
There's a frequency method in collections
int occurrences = Collections.frequency(listObject, searchItem);
Java doc for collections
As far as I am aware, there is no defined method to return the frequency of a particular element in an array. If you were to write a custom method, it would simply be a matter of iterating through the array, checking each value, and if the value matches the element you're after, incrementing a counter.
So something like:
// in this example, we assume myArray is an array of ints
private int count( int[] myArray, int targetValue) {
int counter = 0;
for (int i = 0 ; i < myArray.length; i++ ) {
if (myArray[i] == targetValue) {
counter++;
}
}
return counter;
}
Of course, if you want to find the frequency of all the unique values in your array, this has the potential of being extremely inefficient.
Also, why are you using a 7-sided die? The Random nextInt() will return a number from 0 up to but not including the max. So your die will return values from 0 through 6. For a six-sided die, you'd want a new Random(6); and then increment your roll by one to get a value from one through six: flip.nextInt() +1;.
class FindOccurrence {
public static void main (String[]args) {
int myArray[] = {5, 8, 5, 12, 19, 5, 6, 7, 100, 5, 45, 6, 5, 5, 5};
int numToFind = 5;
int numberOfOccurrence = 0;
for (int i=0; i < myArray.length; i++) {
if (numToFind == myArray[i]) {
numberOfOccurrence++;
}
}
System.out.println("Our number: " + numToFind);
System.out.println("Number of times it appears: " + numberOfOccurrence);
}
}

Categories