How to find the total of an 2d array? - java

Have to input numbers of students & subjects. (Using random marks) I want to print the total marks of students & the total marks of subjects. Here is the code given below.
import java.util.*;
class Example{
public static void readMarks(int[][] x){
Random r=new Random();
for(int i=0; i<x.length; i++){
for(int j=0; j<x[i].length; j++){
x[i][j]=r.nextInt(101);
}
}
}
public static void printMarks(int[][] x){
for(int i=0; i<x.length; i++){
for(int j=0; j<x[i].length; j++){
System.out.print(x[i][j]+" ");
}
System.out.println();
}
}
public static int[] findStudenTot(int[][] x){
int tot[]=new int[x.length];
for(int i=0; i<x.length; i++){
for (int j = 0; j<x[i].length; j++){
tot[i]+=x[i][j];
}
}
return tot;
}
public static int[] findSubjectTot(int[][] x){
int tot1[]=new int[x.length];
for(int i=0; i<x.length; i++){
for (int j = 0; j<x[i].length; j++){
tot1[i]+=x[i][j];
}
}
return tot1;
}
public static void main(String args[]){
Scanner input=new Scanner(System.in);
System.out.print("Input no of students : ");
final int N=input.nextInt();
System.out.print("Input no of subject : ");
final int S=input.nextInt();
int[][] marks=new int[N][S];
readMarks(marks);
int[] stTotal=findStudenTot(marks);
int[] subTotal=findSubjectTot(marks);
System.out.println("total is : "+stTotal);
System.out.println("total is : "+subTotal);
}
}
How to print stTotal , subTotal?
If we assume enter 5 for both inputs this output total is : [I#3d4eac69 ...why?
what are these characters & how can I avoid these?

How to print stTotal , subTotal?
Do it as follows:
System.out.println("total is : " + Arrays.toString(stTotal));
System.out.println("total is : " + Arrays.toString(subTotal));
[Update]
Replace the definition of findSubjectTot with the following:
public static int[] findSubjectTot(int[][] x) {
int tot[] = new int[x[0].length];
for (int i = 0; i < x[0].length; i++) {
for (int j = 0; j < x.length; j++) {
tot[i] += x[j][i];
}
}
return tot;
}

i think the issue lies in findStudentTot Method, you seem to have return type of 2D array but is returning a 1D array so this should solve it
public static int[] findStudenTot(int[][] x){
int tot[]=new int[x.length];
for(int i=0; i<x.length; i++){
for (int j = 0; j<x[i].length; j++){
tot[i]+=x[i][j];
}
}
return tot;
}

Not certain what you want but try this. Change int[][] to int[] as the return type.
public static int[] findStudenTot(int[][] x){
int tot[]=new int[x.length];
// rest of code here.

Related

How to print only distinct integer values once even though they are repeated multiple times

I am trying to print only distinct integer values once even though they are repeated multiple times in an array with the introduced order. Firstly, I need to take array size from user but I cannot determine how to initialize that variable.Can I use n -inclueded in the code- as an array size variable? When I compiled I doesn't print anything. Where are my mistakes, and how to deal with them? Any idea?
public static void uniqueNumbers(int arr[], int n)
{
for (int i=0; i<n; i++)
{
for (int j =0; j<i;j++)
{
if (arr [i]==arr[j])
break;
if (i==j)
System.out.print(arr[i] + " ");
}
}
}
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int n =sc.nextInt();
int arr [] = new int [n];
uniqueNumbers(arr,n);
}
}
You need to fill the array,that is, you need to take input for the array elements.
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
int n =sc.nextInt();
int arr [] = new int [n];
//Add the following lines.
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
uniqueNumbers(arr,n);
}
Print the array and try your logic again.
you need to first request for the size of the array as shown below:
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter array size");
int n =scan.nextInt();
// declaring and creating array objects
int[] arr = new int[n];
// displaying default values
System.out.println("Default values of array:");
for (int i=0; i < arr.length; i++) {
System.out.print(arr[i]+"\t");
}
// initializing array
System.out.println("\n\n***Initializing Array***");
System.out.println("Enter "+ arr.length
+ " integer values:");
for(int i=0; i < arr.length; i++) {
// read input
arr[i] = scan.nextInt();
}
uniqueNumbers(arr, n);
}
public static void uniqueNumbers(int[] arr, int n) {
int slow = 1;
for (int fast = 1; fast < n; fast++) {
if (arr[fast] != arr[slow - 1]) {
arr[slow++] = arr[fast];
}
}
arr = Arrays.copyOf(arr, slow);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}

the java code is not able to take last test case as input

Given a number K and string S of digits denoting a positive integer, build the largest number possible by performing swap operations on the digits of S atmost K times.
import java.util.Scanner;
public class competitive {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int t=s.nextInt();
while(t>0){
t--;
int n=s.nextInt();
//taking input
String number=s.next();
int l=number.length();
char[] num=new char[l];
// spliting into char
for(int i=0; i<l; i++) {
num[i] = number.charAt(i);
}
//converting into integer
int[] nm=new int[l];
for(int i=0; i<l; i++){
nm[i]=Character.getNumericValue(num[i]);
}
int[] nm2=new int[l];
for(int i=0; i<l; i++){
nm2[i]=nm[i];
}
for(int i=0; i<l; i++){
for(int j=i+1; j<l; j++){
if(nm[i]<nm[j]) {
int temp =nm[i];
nm[i]=nm[j];
nm[j]=temp;
}
}
}
int x=0;
//sorting
for(int i=0; i<n; i++){
for(int j=0; j<l; j++){
if(nm[i]==nm2[j] && j>x){
int temp=nm2[j];
nm2[j]=nm2[x];
nm2[x]=temp;
x++;
break;
}
}
}
for(int i=0; i<l; i++){
System.out.print(nm2[i]);
}
System.out.print("\n");
}
}
}
3
4
1234567
3
3435335
2
1034
it is not taking input 1034
how to clear the error.
i don't know but this error is coming for a long time and i am not able to figure out why

How stop array input limit then the result to show the output?

I have a question about stop array input limit then the result to show the output.
Below is my coding have already set new float[3][3]:
import java.util.Scanner;
public class Clone2Darray {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println ("Type nine float numbers two-dimensional array of similar type and size with line breaks, end by -1:");
float[][] a = new float[3][3];
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
The limit output is show me like below:
run:
Type float numbers in the two-dimensional array of similar type and size
with line breaks, end by -1:
5.33
9.33
63.33
6.36
3.55
7.25
2.33
3.66
The result is:
6.33 5.33 9.33
63.33 6.36 3.55
7.25 2.33 3.66
BUILD SUCCESSFUL (total time: 31 seconds)
My problem is want to stop limit float[3][3] and can unlimited key in the input until type -1 to stop the input. May I know how to remove the limit float[3][3] in the array? Hope anyone can guide me to solve my problem. Thanks.
At the point when you allocate memory for the two-dimensional array you have to tell the sizes of its elements, because memory will be allocated for that array and the amount of memory to be allocated must be known.
You can bypass this, by using some more dynamic types, like List and its popuplar implementation, ArrayList, even in a nested form. That's a nice thing to do, but then you will not have a "real" array.
The below code allows you to create the dynamic arrays.
import java.util.Scanner;
public class Clone2DArray {
public static float[][] clone(float[][] a) throws Exception {
float b[][] = new float[a.length][a[0].length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[i][j] = a[i][j];
}
}
return b;
}
public static void main(String args[]) {
Scanner sc = new Scanner (System.in);
System.out.println("enter row size");
int row = Integer.parseInt(sc.nextLine());
System.out.println("enter column size");
int column = Integer.parseInt( sc.nextLine());
System.out.println ("Type float numbers two-dimensional array of similar type and size with line breaks:");
float[][] a = new float[row][column];
for (int i=0; i<row; i++){
for (int j=0; j<column; j++){
String line = sc.nextLine();
if ("-1".equals(line)){
break;
}
a[i][j]=Float.parseFloat(line);
}
}
System.out.println("\n The result is:");
try {
float b[][] = clone(a);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}

when compile this code only show scores of last input

when compile this code only show scores of last input
import java.util.*;
public class TestII {
static Scanner key = new Scanner (System.in);
static int countNa = 0;
static int countSc = 0;
static int numSc;
static int numNa;
static int [] scores = null;
static String [] names = null;
public static void main(String[] args) {
System.out.println("How many name and scores");
System.out.print("N> ");
numNa = key.nextInt();
System.out.print("S> ");
numSc = key.nextInt();
names = new String [numNa];
scores = new int [numSc];
readNameScores( );
showNamesScores ();
}
public static void readNameScores (){
for (int i = 0; i < names.length; i++){
countNa++;
System.out.print("Name "+countNa+": ");
names [i] = key.next();
for (int j = 0; j < scores.length; j++){
countSc++;
if (countSc > scores.length){
countSc = 0;
countSc++;
}
System.out.print("\tScore "+countSc+": ");
scores [j] = key.nextInt();
}
}
}
public static void showNamesScores (){
System.out.println("");
for (int i = 0; i < names.length; i++){
System.out.print(names [i]+"\t");
for (int j = 0; j < scores.length; j++){
System.out.print(scores [j]+" ");
}
}
}
}
sample of output
How many name and scores
N> 2
S> 2
Name 1: max
Score 1: 2
Score 2: 4
Name 2: mike
Score 1: 3
Score 2: 2
max 3 2 mike 3 2
Your scores array is make to hold the scores of just a single name. You should change it to a 2D array.
static int [][] scores = null;
...
names = new String [numNa];
scores = new int [numNa][numSc];
...
public static void readNameScores (){
for (int i = 0; i < names.length; i++){
System.out.print("Name "+(i+1)+": ");
names [i] = key.next();
for (int j = 0; j < scores.length; j++){
System.out.print("\tScore "+(j+1)+": ");
scores[i][j] = key.nextInt();
}
}
}

How to resolve time-exceeded error(codechef) for stable-marraige?

I am trying to implement the stable marriage using lists and arrays. When i try to submit it on codechef it gives runtime exceeded errors.If someone could help but i want to use the very same data-structure i am using.
import java.util.*;
public class Main {
private int size;
private static LinkedList<Integer>[] menlist;
private static int[][] womatrix;
private static int[][] invwomatrix;
private static int[] womatch;
private static int[] menmatch;
public static void main(String[] args){
Scanner Input = new Scanner(System.in);
int TestCases = Input.nextInt();
while(TestCases-- > 0) {
int size = Input.nextInt();
womatrix=new int[size][size];
invwomatrix=new int[size][size];
menlist=new LinkedList[size];
womatch=new int[size];
menmatch=new int[size];
for(int i = 0; i < size; i++){
int temp=Input.nextInt();
for(int j = 0; j < size; j++)
{
womatrix[i][j] = Input.nextInt();
invwomatrix[i][womatrix[i][j]-1]=j+1;
}
}
for(int i = 0; i < size; i++){
int temp=Input.nextInt();
LinkedList<Integer> menpref = new LinkedList<Integer>();
for(int j = 0; j < size; j++)
{
int a=Input.nextInt();
menpref.add(a);
}
menlist[i]=menpref;
}
LinkedList<Integer> ll = new LinkedList<Integer>();
for(int i=0;i<size;i++){
womatch[i]=0;
menmatch[i]=0;
ll.add(i+1);
}
while((ll.isEmpty()!=true) || menlist[ll.getFirst()-1].isEmpty()!=true ){
int newman=ll.removeFirst();
//System.out.print("freeman "+newman+" "+menlist[newman-1].isEmpty()+"\n");
int women=(menlist[newman-1].removeFirst());
//System.out.print("highrank "+women+"intial_pair "+womatch[women-1]+"\n");
if(womatch[women-1]==0){
womatch[women-1]=newman;
menmatch[newman-1]=women;
//int a=ll.removeFirst();
}
else{
int oldman=womatch[women-1];
if(invwomatrix[women-1][newman-1]<invwomatrix[women-1][oldman-1]){
womatch[women-1]=newman;
menmatch[newman-1]=women;
ll.addFirst(oldman);
}
else{
ll.addFirst(newman);
}
}
/*for(int i=0; i<this.size; i++) {
System.out.print((i+1)+" "+ menmatch[i] +"\n");
}*/
if(ll.isEmpty()==true){break;}
}
for(int k=0;k<size;k++){
System.out.print((k+1)+" "+menmatch[k] +"\n");
}
}
}
}

Categories

Resources