Java modify array elemens - java

Hey guys I want to write program that shifts elements in an array once to the left but I tried everything and it's not working. The code below is outputting just 0's. Can someone please tell me how I can do this. Thank you!
import java.util.Scanner;
public class StudentScores {
public static void main (String [] args) {
Scanner scnr = new Scanner(System.in);
final int SCORES_SIZE = 4;
int[] oldScores = new int[SCORES_SIZE];
int[] newScores = new int[SCORES_SIZE];
int i;
for (i = 0; i < oldScores.length; ++i) {
oldScores[i] = scnr.nextInt();
}
int temp = newScores[0];
for (i = 0; i < oldScores.length - 1; ++i) {
newScores[i] = newScores[i+1];
}
temp = newScores[oldScores.length - 1];
for (i = 0; i < newScores.length; ++i) {
System.out.print(newScores[i] + " ");
}
System.out.println();
}
}````

As pointed out by people in comments, you seem to be assigning newScores[] to newScores[] value(an uninitialized array has all values set to 0):
int temp = newScores[0]; // Should be oldScores[0]
// ...
newScores[i] = newScores[i+1]; // Should be oldScores[i+1]
You need to have oldScores[] values on RHS. Since you only want to shift by one place, I think extra array is unnecessary. You can do it in place like this:
int temp = oldScores[0];
for (i = 0; i < oldScores.length - 1; ++i) {
oldScores[i] = oldScores[i + 1];
}
oldScores[oldScores.length - 1] = temp;

Related

Array not copying another array

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.

calling another method from different class

I was practicing java. And I created a method in another class within the same package such that,
class ArraysPractice2{
int n;
int[] arr = new int[n];
double averageA(int [] arr)
{
double ans = 0;
int added = 0;
int total = arr.length;
for(int i = 0; i < arr.length; i++)
{
added = added + arr[i];
}
ans = added / total;
return ans;
}
}
and then I have a main method has following code,
ArraysPractice2 aT = new ArraysPractice2();
int[] testArr = new int[10];
for(int i = 0; i < testArr.length; i++)
{
testArr[i] = i + 1;
}
aT.averageA(testArr);
I expected that aT.averageA would give me the average of testArr array.
However, it does not give me anything.
What are the issues in here?
I have a feeling that I am not understanding OOP well..
Thank you for your help.
aT.averageA(testArr);
You are not receiving/using a value you have got in the line above.
Try this:
double res = aT.averageA(testArr);
System.out.println("aT.averageA(testArr = "+res);
and you should see your value.

Temp integers not resetting

I am creating a histogram using another class to help display it, but that is not important to my question. Let me start by showing my code below
public class DisplayHistogram {
public static void main(String[] args) {
int temp = 0;
int holder = 0;
int average;
Random rand = new Random();
Histogram x = new Histogram(1, 20);
for(int i = 0; i<=10000; i++)
{
for(int j = 0; j<=3; j++)
{
temp = rand.nextInt(20) + 1;
holder = holder + temp;
}
average = Math.round(holder / 3);
x.submit(average);
}
System.out.println(x.toString());
}
}
the problem I am having is I set the histogram to have a min of 1 and max of 20. I am generating three random integers and finding the average of the 3 and submitting it to the histogram 10,000 times. However, after the first loop of 10000, the "holder" variable doesn't reset back to 0 causing my program trying to submit a value outside of the max, and creating an error. I have attempted to set holder to 0 at the end of every loop by doing
x.submit(average);
holder = 0;
temp = 0;
However that does not help.
I have tried some of your suggestions making my code look like
import java.util.*;
public class DisplayHistogram {
public static void main(String[] args) {
Random rand = new Random();
Histogram x = new Histogram(1, 20);
for(int i = 0; i<=10000; i++)
{
int temp = 0;
int holder = 0;
int average = 0;
for(int j = 0; j<=3; j++)
{
temp = rand.nextInt(20) + 1;
holder = holder + temp;
}
average = Math.round(holder / 3);
x.submit(average);
}
System.out.println(x.toString());
}
}
However it still returns this error
Exception in thread "main" HistogramOutOfBoundsException:
*******
Submitted value 22 is outside range [1,20] of Histogram.
*******
at Histogram.submit(Histogram.java:31)
at DisplayHistogram.main(DisplayHistogram.java:19)
Write your loops like this:
for(int i = 0; i<=10000; i++)
{
holder = 0; // add this line
for(int j = 0; j<=3; j++)
{
temp = rand.nextInt(20) + 1;
holder = holder + temp;
}
average = Math.round(holder / 3);
x.submit(average);
}
System.out.println(x.toString());
}
Fixed. Was looping four times instead of three. For loop should've looked like
for(int i=0; i<=2; i++)
Short answer
Pay attention to details.
The answer you want
Unlike the other answer,
don't just initialize the holder variable every loop.
Instead, minimize the scope of the holder variable to the loop.
public static void main(String[] args)
{
int average;
Random rand = new Random();
Histogram x = new Histogram(1, 20);
for (final int trialCount = 0; trialCount <= 10000; ++trialCount)
{
int holder = 0;
for (final int sampleCount = 0; sampleCount <= 3; ++sampleCount)
{
int temp = rand.nextInt(20) + 1;
holder += temp;
}
average = Math.round(holder / 3);
x.submit(average);
}
System.out.println(x.toString());
}

Inserting number into random array

I need some help inserting the number 8 into an array that gives me random values. The array must be in order. For example if I had an array of (1,5,10,15), I have to insert the number 8 between 5 and 10. I am having a problem on how I can figure our a way to find the index where 8 will be placed because the array is random, it can be anything. Here is my code so far :
public class TrickyInsert {
public static void main(String[] args) {
int[] mysteryArr = generateRandArr();
//print out starting state of mysteryArr:
System.out.print("start:\t");
for ( int a : mysteryArr ) {
System.out.print( a + ", ");
}
System.out.println();
//code starts below
// insert value '8' in the appropriate place in mysteryArr[]
int[] tmp = new int[mysteryArr.length + 1];
int b = mysteryArr.length;
for(int i = 0; i < mysteryArr.length; i++) {
tmp[i] = mysteryArr[i];
}
tmp[b] = 8;
for(int i =b ; i<mysteryArr.length; i++) {
tmp[i+1] = mysteryArr[i];
}
mysteryArr = tmp;
any tips? thanks!
Simply add the number then use Arrays.sort method,
int b = mysteryArr.length;
int[] tmp = new int[b + 1];
for(int i = 0; i < b; i++) {
tmp[i] = mysteryArr[i];
}
tmp[b] = 8;
mysteryArr = Arrays.sort(tmp);
In your example the random array is sorted. If this is the case, just insert 8 and sort again.
Simply copy the array over, add 8, and sort again.
int[] a = generateRandArr();
int[] b = Arrays.copyOf(a, a.length + 1);
b[a.length] = 8;
Arrays.sort(b);
int findPosition(int a, int[] inputArr)
{
for(int i = 0; i < inputArr.length; ++i)
if(inputArr[i] < a)
return i;
return -1;
}
int[] tmpArr = new int[mysteryArr.length + 1];
int a = 8; // or any other number
int x = findPosition(a, mysteryArr);
if(x == -1)
int i = 0;
for(; i < mysteryArr.length; ++i)
tmpArr[i] = mysteryArr[i];
tmpArr[i] = a;
else
for(int i = 0; i < mysteryArr.length + 1; ++i)
if(i < x)
tmpArr[i] = mysteryArr[i];
else if(i == x)
tmpArr = a;
else
tmpArr[i] = mysteryArr[i - 1];
I will suggest using binary search to find the appropriate index. Once you locate the index, you can use
System.arraycopy(Object src, int srcIndex, Obj dest, int destIndex, int length)
to copy the left half to your new array (with length one more than the existing one) and then the new element and finally the right half. This will stop the need to sort the whole array every time you insert an element.
Also, the following portion does not do anything.
for(int i =b ; i<mysteryArr.length; i++) {
tmp[i+1] = mysteryArr[i];
}
since int b = mysteryArr.length;, after setting int i =b ;, i<mysteryArr.length; will be false and hence the line inside this for loop will never execute.

ways to speed up the Full Counting Sort

I encountered a question on hackerrank.
https://www.hackerrank.com/challenges/countingsort4
My first attempt passed all the test cases except the last one, due to timeout.
After failed to come up with a more efficient algorithm, I improved the code by using StringBuilder instead of concatenating Strings directly. This brought the running time from more than 5 sec to 3.5 sec.
My question is that is there any other way that I can improve the running time?
Thanks.
The following is my code.
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
scanner.nextLine();
int[] oriNum = new int[N];
String[] oriStr = new String[N];
int[] count = new int[100];
int[] indices = new int[100];
int[] output = new int[N];
// save the originals and the count array
for (int i = 0; i < N; i++) {
oriNum[i] = scanner.nextInt();
oriStr[i] = scanner.nextLine().trim();
count[oriNum[i]]++;
}
// accumulate the count array
indices[0] = 0;
for (int i = 1; i < 100; i++) {
indices[i] = indices[i-1] + count[i-1];
}
// output order
for (int i = 0; i < N; i++) {
int num = oriNum[i];
output[indices[num]++] = i;
}
int bar = N/2;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < N; i++) {
int index = output[i];
if (index < bar)
sb.append("- ");
else
sb.append(oriStr[index]+ " ");
}
System.out.println(sb.toString());
}
}
You should try a plain buffered reader instead of Scanner. Scanner is surprisingly slow and I have participated in programming competitions where Scanner was the sole reason for "time limit exceeded".
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution
{
public static void main(String[] args)throws Exception
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(in.readLine());
int[] c=new int[100];
String[][] dt=new String[100][10300];
for(int i=0;i<n;i++)
{
String[] str=in.readLine().split(" ");
int val=Integer.parseInt(str[0]);
if(i<n/2)
dt[val][c[val]]="-";
else
dt[val][c[val]]=str[1];
c[val]++;
}
StringBuilder sb=new StringBuilder("");
for(int i=0;i<100;i++)
if(i<n)
for(int k=0;k<c[i];k++)
if(dt[i][k]!=null)
sb.append(dt[i][k]+" ");
else break;
System.out.println(sb.toString());
}
}
This was my approach to problem. (it is in c++).
void counting_sort(vector<int> &arr, int size, vector<vector<string> > foo, vector<int> first_half)
{
int max = *max_element(arr.begin(), arr.end());
int min = *min_element(arr.begin(), arr.end());
int range = max - min + 1;
int count[range] = {0};
// counting frequency of numbers in array
for (int i = 0; i < size; i++)
{
count[arr[i] - min]++;
}
// calculating cumulative sum
for (int i = 1; i < range; i++)
{
count[i] += count[i - 1];
}
vector<vector<string> > output(size);
// making the new sorted array
for (int i = size - 1; i >= 0; i--) // traversing from backward for stability
{
output[count[arr[i]-min] - 1] = foo[i];
count[arr[i]-min]--;
}
// copying the sorted array in original array
int j=0;
for (int i = 0; i < size; i++)
{
if(stoi(output[i][0]) == first_half[j])
{
cout << "- ";
j++;
}
else
{
cout << output[i][1] << ' ';
}
}
}
// Complete the countSort function below.
void countSort(vector<vector<string>> arr) {
vector<int> num;
vector<int> first_half;
for(int i=0; (unsigned)i<arr.size(); i++)
{
num.push_back(stoi(arr[i][0]));
if(i < ((unsigned)arr.size()/2))
{
first_half.push_back(stoi(arr[i][0]));
}
}
sort(first_half.begin(), first_half.end());
counting_sort(num, num.size(), arr, first_half);
}

Categories

Resources