I get this error when I attempt to sort it based off the second char in the string but it runs
fine when I use the first char
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 8
at StringCountSort.countingSort(StringCountSort.java:27)
at StringCountSort.main(StringCountSort.java:38)
import java.util.Arrays;
public class StringCountSort{
public static void countingSort(String[] array, int size, int digit)
{
String[] result = new String[size+1];
int maximum = 122;
int[] count = new int[maximum + 1];
for (int i = 0; i < count.length; i++){
count[i] = 0;
}
for (int i = 0; i < size; i++){
count[array[i].charAt(digit)] +=1;
}
for (int i = 1; i < count.length; i++){
count[i] += count[i-1];
}
for (int i = size -1; i >= 0; i--){
result[count[array[i].charAt(digit)] - 1] = array[i];
count[array[i].charAt(0)]--;
}
for (int i = 0; i < size; i++) {
array[i] = result[i];
}
}
public static void main(String args[]){
String[] data = { "eg", "fa", "bz", "ch", "hv", "df", "ag" };
StringCountSort.countingSort(data, data.length, 1);
System.out.println("Sorted Array in Ascending Order: ");
System.out.println(Arrays.toString(data));
}
}
line 28 result[count[array[i].charAt(digit)] - 1] = array[i];
line 37 StringCountSort.countingSort(data, data.length, 1);
Change
count[array[i].charAt(0)]--;
to
count[array[i].charAt(digit)]--;
This should do the trick.
I also suggest the following improvements:
You don't need to pass the length of array as an argument.
You don't need to set every int of count to 0;
maximum should be Character.MAX_VALUE, to support every possible character.
The finished function could look like this:
public static void countingSort(String[] array, int digit) {
String[] result = new String[array.length];
int[] count = new int[Character.MAX_VALUE + 1];
for (int i = 0; i < array.length; i++){
count[array[i].charAt(digit)]++;
}
for (int i = 1; i < count.length; i++){
count[i] += count[i-1];
}
for (int i = array.length -1; i >= 0; i--){
result[count[array[i].charAt(digit)] - 1] = array[i];
count[array[i].charAt(digit)]--;
}
for (int i = 0; i < array.length; i++) {
array[i] = result[i];
}
}
Things that need to be changed are (if you want to sort the strings on the basis of first character)
count[array[i].charAt(digit)] +=1 to count[array[i].charAt(0)] +=1
result[count[array[i].charAt(digit)] - 1] = array[i]; count[array[i].charAt(0)]--; to result[--count[array[i].charAt(0)]] = array[i];
If you want to sort the string on the basis of the second character then simply change :
count[array[i].charAt(0)]--; to count[array[i].charAt(digit)]--;
Related
I am trying to create a program, which counts the minimum of each dimension in a two dimensional array. So for ex. if i had an array:
int[][] test = {{1,2,3},{2,3,4},{4,5,6}}
the program would display: [1,2,4] - the minimum of each dimension.
For that I've created a method called minimum, which looks like this
static int[] minimum(int[][] arr) {
int[] result = new int [arr.length];
for (int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr[i].length; j++) {
int min = arr[i][0];
if(arr[i][j] < min) {
min = arr [i][j];
result [i] = min;
} else{
}
}
}
return result;
}
But when i call out this method in my main, with a sample array
public static void main(String[] args) {
int[][] arr = {{1,2,3,},{3,4,5},{6,6,6}};
System.out.println(Arrays.toString(minimum(arr)));
}
The program displays [0,0,0,]. Do You have any clue where is the problem and how to fix it?
The problem is that if the first element in the array is min, it never gets recorded to the result array. Try:
static int[] minimum(int[][] arr) {
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = arr[i][0];
for (int j = 1; j < arr[i].length; j++) {
if (arr[i][j] < result[i]) {
result[i] = arr[i][j];
}
}
}
return result;
}
Note that there needs to be at least one element per row in the input matrix for the above function; add a conditional or use Integer.MIN_VALUE to handle empty rows if you wish.
This should work. You reset the min to the first element every time. So you are basically comparing if there is any value smaller than the first one.
static int[] minimum(int[][] arr){
int[] result = new int [arr.length];
for (int i = 0; i < arr.length; i++){
result[i] = Integer.MAX_VALUE;
for(int j = 0; j < arr[i].length; j++){
if(arr[i][j] < result[i]) {
result [i] = arr[i][j];
}
}
}
return result;
}
I am stuck with an exercise which tells me to create a reversed array from the given one.
After some thinking I made such code:
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = 0; j < nums.length; j++) {
nums2[j] = nums[i];
}
}
return nums2;
}
But it is throwing out three exact same numbers.
You don't need a nested for loop - just iterate over the source array and fill the result array in the opposite order:
public int[] reverse(int[] nums) {
int len = nums.length;
int[] result = new int[len];
for (int i = 0; i < len; ++i) {
result[len - i - 1] = nums[i];
}
}
From a first look, your code should be more like this:
public int[] reverse3(int[] nums)
{
// initialize a second array with the same length
int[] nums2 = new int[nums.length];
// initialize the nums2 index
int index = 0;
// you only need one loop for this (since we'll be incrementing the index of nums2)
for (int i = nums.length - 1; i >= 0; i--) {
nums2[index] = nums[i];
index++;
}
return nums2;
}
Swap the symetric values in the array like this :
public static void reverse(int[] nums) {
for (int i = 0; i < nums.length / 2; i++) {
int temp = nums[i];
nums[i] = nums[nums.length - 1 - i];
nums[nums.length - 1 - i] = temp;
}
To reverse an array you only have to swap the elements until the midpoint:
public int[] reverse(int[] nums) {
int numsLength = nums.length;
for (int i = 0; i < numsLength / 2; i++) {
int temp = nums[i];
nums[i] = nums[numsLength - i - 1];
nums[numsLength - i - 1] = temp;
}
return nums;
}
This way is much more optimized.
Source: How do I reverse an int array in Java?
I am new to Java development and sorry if this question will be too
silly, but it seems like I am stuck with the exercise which tells me
to create a reversed array from the given one.
After some thinking I made such code:
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = 0; j < nums.length; j++) {
nums2[j] = nums[i];
} } return nums2; }
But it is throwing out three exact same numbers. Could I please count
on some help? Thank you
Use one loop only. If you want to use 2 arrays(wich i do not see the point.) this will work:
int j = 0;
for(int i = nums.length -1; i >= 0; i--){
nums2[j] = nums[i];
j++;
}
But if you want to use only one array, you can do this:
for (int i = 0; i < nums.length/2; i++) {
int aux = nums[i];
nums[i] = nums[nums.length-i-1];
nums[nums.length-i-1] = aux;
}
There are so many efficient ways to do it but to make you understand i am gonna modify your own code
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
for (int i = nums.length - 1; i >= 0; i--) {
for (int j = (nums.length-1) - i; j < nums.length; j++) {
nums2[j] = nums[i];
}
}
return nums2;
}
or let's do a a little bit modification rather than using nums.length() again and again we can put it inside a variable
public int[] reverse3(int[] nums) {
int[] nums2 = new int[3];
int length = nums.length;
for (int i = length - 1; i >= 0; i--) {
for (int j = (length-1) - i; j < length; j++) {
nums2[j] = nums[i];
}
}
return nums2;
}
Remember it is not an efficient way but to make you understand i just modify the logic. Using nested loops like that will decrease the performance so better avoid it and try to do it in much more optimized way..
Recently, I took Linkedin placement test in which there was a question in which output for 4 test cases were wrong for me. I could not figure out what was my mistake becasue inputs/outputs were hidden.
Anyways here was the question:
Find the maximum element from an array where product of any other two elements would be equal to that number and return that number .If no, such element is there then return -1.
Here was my solution:
static int maxElement(int[] arr) {
Arrays.sort(arr);
int max = arr[arr.length-1];
int result = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
result = arr[i] * arr[j];
if (result == max) {
return max;
}
}
}
return -1;
}
I guess you need to find the possible maximum number in the array and the product of two elements in the array.
If I assume this, your code fails for this test case:
int[] arr = {2,4,5,3,7,6}; , where the answer should be 6
Check this below code it will work for above test-case.
Just add one more reverse for loop to check the possible value and product.
static int maxElement(int[] arr) {
Arrays.sort(arr);
for (int k = arr.length-1; k >= 0; k--) {
int max = arr[k];
int result = 0;
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
result = arr[i] * arr[j];
if (result == max) {
return max;
}
}
}
}
return -1;
}
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < a.length; i++) {
list.add(a[i]);
}
int maxSum = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if ((a[i] * a[j]) > maxSum) {
if(list.contains(a[i] * a[j]))
maxSum = a[i] * a[j];
}
}
}
if (maxSum != 0)
return maxSum;
return -1;
I got homework "Take two given array(already sorted up, for example {1,2,3}) and create a new array contains both arrays and then sort him up", we have a function to sort up arrays so it's not the problem, however it gets a little bit complex to me, here is my code:
public static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
int[] a = new int[3];
int[] b = new int[5];
Help_arr.scan(a);
Help_arr.scan(b);
Help_arr.print(peula(a, b));
}
public static int[] peula(int[] a1, int[] b1) {
int[] c = new int[a1.length + b1.length];
for (int i = 0; i < a1.length; i++)
c[i] = a1[i];
for (int i = a1.length; i < c.length; i++){
c[i] = b1[i];
}
Help_arr.sortup(c);
return c;
}
Functions used from Help_arr class:
1) Scan an array:
public static void scan(int[] arr1) {
for (int i = 0; i < arr1.length; i++) {
System.out.println("Enter number" + (i + 1));
arr1[i] = in.nextInt();
}
}
2) Print an array:
public static void print(int[] arr1) {
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i] + " ");
}
}
3) Sort up an array:
public static void sortup(int[] arr1) {
int i, mini, temp, j;
for (j = 0; j < arr1.length; j++) {
mini = j;
for (i = j; i < arr1.length; i++) {
if (arr1[i] < arr1[mini])
mini = i;
}
temp = arr1[j];
arr1[j] = arr1[mini];
arr1[mini] = temp;
}
}
I get an error in the line c[i]=b1[i]; the array is going out of index bounds but I followed the code and this for will run until i=7 as the c.length is 8 and it is possible. But maybe I am missing something, here is the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at arrays.PgRonTargilMivhan.peula(PgRonTargilMivhan.java:21)
at arrays.PgRonTargilMivhan.main(PgRonTargilMivhan.java:13)
The issue is with this code:
for (int i = a1.length; i < c.length; i++){
c[i] = b1[i];
here b1 index should start with 0 but you are starting with a1.length. You should have a separate index for b1 or use b1[i-a1.length].
Please find the logic ..
you were using 'i' index for array b is the problem.
Solution is below. Good luck
int[] c = new int[a.length + b.length];
int i = 0;
for (i = 0; i < a.length; i++)
c[i] = a[i];
for (int j = 0; j < b.length; j++)
c[i] = b[j];
}
I'm trying to convert an integer into an array of digits, then print those digits out in order. It's an early problem in Java: How to Program, and I'm confused as to why I can't make it work.
Here's my class:
public class AnyDigits {
private int[] ns;
public AnyDigits(int n){
this.ns = new int[String.valueOf(n).length()];
for(int i = 0, x = n; x > 0; i++, x = x / 10){
this.ns[i] = x % 10;
}
}
public void printDigits(){
for(int i = this.ns.length - 1; i == 0; i--){
System.out.printf("%d ", this.ns[i]);
}
}
}
I have this code in my main method:
AnyDigits digitsTest = new AnyDigits(42339);
digitsTest.printDigits();
Any comments on the organisation, style and formatting of my code are also welcomed.
Any help gratefully received!
for(int i = this.ns.length - 1; i == 0; i--){
System.out.printf("%d ", this.ns[i]);
}
This won't work, you are iterating while i==0, i will never be 0 at the first loop unless this.ns.length == 1.
You need
for(int i = this.ns.length - 1; i != 0; i--){
System.out.printf("%d ", this.ns[i]);
}
or
for(int i = this.ns.length - 1; i >= 0; i--){
System.out.printf("%d ", this.ns[i]);
}
Anyway, if you want to print an array, you can just do
System.out.println(Arrays.toString(yourArray));
Another way aside from BackSlash's answer-
private static int[] makeArrayFromInt(final int val){
String temp = String.valueOf(val);
int[] digits = new int[temp.length()];
for(int i = 0; i < temp.length(); i++){
digits[i] = Integer.parseInt(temp.substring(i, i + 1));
}
return digits;
}
Test:
int[] digits = makeArrayFromInt(12234);
for(int i = 0; i < digits.length; i++){
System.out.println(digits[i]);
}