Pre increment on arrays - java

Can anyone explain the output of this code? I have been hitting my head really hard to understand, but I just don't get it.
public static void main(String ars[]) {
int responses[] = {1,2,4,4};
int freq[] = new int[5];
for(int answer = 1; answer < responses.length; answer++) {
++freq[responses[answer]];
}
for (int rating = 1; rating < freq.length; rating++)
System.out.printf("%6d%10d\n", rating, freq[rating]);
}
Output
1 0
2 1
3 0
4 2

In first loop ++freq[responses[answer]]; means :
responses[answer] get the value from response array index.
Freq[value] check & get the value from Filter array index.
++Freq[value] add value 1 to Freq[value].

I've tried to simply things a bit so you can see what is going on:
int responses[] = new int[4];
responses[0] = 1;
responses[1] = 2;
responses[2] = 4;
responses[3] = 4;
int freq[] = new int[5];
for(int answer = 1; answer < 4; answer++)
{
int x = responses[answer];
freq[x] = freq[x] + 1;
}
for (int rating = 1; rating < 5; rating++)
{
//Print 6 spaces and then the rating variable
//Print 10 spaces then the integer at freq[rating]
System.out.printf("%6d%10d\n", rating, freq[rating]);
}
I would look up the ++ prefix & postfix.

Related

Adding columns in an array that is created using command line arguments

My goal for this program is to create a 2D-array ratings whose size is specified by the first two arguments from the command line. args[0] would represent the number of rows r and arg[1] would represent the number of columns c. The next arguments that follow would all be used to fill in the array. So if the command-line argument was 3 2 5 2 3 3 4 1. I would hope that the array would be 3 rows by 2 columns. The value 5 would be in ratings[0][0], the value 2 would be in ratings[0][1], the value 3 would be in ratings[1][0], etc. After that, I want to compute the sum of each column. So column 0 would be 12 and column 1 would be 6 in this scenario.
public static void main(String[] args) {
int r = Integer.parseInt(args[0]);
int c = Integer.parseInt(args[1]);
int[][] ratings = new int[r][c];
int z = 2;
int y = 3;
int x = 0;
int counting = 0;
int sum = 0;
for (int rows = 0; rows < ratings.length; rows++ ) {
for (int column = 0; column < ratings[c].length; column++){
ratings[rows][column] = Integer.parseInt(args[z]);
sum += ratings[rows][column];
z++;
}
System.out.println(sum);
sum = 0;
}
//System.out.println(movieRating);
}
This is my attempt at summing the columns but this right now just sums 5 and 2, 3 and 3, 4 and 1. I want the columns not the rows to be summed but do not know how to fix it. Thank you
You seem to be adding the values to the 2D array correctly. What you're missing is an additional nested loop to print out the column totals:
for (int i = 0; i < ratings[c].length; i++) {
int colSum = 0;
for (int j = 0; j < ratings.length; j++) {
colSum += ratings[j][i];
}
System.out.println(colSum);
}
Add that where you currently have that //System.out.println(movieRating); line. Since you were adding the numbers to the array row-wise, you need to flip the for loops to be able to sum the columns.
Things you did right
You correctly initialized the ratings 2D-array with the values given on the command line. Let me re-write this below without your attempt at computing the columns' sum. Note that I renamed the variables so that the indices used in the for loop are single letter variable.
public static void main(String[] args) {
int rows = Integer.parseInt(args[0]);
int columns = Integer.parseInt(args[1]);
int[][] ratings = new int[rows][columns];
int argIndex = 2;
for (int r = 0; r < ratings.length; r++ ) {
for (int c = 0; column < ratings[r].length; c++){
ratings[r][c] = Integer.parseInt(args[argIndex]);
argIndex++;
}
}
}
Thing you didn't get right
The ratings array is filled row by row. In the code you posted, you compute in variable sum the sum of the elements inserted in the same row. This is the reason why it doesn't print the results you expected.
To compute the sum of each columns, I would recommend you create a new array in which to store this result. Integrating it with the code above:
public static void main(String[] args) {
int rows = Integer.parseInt(args[0]);
int columns = Integer.parseInt(args[1]);
int[][] ratings = new int[rows][columns];
int[] columnSums = new int[columns];
int argIndex = 2;
for (int r = 0; r < ratings.length; r++ ) {
for (int c = 0; column < ratings[r].length; c++){
ratings[r][c] = Integer.parseInt(args[argIndex]);
columnSums[c] += ratings[r][c];
argIndex++;
}
}
// array columnSums contains your results
}
I have changed your original code with a simpler version.
Let me know if you have problems understanding the solution.
public static void main(String[] args)
{
int row = Integer.parseInt(args[0]);
int col = Integer.parseInt(args[1]);
int arrayLength = row * col; // use a single dimension array, for simplicity
int[] ratings = new int[arrayLength]; // the array size is based on the rows and columns
// add data to the 'ratings' array
// This is not actually needed because the conversion can be done directly when the columns are summed up
for(int i = 0; i < arrayLength; i++)
{
ratings[i] = Integer.parseInt(args[i + 2]);
}
// sum up the columns using the % operator
int[] result = new int[col];
for(int i = 0; i < arrayLength; i++)
{
result[i % col] += ratings[i];
}
// print result
for(int i = 0; i < result.length; i++)
{
System.out.println(String.format("Movie %d rating is %d", i, result[i]));
}
}
PS: you are missing the validation around the String to int conversion and checks around the correctness of the user input

Java 2D arrays coin collection game from larger neigbouring cell

My issue is the following:
I have a 2D array of size n x m, entered on a single line. On the next n lines there are m number of elements, that fill the array. So far so good.
There is a pawn on the field that always starts at the only 0 on the field (assuming there is always one 0).
It can move up and down, right and left. It always moves to the neighbouring cell with most coins and at each move collects 1 coin (=> empties the visited cell by 1). The pawn does this until there are only 0s around it and it can collect nothing anymore. I need to find the sum of all coins collected.
Here is a representation of first steps in Paint:
Coin Collection first steps:
Sample input:
4 3, 3 2 4, 2 0 3, 1 1 5, 2 2 5 -> output: 22
Here is my code so far:
I have some unfinished work with the targetCell (I still wonder how to get its coordinates dynamically in a loop, so that each cell with a larger value than the previous turns to a targetCell.) Also I'm stuck with using the directions I just created. Any hints would be useful for me to further develop the task.
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
String[] my_array = input.split(" ");
int[] array = Arrays.stream(my_array).mapToInt(Integer::parseInt).toArray();
int n = array[0]; // rows of matrix
int m = array[1]; // cols of matrix
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++) {
String line = scanner.nextLine();
String[] numbers = line.split(" ");
matrix[i] = new int[m];
for (int j = 0; j < m; j++) {
matrix[i][j] = Integer.parseInt(numbers[j]);
}
}
int startPoint = 0;
int currentRow = 0;
int currentCol = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] == 0) {
startPoint = matrix[i][j];
currentRow = i;
currentCol = j;
}
}
}
int target1 = 0;
int target2 = 0;
int targetCell = 0;
target1 = Math.max(matrix[currentRow - 1][currentCol], matrix[currentRow + 1][currentCol]);
target2 = Math.max(matrix[currentRow][currentCol - 1], matrix[currentRow][currentCol + 1]);
targetCell = Math.max(target1, target2);
System.out.println(targetCell);
int hDirection = 1;
if (targetCol < currentCol) {
hDirection = -1;
}
int vDirection = 1;
if (targetRow < currentRow) {
vDirection = -1;
}
}
}
}
(Can't comment so will use an answer for now. Sorry)
My first thought would be to keep a global variable for the run so that when a coin is collected, it is added to its current value; similar to how you would keep score in games like Tetris. That's assuming I've read it right.
So something like:
private static int current_score = 0; //Assuming no use of objects so using static
Couldn't understand the sample input in this example. If you could give a three turn scenario of what the final score would be, I could give you better insight.

Storing digits of numbers in array

Hello fellow programmers !
I am a beginner with Java and i am looking for a method or a way maybe to store the digits of a 6 digit number entered by the user , in an int array.
For example :-
if the number is 675421.
then i want to store the digits in an array like :-
int[] array = new int[6];
int number = 675421
array[0] = 6;
array[1] = 7;
array[2] = 5;
array[3] = 4;
array[4] = 2;
array[5] = 1;
I want to do so so that i can work with the array to maybe sort or change the order or numbers in array. Thanks!
Here you go,
String temp = Integer.toString(number);
int[] num = new int[temp.length()];
for (int i = 0; i < temp.length(); i++){
num[i] = temp.charAt(i) - '0';
}
for (int i = 0; i < temp.length(); i++) {
System.out.println(num[i]);
}
Edit, after comment
Here, First, you are converting to your number to a string.
Then, take each char out of it(in the loop), subtract the ASCII value of 0 from each char to get the digit [ie, ASCII of 0 is 48, 1 is 49, ... ] (see ASCII table)
Do something like this:
String number = "123123";
int[] intArray = new int[number.length()];
for (int i = 0; i < number.length(); i++)
{
intArray[i] = Integer.parseInt(Character.toString(number.charAt(i)));
}
Hope this helps,
Jason.
Below is the recursive solution
public static void main(String[] args) {
int testNum = 675421;
List<Integer> digitList = new ArrayList<Integer>();
collectDigits(testNum, digitList);
Object[] resultArr = digitList.toArray();
int listSize = resultArr.length;
for (int listCount = 0; listCount < listSize; listCount++) {
System.out.println("result["+listCount+"] = "+resultArr[listCount]);
}
}
private static void collectDigits(int num, List<Integer> digits) {
if (num / 10 > 0) {
collectDigits(num / 10, digits);
}
digits.add(num % 10);
}
One way to do this would be to turn the original integer into a string.
Loop over the string, parsing each character back to an int, and place into the array. Here is an example:
int number = 123456;
String strNumber = number+"";
int[] array = new int[strNumber.length()];
int index = 0;
for(char c : strNumber.toCharArray()){
array[index++] = Integer.parseInt(c+"");
}
System.out.println(Arrays.toString(array));
Math solution, you can split the int number using this:
int[] array = new int[6];
int number = 675421;
array[0] = ((number/100000)%10);
array[1] = ((number/10000)%10);
array[2] = ((number/1000)%10);
array[3] = ((number/100)%10);
array[4] = ((number/10)%10);
array[5] = ((number/1)%10);
If the "number" has a variable length you can automate this, write a coment if you need help

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;
}

The Sum of large Integers using Arrays

I am trying to write a program that sums up the total of two large numbers. I used two arrays for the numbers to sum up and the third array to store the result of the summation, But I am getting the wrong output, would you check?
Here is my method:
public static int [] sumBigInt(int [] A, int [] B, int n)
{
int sumPerCol = 0;
int carriedValue = 0;
int[] totalArray = new int[A.length + 1];
for(int i = A.length - 1; i >= 0; i--)
{
sumPerCol = A[i] + B[i] + carriedValue;
if( i == 0)
totalArray[i] = carriedValue;
else if(sumPerCol >= 10)
{
carriedValue = sumPerCol / 10;
totalArray[i] = sumPerCol % 10;
}
else
{
totalArray[i] = sumPerCol;
carriedValue = 0;
}
}// end of for-Loop
return totalArray;
}
**** In main, I am not getting the correct output:
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(TwoTo_n(8));
int[] arrayA = {6,9,4,6,9,1,8,9,3,5,6};
int[] arrayB = {5,9,6,4,3,1,6,7,6,9,5};
int[] arrayTest = new int[arrayA.length + 1];
for (int i = 0; i < arrayTest.length; i++)
arrayTest[i] = sumBigInt(arrayA, arrayB, 14)[i];
for (int i = 0; i < arrayTest.length; i++)
System.out.print(arrayTest[i] + " ");
}
Here is the output I get :
1 9 1 1 2 3 5 7 0 5 1 0
The output should be:
1 2 9 1 1 2 3 5 7 0 5 1 => now the digit in position 1 disappears :(
There is ONE digit missing; that digit should be added at position zero in my final array, but its not showing up.
Thank you
Your code is almost correct. In order to fix it, think what happens to carriedValue after you finish the loop:
When the loop ends, and carriedValue is zero, your program returns the correct value
When the loop ends, and carriedValue is one, the most significant digit of the result gets dropped.
All you need to do to fix this is to "shift" digit positions in your totalArray by one, and assign carriedValue to the top digit after the end of the loop:
for(int i = A.length - 1; i >= 0; i--) {
sumPerCol = A[i] + B[i] + carriedValue;
if(sumPerCol >= 10) {
carriedValue = sumPerCol / 10;
totalArray[i+1] = sumPerCol % 10;
} else {
totalArray[i+1] = sumPerCol;
carriedValue = 0;
}
}// end of for-Loop
totalArray[0] = carriedValue;
Note the use of totalArray[i+1] in place of totalArray[i]. This is because your method automatically extends the number of significant digits by one. You could change this behavior by re-allocating the array and copying data into it only when carriedValue is non-zero.
Demo.

Categories