Sorting of total in an array - java

I am trying to list all the content in a text file then calculate the number of each element by ignoring the first element in each row and sort it in descending order. I don't know how can i sort it.
The content of the text file :
1,2,8,4,5,6,7,7,
3,4,5,6,7,8,3,
5,6,7,8,9,9,
I want the expected result to like this :
Exam[1] : 2 8 4 5 6 7 7
count : 7
Exam[3] : 4 5 6 7 8
count : 5
Exam[5] : 6 7 8 9 9 3
count : 6
Sorted :
How can i sort count 7, count 6 and count 5 in descending order ?
I have tried using this sorting :
private static void sortInDescending(int[] num){
int n = num.length;
int temp = 0;
for(int i = 0; i < n; i++) {
for(int j = 1; j < (n-i); j++) {
temp = num[j-1];
num[j-1] = num[j];
num[j] = temp;
}
}
}
But this sort is to sort each element in each row in descending order.
This is my coding that i done so far :
Scanner scanner = new Scanner(new File("test.txt"));
int row = 0;
int count = 0;
while(scanner.hasNextLine()) {
String currentline = scanner.nextLine();
row++;
String[] items = currentline.split(",");
int[] intitems = new int[items.length];
int i = 0;
for(i = 0; i < items.length; i++) {
intitems[i] = Integer.parseInt(items[i]);
if(i == 0) {
System.out.print("Exam[" +intitems[i]+ "] ");
} else {
System.out.print(intitems[i]+ " ");
count++;
}
}
System.out.println("\nCount " +count);
count = 0;
}

Here is how you can sort your arrays instead of doing it yourself using Arrays
//initialize the array which you want to sort
//in your case it would be `exam` or `count` array
//Pass the array as an argument to sort method, for example
int[] s = new int[10]; //initialize it with values
Arrays.sort(s); //this will sort it in ascending order
System.out.println(Arrays.toString(s)); //to print it
Now, if you want to reverse it - use a for loop and read your array from last index to first index. I am sure you can make that.

Related

Printing an integer array in java using for loop, but the first element is always zero

I have been trying for hours to change a user inputted string of numbers into an integer, then create and print an integer array with those integers. I finally got it, but the first element of the printed array is always zero. I don't know how to fix it. I feel like it is really simple, but I am exhausted and am getting stuck on the easiest things. Does anyone know what is wrong? I'll put my code below.
String stringNum = input.nextLine();
int size = stringNum.length();
int[] myArray = new int[size];
for (int a : myArray) {
System.out.print(a);
System.out.print(" ");
for (int i = 0; i < size; i++) {
char n = stringNum.charAt(i);
int intNum = Character.getNumericalValue(n);
myArray[i] = intNum;
}
}
// input: 12345
// output: 0 2 3 4 5
You have mixed up printing the array and populating the array.
First, parse the input string and populate the array
String stringNum = input.nextLine();
int size = stringNum.length();
int[] myArray = new int[size];
for (int i = 0; i < size; i++) {
char n = stringNum.charAt(i);
int intNum = Character.getNumericalValue(n);
myArray[i] = intNum;
}
Then print the elements,
for (int a : myArray) {
System.out.print(a);
System.out.print(" ");
}

How to approach sorting array largest value first everything else ascending

After generating random numbers in previously user initialised array size afterwards it should be sorted as: Largest value first, everything else in ascending order.
INPUT: 8 29 15 52 18
OUTPUT: 52 8 15 18 29
The problem is I can not understand rather it should be used via one sorting algorithm or via two and then combining? Without Arrays.sort. method.
Did some code for input, random value generating, and finding the largest value and displayig it.
public static void main(String[] args) {
System.out.println("Ievadiet masiva lielumu: "); //Enter array size
Scanner scan = new Scanner(System.in);
Random valuesGenerator = new Random();
int num = scan.nextInt();
int[] myArray = new int[num];
for (int i = 0; i < myArray.length; ++i) {
int randomInt = valuesGenerator.nextInt(100);
myArray[i] = randomInt;
}
System.out.println("Randomizeti generetais masivs: "); //Generated array
for(int k=0; k < myArray.length; k++)
{
System.out.print(myArray[k] + " ");
}
System.out.println(); //New line
int largest = myArray[0];
int largeIndx = 0;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] > largest) {
largest = myArray[i];
largeIndx = i;
}
}
System.out.println("===================");
System.out.println("Largest value = "+largest);
System.out.println("Largest value index = "+largeIndx);
System.out.println("First element is = "+myArray[0]); //first
System.out.println("");
for(int k=0; k < myArray.length; k++)
{
System.out.print(myArray[k] + " ");
}
}
The way I would do that would probably be to find the largest value (you got that already), swap it with the first element in the array and then apply any sorting algorithm on the array, excluding the first element.

removing similar element from the array from sum of any two integer

My input is one integer suppose M and the program must print all the combination of two integer x and y where x + y = M.
Let us take our input as M = 50 and array element as 25 20 25 30 15 45 45 5
and my required output is
5 45,20 30,25 25.
But my output is coming as
5 45,5 45,20 30,25,25
How to remove the occurrence of that two times 5 45?
My code is as follows
Scanner s = new Scanner(System.in);
int m = s.nextInt();
s.nextLine();
String str = s.nextLine();
StringTokenizer st = new StringTokenizer(str);
int len = st.countTokens();
int[] a = new int[len];
String[] temp = new String[len];
for (int i = 0; i < len; i++)
{
temp[i] = st.nextToken();
a[i] = Integer.parseInt(temp[i]);
}
Arrays.sort(a);
for (int i = 0;i < len-1; i++)
{
for(int j = i + 1; j < len; j++)
{
if ((a[i] +a [j]) == m)
System.out.println(a[i] + " " + a[j]);
}
}
use break for skipping repeated number(inner loop) and check (a[i] - a[i+1]) == 0 and use continue to skip repeated number in outer loop.
include only the following changes in the for loop, works perfectly
// Init a new array.
for(int i=0;i<len-1;i++)
{
if((a[i] - a[i+1]) == 0)
continue; // for skipping repeated number in outer loop
for(int j=i+1;j<len;j++)
{
if((a[i]+a[j])==m ) {
System.out.println(a[i]+" "+a[j]);
break; // for skipping repeated number in inner loop
}
else if(a[i] == m/2){
System.out.println(a[i]+" "+a[i]);
break;
}
}
}
input
25 ,20, 25 ,30, 15, 45, 45, 5
output
5 45
20 30
25 25
input
5 ,5 ,45, 45, 45
output
5 45
(5 45) is printed two times as 45 occured 2 times in your input (25 20 25 30 15 45 45 5), if you need distinct pairs remove duplicates from array.
anyway this is not the best optimized solution. for more details check https://www.geeksforgeeks.org/count-pairs-with-given-sum/
you can try to store in a list what you printed and not repeat a print if already printed.
Scanner s=new Scanner(System.in);
int m=s.nextInt();
s.nextLine();
String str=s.nextLine();
StringTokenizer st=new StringTokenizer(str);
int len=st.countTokens();
int a[]=new int[len];
String []temp=new String[len];
for(int i=0;i<len;i++)
{
temp[i]=st.nextToken();
a[i]=Integer.parseInt(temp[i]);
}
Arrays.sort(a);
List<String> output = new ArrayList<>();
for(int i=0;i<len-1;i++)
{
for(int j=i+1;j<len;j++)
{
if((a[i]+a[j])==m) {
String msg = a[i]+" "+a[j];
if(!output.contains(msg)) {
System.out.println(msg);
output.add(msg);
}
}
}
}
s.close();
When just printing the correct pairs, you cannot check for the former solutions. You can add a[i] and a[j] whose sum is M to an array. After that, if a new pair summary gives M, you can check the array if elements in it.
Scanner s=new Scanner(System.in);
int m=s.nextInt();
s.nextLine();
String str=s.nextLine();
StringTokenizer st=new StringTokenizer(str);
int len=st.countTokens();
int a[]=new int[len];
String []temp=new String[len];
for(int i=0;i<len;i++)
{
temp[i]=st.nextToken();
a[i]=Integer.parseInt(temp[i]);
}
Arrays.sort(a);
// Init a new array.
for(int i=0;i<len-1;i++)
{
for(int j=i+1;j<len;j++)
{
if((a[i]+a[j])==m) {
// if(new array contains a[i]) continue;
//array.add(a[i]);
//array.add(a[j]);
System.out.println(a[i]+" "+a[j]);
}
}
}
I wouldn't try to reinvent the wheel. Just put every pair in a java.util.Set so you only have distinct pairs:
Add this right before your last nested loop:
Set<String> pairs = new HashSet<>();
And change System.out.println(a[i] + " " + a[j]); to pairs.add(a[i] + " " + a[j]);
And in the end you can print the contents of the Set.
Try it online.

Getting the most "popular" number from array

I need for homework to get the most "popular" number in an array (the number in the highest frequency), and if there are several numbers with the same number of shows, get some number randomly.
After more then three hours of trying, and either searching the web, this is what I got:
public int getPopularNumber(){
int count = 1, tempCount;
int popular = array[0];
int temp = 0;
for ( int i = 0; i < (array.length - 1); i++ ){
if ( _buses[i] != null )
temp = array[i];
tempCount = 0;
for ( int j = 1; j < _buses.length; j++ ){
if ( array[j] != null && temp == array[j] )
tempCount++;
}
if ( tempCount > count ){
popular = temp;
count = tempCount;
}
}
return popular;
}
This code work, but don't take into account an important case- if there is more than one number with the same count of shows. Then it just get the first one.
for example: int[]a = {1, 2, 3, 4, 4, ,5 ,4 ,5 ,5}; The code will grab 4 since it shown first, and it's not random as it should be.
Another thing- since it's homework I can't use ArrayList/maps and stuff that we still didn't learn.
Any help would be appreciated.
Since they didn't give you any time complexity boundary, you can "brute force" the problem by scanning the the array N^2 times. (disclaimer, this is the most intuitive way of doing it, not the fastest or the most efficient in terms of memory and cpu).
Here is some psuedo-code:
Create another array with the same size as the original array, this will be the "occurrence array"
Zero its elements
For each index i in the original array, iterate the original array, and increment the element in the occurrence array at i each time the scan finds duplicates of the value stored in i in the original array.
Find the maximum in the occurrence array
Return the value stored in that index in the original array
This way you mimic the use of maps with just another array.
If you are not allowed to use collection then you can try below code :
public int getPopularNumber(){
int inputArr[] = {1, 2, 3, 4, 4, 5 ,4 ,5 ,5}; // given input array
int[] tempArr = new int[inputArr.length];
int[] maxValArr = new int[inputArr.length];
// tempArr will have number as index and count as no of occurrence
for( int i = 0 ; i < inputArr.length ; i++){
tempArr[inputArr[i]]++;
}
int maValue = 0;
// find out max count of occurrence (in this case 3 for value 4 and 5)
for( int j = 0 ; j < tempArr.length ; j++){
maValue = Math.max(maValue, tempArr[j]);
}
int l =0;
// maxValArr contains all value having maximum occurrence (in this case 4 and 5)
for( int k = 0 ; k < tempArr.length ; k++){
if(tempArr[k] == maValue){
maxValArr[l] = k;
l++;
}
}
return maxValArr[(int)(Math.random() * getArraySize(maxValArr))];
}
private int getArraySize(int[] arr) {
int size = 0;
for( int i =0; i < arr.length ; i++){
if(arr[i] == 0){
break;
}
size++;
}
return size;
}
that's hard as hell :D
After some trying, I guess I have it (If there will be 2 numbers with same frequency, it will return first found):
int mostPopNumber =0;
int tmpLastCount =0;
for (int i = 0; i < array.length-1; i++) {
int tmpActual = array[i];
int tmpCount=0;
for (int j = 0; j < array.length; j++) {
if(tmpActual == array[j]){
tmpCount++;
}
}
// >= for the last one
if(tmpCount > tmpLastCount){
tmpLastCount = tmpCount;
mostPopNumber = tmpActual;
}
}
return mostPopNumber;
--
Hah your code give me idea- you cant just remember last most popular number, btw I've found it solved there Find the most popular element in int[] array
:)
EDIT- after many, and many years :D, that works well :)
I've used 2D int and Integer array - you can also use just int array, but you will have to make more length array and copy actual values, Integer has default value null, so that's faster
Enjoy
public static void main(String[] args) {
//income array
int[] array= {1,1,1,1,50,10,20,20,2,2,2,2,20,20};
//associated unique numbers with frequency
int[][] uniQFreqArr = getUniqValues(array);
//print uniq numbers with it's frequency
for (int i = 0; i < uniQFreqArr.length; i++) {
System.out.println("Number: " + uniQFreqArr[i][0] + " found : " + uniQFreqArr[i][1]);
}
//get just most frequency founded numbers
int[][] maxFreqArray = getMaxFreqArray(uniQFreqArr);
//print just most frequency founded numbers
System.out.println("Most freq. values");
for (int i = 0; i < maxFreqArray.length; i++) {
System.out.println("Number: " + maxFreqArray[i][0] + " found : " + maxFreqArray[i][1]);
}
//get some of found values and print
int[] result = getRandomResult(maxFreqArray);
System.out.println("Found most frequency number: " + result[0] + " with count: " + result[1]);
}
//get associated array with unique numbers and it's frequency
static int[][] getUniqValues(int[] inArray){
//first time sort array
Arrays.sort(inArray);
//default value is null, not zero as in int (used bellow)
Integer[][] uniqArr = new Integer[inArray.length][2];
//counter and temp variable
int currUniqNumbers=1;
int actualNum = inArray[currUniqNumbers-1];
uniqArr[currUniqNumbers-1][0]=currUniqNumbers;
uniqArr[currUniqNumbers-1][1]=1;
for (int i = 1; i < inArray.length; i++) {
if(actualNum != inArray[i]){
uniqArr[currUniqNumbers][0]=inArray[i];
uniqArr[currUniqNumbers][1]=1;
actualNum = inArray[i];
currUniqNumbers++;
}else{
uniqArr[currUniqNumbers-1][1]++;
}
}
//get correctly lengthed array
int[][] ret = new int[currUniqNumbers][2];
for (int i = 0; i < uniqArr.length; i++) {
if(uniqArr[i][0] != null){
ret[i][0] = uniqArr[i][0];
ret[i][1] = uniqArr[i][1];
}else{
break;
}
}
return ret;
}
//found and return most frequency numbers
static int[][] getMaxFreqArray(int[][] inArray){
int maxFreq =0;
int foundedMaxValues = 0;
//filter- used sorted array, so you can decision about actual and next value from array
for (int i = 0; i < inArray.length; i++) {
if(inArray[i][1] > maxFreq){
maxFreq = inArray[i][1];
foundedMaxValues=1;
}else if(inArray[i][1] == maxFreq){
foundedMaxValues++;
}
}
//and again copy to correctly lengthed array
int[][] mostFreqArr = new int[foundedMaxValues][2];
int inArr= 0;
for (int i = 0; i < inArray.length; i++) {
if(inArray[i][1] == maxFreq){
mostFreqArr[inArr][0] = inArray[i][0];
mostFreqArr[inArr][1] = inArray[i][1];
inArr++;
}
}
return mostFreqArr;
}
//generate number from interval and get result value and it's frequency
static int[] getRandomResult(int[][] inArray){
int[]ret=new int[2];
int random = new Random().nextInt(inArray.length);
ret[0] = inArray[random][0];
ret[1] = inArray[random][1];
return ret;
}

arraylist java counting runs of integers

I am new to java and array lists. I am supposed to sort populate an array full of random integers, then if there is a run (multiples of the same number in a row), put ( ) around that run.
So if the random list is:
2 3 4 5 5 5 5 6 7 7 9
2 3 4 (5 5 5 5) 6 (7 7) 9
This is what I have so far:
import java.util.*;
class Run {
public static void main (String [] args){
Scanner m = new Scanner(System.in);
System.out.print("Enter length wanted: ");
int len = m.nextInt();
System.out.print("Enter max number wanted: ");
int max = m.nextInt();
max = max -1;
int[] x = new int[len];
ArrayList<String> y = new ArrayList<String>();
//Filling x with random numbers
for(int i = 0; i<len; i++){
x[i] = ((int)(Math.random()*max)+1);
}
System.out.println("Orginal Array: " + Arrays.toString(x));
for(int i = 0; i<=len-1; i++){
if(x[i] == x[i++]){ //I just don't know how I am exactly supposed to sort this
}else{
}
}
//Array List with ()
System.out.println("Runs labeled Array: " + y);
}
}
You're going to need a String to display the final output. Also, don't go out of the array.
Try Something like this:
x = Collections.sort(x);
String s = "";
boolean b;
for(int i = 0; i<=len-1; i++){
if(x[i] == x[i+1]){
s+=" ("+i+" ";
b = true;
}else{
if(b == true){
s+=i+") ";
b = false;
}
s+=i + " ";
}
}
use Collections.sort(yourList) to sort your ArrayList.
If you dont wanna use API methods.
try :
for(int i=0;i<list.size(); i++){
for(int j=i+1; j<list.size(); j++){
if(list.get(i)>list.get(j)){
temp = list.get(i);
list.set(i,list.get(j));
list.set(j, temp);
}
}
}

Categories