I am trying to develop a program to delete all the median values from an array (the middle value if it has an odd number of elements, the two middle values if it has an even number of elements) until there are only two elements left, elements [0] and [1]. For example, if the user inputs 1, 2, 3, 4, 5, the program will return [1, 5]. I put down what I thought logically might help, but my array x isn't copying myArray in the for loops. I am not looking for someone to completely do the code for me, just to point out where I am wrong. Here is my code:
import java.util.*;
public class Deletion
{
public static void main(String[]args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the array length:");
int [] myArray = new int[kb.nextInt()];
int [] x = new int[myArray.length - 1];
int index1 = 0;
int index2 = 0;
int index3 = 0;
if(myArray.length < 3)
{
System.out.println("Please make sure array length is greater than two. Run again.");
System.exit(0);
}
else
{
for(int i = 0; i < myArray.length; i++)
{
System.out.println("Please enter a number for position " + i + ":");
myArray[i] = kb.nextInt();
}
for(int i = 0; i < myArray.length; i++)
{
while(myArray.length > 2)
{
if(myArray.length%2 != 0)
{
index1 = (myArray.length/2);
for(int j = 0, r = 0; j < myArray.length; j++)
{
if(j != index1)
{
x[r++] = myArray[j];
myArray = x;
}
}
x = new int[myArray.length - 1];
}
else
{
index2 = (myArray.length/2);
index3 = (myArray.length/2 - 1);
for(int j = 0, r = 0; j < myArray.length; j++)
{
if(j != index2 && j != index3)
{
x[r++] = myArray[j];
myArray = x;
}
}
x = new int[myArray.length - 1];
}
}
}
}
System.out.println(Arrays.toString(myArray));
}
}
You must create the array and populate it, else it's using the same memory address, hence won't work. Use the following:
myArray = ArrayUtils.clone(x);
When you are doing do “myArray = x”, your are actually merely assigning a reference to the array. Hence, if you make any change to one array, it would be reflected in other arrays as well because both myArray and x are referring to the same location in memory.
Thus, what you need is
myArray = x.clone();
I cleaned up your code a bit. According to what you described, what really matters is pulling in the minimum and maximum values in the array - everything else will be deleted, so you simply need a single traversal through the array to find those two values.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean isValid = false;
int validLength = 0;
System.out.println("Please enter the array length:");
while (!isValid) {
int length = scanner.nextInt();
if (length < 3) {
System.out.println("Please make sure array length is greater than two. Try again.");
}
else {
isValid = true;
validLength = length;
}
}
int minimumValue = Integer.MAX_VALUE, maximumValue = Integer.MIN_VALUE;
for (int i = 0; i < validLength; i++) {
System.out.println("Please enter a number for position " + i + ":");
int nextInt = scanner.nextInt();
if (nextInt < minimumValue) minimumValue = nextInt;
else if (nextInt > maximumValue) maximumValue = nextInt;
}
System.out.println(Arrays.toString(new int[] {minimumValue, maximumValue}));
}
Edit: made another revision as using an array is unnecessary. Just keep track of the minimum and maximum values as they are being entered.
Related
I am trying to create a random array without duplicates.
The assignment is to take an integer array and maximum value from user, fills the array with random numbers between 0 and maximum value, and display random array without duplicates, WITHOUT using any other classes except random and scanner.
This is a sample output:
Please enter the size of the array: 10
Please enter the maximum value: 50
[39,2,17,49,12,19,40,31,42,15]
I need help in removing the duplicates. I am not sure if what I am doing is correct, I am a bit of a beginner but here is what I have so far. Help would be greatly appreciated. Thanks.
public class Fill {
private static int size;
private static int maxVal;
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
// Ask user to enter the size of the array
System.out.print("Please enter the size of the array: ");
size = kb.nextInt();
// Ask user to enter the maximum value allowed
System.out.print("Please enter the maximum value: ");
maxVal = kb.nextInt();
// Call fill() method
int arr[] = fill(size, maxVal);
// Print filled array
System.out.print("[");
for (int i = 0; i < arr.length - 1; i++)
System.out.print(arr[i] + ",");
System.out.print(arr[arr.length - 1] + "]");
}
public static int[] fill(int size, int maxVal) {
int arr[] = new int[size];
Random random = new Random();
// Fills the array with random numbers between 0 and maximum value
if (size <= 0 || maxVal < size - 1) {
System.out.print("Incorrect Parameters. Please Retry");
main(null);
} else {
for (int j = 0; j < size; j++) {
arr[j] = random.nextInt(maxVal);
// Check array for duplicates
for (int k = j + 1; k < size; k++) {
if(arr[j] == arr[k]) {
//create new random array
fill(size, maxVal);
}
}
}
}
return arr;
}
}
I have edited and fixed some issues in your code as below:
public class Fill {
private static int size;
private static int maxVal;
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
// Ask user to enter the size of the array
System.out.print("Please enter the size of the array: ");
size = kb.nextInt();
// Ask user to enter the maximum value allowed
System.out.print("Please enter the maximum value: ");
maxVal = kb.nextInt();
// Call fill() method
int arr[] = fill(size, maxVal);
// Print filled array
System.out.print("[");
for (int i = 0; i < arr.length - 1; i++)
System.out.print(arr[i] + ",");
System.out.print(arr[arr.length - 1] + "]");
}
public static int[] fill(int size, int maxVal) {
int arr[] = new int[size];
Random random = new Random();
// Fills the array with random numbers between 0 and maximum value
if (size <= 0 || maxVal < size ) {
System.out.print("Incorrect Parameters. Please Retry");
main(null);
} else {
for (int j = 0; j < size; j++) {
int newNumber = random.nextInt(maxVal + 1);
// Check array for duplicates
while(alreadyExist(newNumber, arr)){
newNumber = random.nextInt(maxVal + 1);
}
arr[j] = newNumber;
}
}
return arr;
}
static boolean alreadyExist(int a, int[] arr){
for(int i = 0 ; i < arr.length ; i++){
if(arr[i] == a) return true;
}
return false;
}
}
Now it does not return any repetitive value.
I am new to Java Programming (or programming infact).
I have an array which contains either 4 or 6 only. Given a number, either 4 or 6, find the highest sequential occurrence of the given number.
I need highest sequential occurrence count
Example: arr[{4,4,6,6,4,4,4,4,4,6}]
If the above array is given, and next input number is 4, the output should be 5. Because the number 4 has occurred sequentially 5 times.
public static void main(String[] args) throws IOException {
String arrayTK = br.readLine(); // Input is 4466444446
int[] inpArray = new int[10];
for (int i = 0; i < 10; i++) {
inpArray[i] = arrayTK.charAt(i) - '0';
}
int maxSequenceTimes = 0;
for (int j = 0; j < 10; j++) {
// Logic
}}
Any help would be greatly appreciated.
Edit
We will separate and count all sequences and then search in each sequence to know which sequence contain the biggest length.
int[] arr = {4,4,6,6,4,4,4,4,4,6};
boolean newSeq = false;
int diffrentSeq = 0;
int currentNumber;
//Get sequence numbers
for (int i = 0; i < arr.length; i++) {
currentNumber = arr[i];
if (i >= 1 && currentNumber != arr[i - 1])
newSeq = true;
else if (i == 0)
newSeq = true;
//It's new sequence!!
if (newSeq) {
diffrentSeq++;
newSeq = false;
}
}
System.out.println(diffrentSeq);
int[] maxSequencSize = new int[diffrentSeq];
int lastIndex = 0;
for (int i = 0; i < maxSequencSize.length; i++) {
int currentNum = arr[lastIndex];
for (int j = lastIndex; j < arr.length; j++) {
if (arr[j] == currentNum) {
maxSequencSize[i]++;
lastIndex = j + 1;
} else break;
}
}
System.out.println(max(maxSequencSize));
You need to get max value which act the max sequence length:
private static int max(int[] array){
int maxVal = 0;
for (int anArray : array) {
if (anArray > maxVal)
maxVal = anArray;
}
return maxVal;
}
String arrayTK = br.readLine(); // Input is 4466444446
Because your first input is a string, you don't need to convert it to an int array and if you are using you can use:
String arrayTK = "4466444446";
int result = Arrays.asList(arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2").split(";"))
.stream().max(Comparator.comparingInt(String::length)).get().length();
System.out.println(result);
Explanation :
arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2") put a separator between each two different numbers the result should be 44;66;44444;6
.split(";") split with this separator (i used ; in this case) the result is ["44", "66", "44444", "6"]
stream().max(Comparator.comparingInt(String::length)).get() get the max input
.length() to return the length of the result
Ideone demo
Edit
How I modify the same, to get count to any specific number. I mean, max sequential occurrence of number 4
In this case you can just add a filter .filter(t -> t.matches(number + "+")) which mean get only the numbers which match 4+ where 4 can be any number :
...
int number = 6;
int result = Arrays.asList(arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2").split(";"))
.stream()
.filter(t -> t.matches(number + "+"))
.max(Comparator.comparingInt(String::length)).get().length();
You need something like this:
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner br =new Scanner(System.in);
String str = br.next();
int arr[]=new int[str.length()];
for(int i=0;i<str.length();i++)
{
arr[i]=str.charAt(i)-'0';
//System.out.println(arr[i]);
}
int j=0;
int count=1,max=0;
for(int i=0;i<str.length();i++)
{
if(i==0){
j=arr[i];
}
else
{
if(arr[i]==j)
{
count++;
//System.out.println(" "+count);
}
else
{
if(max<count){
max=count;
}
count=1;
j=arr[i];
}
}
}
if(max<count){
max=count;
}
System.out.println(max);
}
}
That should do the work. Every time you find the matching value you start counting and when the streak is over you compare the length with the maximum length you have found so far.
public int logic(int[] inpArray, int num) {
int count = 0, max = 0
for(int i = 0; i < 10; ++i){
if(inpArray[i] == num) {
count++
else{
if(count > max)
max = count;
count = 0;
}
}
if (count > max)
max = count;
return max;
}
How do I save it actually in the Array?
With this code it doesn't save anything in the array
I hope you can tell me more ways how to do it and explain in detail, thank you very much
import java.util.Scanner;
public class CountArray
{
public static void main(String[] arg)
{
Scanner scan = new Scanner(System.in);
int countPOZ = 0;
int countP5 = 0;
int countNONE = 0;
System.out.println();
System.out.print("Type elements: ");
int[] x = new int [scan.nextInt()];
for(int i = 0; i < x.length; i++)
{
System.out.print("Type numbers: ");
int numrat = scan.nextInt();
if(numrat > 0)
countPOZ++;
else if (numrat % 5 == 0)
countP5++;
else
countNONE++;
}
System.out.println();
System.out.println(x[1]); //here it will display 0 because nothing is saved.. in the array
System.out.println("Positive: "+countPOZ);
System.out.println("Div.. with 5: "+countP5);
System.out.println("Others: "+countNONE);
}
}
You store a value in the ith position of your x array with:
x[i] = someValue;
In the context of your loop :
for(int i = 0; i < x.length; i++)
{
System.out.print("Type numbers: ");
int numrat = scan.nextInt();
if(numrat > 0)
countPOZ++;
else if (numrat % 5 == 0)
countP5++;
else
countNONE++;
x[i] = numrat;
}
This stores the user's input in order.
x[i] = scan.nextInt();
Remove the local numrat and use x[i]. And please use braces, something like
x[i] = scan.nextInt();
if(x[i] > 0) {
countPOZ++;
} else if (x[i] % 5 == 0) {
countP5++;
} else {
countNONE++;
}
This is covered in and an example to JLS-10.4 - Array Access.
A component of an array is accessed by an array access expression (§15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i].
All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.
class Gauss {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++) ia[i] = i;
int sum = 0;
for (int e : ia) sum += e;
System.out.println(sum);
}
}
Try, add values in array then use array for business logic.
int[] x = new int [scan.nextInt()];
for(int i = 0; i < x.length; i++){
System.out.print("Type numbers: ");
x[i] = scan.nextInt();
if(x[i] > 0)
countPOZ++;
else if (x[i] % 5 == 0)
countP5++;
else
countNONE++;
}
But you missing something int[] x = new int [scan.nextInt()] as per your code you are not passing only one element and add that element to your array.
I assist pass multiple elements as comma separated list 1,2,3,4,5,6,7 then in your code you can create array list int x[] = scan.nextInt().split(",") then use it.
in your code
int[] x = new int [scan.nextInt()];
you are defining the size of an array. you are not storing any elements in here.
So define any elements in an array you have to access it's index and store your value in that specific index
x[1] = scan.nextInt()
can store the values in specific index
I had to write a program that find the largest element in an array. The user is prompted to enter the number of rows and columns, then prompted to enter the numbers in the rows and columns.
This array is then passed to a method where each number in every column of every row is compared and when the largest number is found the location is then moved to a field which, hopefully, return from the method.
It is not working. Here is my code.. I am sure that it is something silly, but what I can't figure it out. I think that it might have to with the 'a' in calling the method.
I define 'a' with double[][] a = new double[r][c];
I call and pass to the method with int[] find = locateLargest(a);
I tried to use all 3 of these as the return statement:
// return largest;
return largest[indxrow][indxcol];
// return [indxrow][indxcol];
How can I fix my code?
void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Enter the number of rows and columns of the array");
int r = input.nextInt();
int c = input.nextInt();
double[][] rowCol = new double[r][c];
double[][] a = new double[r][c];
System.out.println("Enter the array");
for (int rows = 0; rows < rowCol.length; rows++) {
for (int cols = 0; cols < rowCol[rows].length; cols++) {
rowCol[rows][cols] = input.nextDouble();
a[rows][cols] = rowCol[rows][cols];
int[] find = locateLargest(a);
}
}
System.out.println("The location of the largest element is at (" + a[0] + ", " + a[1] + ")");
}
public static int[] locateLargest(double[][] a) {
double largest = 0;
int indxrow;
int indxcol;
for (int lcol = 0; lcol < a[0].length; lcol++ ) {
largest = a[0][lcol];
indxcol = lcol;
}
for (int lrow = 1; lrow < a.length; lrow++) {
for (int lcol = 0; lcol < a[lrow].length; lcol++)
if (a[lrow][lcol] > largest) {
largest = a[lrow][lcol];
indxrow = lrow;
}
}
// return largest;
return largest[indxrow][indxcol];
//return [indxrow][indxcol];
}
}
You are trying to return a double, when the actual return type of the method is an int[]
from how your code looks, it seems that you mean to return the largest number in the array.. In that case you should return a double, since your array you pass in is a double[][]
public static double locateLargest(double[][] a) {
double largest = 0;
for (int lcol = 0; lcol < a[0].length; lcol++) {
largest = a[0][lcol];
}
for (int lrow = 1; lrow < a.length; lrow++) {
for (int lcol = 0; lcol < a[lrow].length; lcol++)
if (a[lrow][lcol] > largest) {
largest = a[lrow][lcol];
}
}
return largest;
}
In order to return an int[] (as you specified in public static int[] locateLargest(double[][] a)) in your method, you should use
return a[lrow];
because a is an int[][], so a[a_certain_position] will be an int[], i.e. what you are looking for.
EDIT:
This assuming that a was an int[][], but I noticed you defined it as a double[][]. Keep in mind (int[])a[lrow] cast is not possible in Java, so I would suggest you to change your method to return a double[] instead, like this:
public static double[] locateLargest(double[][] a)
I have to create a program that takes an array of both even and odd numbers and puts all the even numbers into one array and all the odd numbers into another. I used a for loop to cycle through all the numbers and determine if they are even or odd, but the problem I'm having is that since the numbers in the original array are random, I don't know the size of either the even or the odd array and therefore can't figure out how to assign numbers in the original array to the even/odd arrays without having a bunch of spots left over, or not having enough spots for all the numbers. Any ideas?
Try using an ArrayList. You can use
num % 2 == 0
to see if num is even or odd. If it does == 0 then it is even, else it is odd.
List<Integer> odds = new ArrayList();
List<Integer> evens = new ArrayList();
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evens.add(array[i]);
}
else {
odds.add(array[i]);
}
}
to convert the ArrayLists back to arrays you can do
int[] evn = evens.toArray(new Integer[evens.size()]);
(Note: untested code so there could be a few typos)
EDIT:
If you are not allowed to use ArrayLists then consider the following that just uses Arrays. It's not as efficient as it has to do two passes of the original array
int oddSize = 0;
int evenSize = 0;
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evenSize++;
}
else {
oddSize++;
}
}
Integer[] oddArray = new Integer[oddSize];
Integer[] evenArray = new Integer[evenSize];
int evenIdx = 0;
int oddIdx = 0;
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evenArray[evenIdx++] = array[i];
}
else {
oddArray[oddIdx++] = array[i];
}
}
You can do it without using arrays or any '%' Just a simple idea
input = new Scanner(System.in);
int x;
int y = 0; // Setting Y for 0 so when you add 2 to it always gives even
// numbers
int i = 1; // Setting X for 1 so when you add 2 to it always gives odd
// numbers
// So for example 0+2=2 / 2+2=4 / 4+2=6 etc..
System.out.print("Please input a number: ");
x = input.nextInt();
for (;;) { // infinite loop so it keeps on adding 2 until the number you
// input is = to one of y or i
if (x == y) {
System.out.print("The number is even ");
System.exit(0);
}
if (x == i) {
System.out.print("The number is odd ");
System.exit(0);
}
if (x < 0) {
System.out.print("Invald value");
System.exit(0);
}
y = y + 2;
i = i + 2;
}
}
Use a List instead. Then you don't need to declare the sizes in advance, they can grow dynamically.
You can always use the toArray() method on the List afterwards if you really need an array.
The above answers are correct and describe how people would normally implement this. But the description of your problem makes me think this is a class assignment of sorts where dynamic lists are probably unwelcome.
So here's an alternative.
Sort the array to be divided into two parts - of odd and of even numbers. Then count how many odd/even numbers there are and copy the values into two arrays.
Something like this:
static void insertionSort(final int[] arr) {
int i, j, newValue;
int oddity;
for (i = 1; i < arr.length; i++) {
newValue = arr[i];
j = i;
oddity = newValue % 2;
while (j > 0 && arr[j - 1] % 2 > oddity) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = newValue;
}
}
public static void main(final String[] args) {
final int[] numbers = { 1, 3, 5, 2, 2 };
insertionSort(numbers);
int i = 0;
for (; i < numbers.length; i++) {
if (numbers[i] % 2 != 0) {
i--;
break;
}
}
final int[] evens = new int[i + 1];
final int[] odds = new int[numbers.length - i - 1];
if (evens.length != 0) {
System.arraycopy(numbers, 0, evens, 0, evens.length);
}
if (odds.length != 0) {
System.arraycopy(numbers, i + 1, odds, 0, odds.length);
}
for (int j = 0; j < evens.length; j++) {
System.out.print(evens[j]);
System.out.print(" ");
}
System.out.println();
for (int j = 0; j < odds.length; j++) {
System.out.print(odds[j]);
System.out.print(" ");
}
}
Iterate through your source array twice. The first time through, count the number of odd and even values. From that, you'll know the size of the two destination arrays. Create them, and take a second pass through your source array, this time copying each value to its appropriate destination array.
I imagine two possibilities, if you can't use Lists, you can iterate twice to count the number of even and odd numbers and then build two arrays with that sizes and iterate again to distribute numbers in each array, but thissolution is slow and ugly.
I imagine another solution, using only one array, the same array that contains all the numbers. You can sort the array, for example set even numbers in the left side and odd numbers in the right side. Then you have one index with the position in the array with the separation ofthese two parts. In the same array, you have two subarrays with the numbers. Use a efficient sort algorithm of course.
Use following Code :
public class ArrayComparing {
Scanner console= new Scanner(System.in);
String[] names;
String[] temp;
int[] grade;
public static void main(String[] args) {
new ArrayComparing().getUserData();
}
private void getUserData() {
names = new String[3];
for(int i = 0; i < names.length; i++) {
System.out.print("Please Enter Student name: ");
names[i] =console.nextLine();
temp[i] = names[i];
}
grade = new int[3];
for(int i =0;i<grade.length;i++) {
System.out.print("Please Enter Student marks: ");
grade[i] =console.nextInt();
}
sortArray(names);
}
private void sortArray(String[] arrayToSort) {
Arrays.sort(arrayToSort);
getIndex(arrayToSort);
}
private void getIndex(String[] sortedArray) {
for(int x = 0; x < sortedArray.length; x++) {
for(int y = 0; y < names.length; y++) {
if(sortedArray[x].equals(temp[y])) {
System.out.println(sortedArray[x] + " " + grade[y]);
}
}
}
}
}