2011-09-23 9 views
2

2 차원 배열 내에서 가장 큰 숫자와 인덱스 위치를 인쇄하려고합니다. 가장 큰 번호를 찾을 수는 있지만 색인 위치를 인쇄하는 방법을 알아낼 수 없습니다. 어쨌든, 지금까지 내가 가지고있는 것은 다음과 같습니다.2 차원 배열에서 인덱스를 찾는 방법

public static void main(String[] args) { 
    int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}}; 

    double max = arr[0][0]; 
    for (int i = 0; i < arr.length; i++) { 
     for (int j = 0; j < arr.length; j++) { 
      if (arr[i][j] > max) { 
       max = arr[i][j]; 

      } 
     } 
    } 
    System.out.println(max); 
    System.out.println(i + j); //No idea what I should be doing here, just trying out everything I can think of 

답변

1

max를 업데이트 할 때마다 i, j를 저장하십시오.

1

2 차원 배열이 있으므로 두 인덱스를 모두 알아야합니다. 당신이 어느 것을 잃어 버리기 때문에 함께 추가하는 것은 불가능합니다. 어때요?

System.out.println("[" + i + "][" + j + "]"); 
3

지금 당장은 2 * arr.length를 최종 값으로 일관되게 가져야합니다. 그것은 아마도 당신이 찾고있는 것이 아닙니다. 최대 값의 좌표를 알고 싶습니다.

public static void main(String[] args) { 
    int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}}; 
    int tmpI = 0; 
    int tmpJ = 0; 
    double max = arr[0][0]; 
    // there are some changes here. in addition to the caching 
    for (int i = 0; i < arr.length; i++) { 
     int[] inner = arr[i]; 
     // caches inner variable so that it does not have to be looked up 
     // as often, and it also tests based on the inner loop's length in 
     // case the inner loop has a different length from the outer loop. 
     for (int j = 0; j < inner.length; j++) { 
      if (inner[j] > max) { 
       max = inner[j]; 
       // store the coordinates of max 
       tmpI = i; tmpJ = j; 
      } 
     } 
    } 
    System.out.println(max); 
    // convert to string before outputting: 
    System.out.println("The (x,y) is: ("+tmpI+","+tmpJ+")"); 
+0

고마워요. 나는 지난 두 시간 동안 놀랐다 ..... 나는 tmpI와 tmpJ와 비슷한 것을 실제로 시도했지만 잘 풀리지 않았다. 내가 한 일과 내가 한 일과 다른 점은 처음에는 값을 0으로 설정하지 않았다는 것입니다. – MNX1024

+0

@ MNX1024 우리 모두에게 일어납니다. – cwallenpoole

+0

코드를 편집하는 것을 깨달았습니다. 원래 네가 무엇을 찾고 있었는지. 여기에 게시 한 내용은 수정하고 다른 프로그램에서 사용하기 전에 올바르게 작동하는 코드를 얻으려는 테스트였습니다. 어쨌든 다른 질문이 있습니다. 이것을 메서드에 넣으면 i와 j를 하나의 return 문으로 반환하고 싶습니다. 가능한가? 그렇다면 어떻게해야합니까? – MNX1024

1

이 될 것입니다 당신이 편평한 배열로 하나의 인덱스를 원하는 경우 :

public static void main (String[] args) throws java.lang.Exception 
{ 
     int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}}; 
      int[] flattened = new int[6*3]; // based off above 
      int maxIndex = 0; 
      double max = arr[0][0]; 
      for (int i = 0; i < arr.length; i++) { 
       for (int j = 0; j < arr.length; j++) { 
        flattened[i + j] = arr[i][j]; 
        if (arr[i][j] > max) { 
         max = arr[i][j]; 
         maxIndex = i+j; 
        } 
       } 
     } 
    System.out.println(max); 
    System.out.println(flattened [maxIndex]); 
} 
0

돈이 작업을 수행하려면 인덱스의 값을 캐시 한 후 나중에 사용해야합니다 효과적인 알고리즘을 구현하는지 확신 할 수 없지만 max를 설정할 때 다른 변수에 인덱스 i, j를 저장하지 않는 이유는 무엇입니까? 이것은 매우 간단합니다.

if (arr[i][j] > max) { 
    max = arr[i][j]; 
    maxX = i; 
    maxY = j; 
} 

FYI 더 나은 구현을 원한다면 "삽입 정렬"알고리즘을 확인하십시오.

2

배열 크기에주의하십시오! 두 번째 for 문은 대부분 잘못되었습니다. 당신은 바로 화면을 인쇄 한 후 i와 j 함께 색인을 추가하고있어

for (int i = 0; i < arr.length; i++) { 
    for (int j = 0; j < arr[i].length; j++) { 
     if (arr[i][j] > max) { 
      max = arr[i][j]; 
      tmpI = i; tmpJ = j; 
     } 
    } 
} 
1
int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}}; 

int max = arr[0][0]; 
int maxI = 0, maxJ = 0; 

for (int i = 0; i < arr.length; i++) { 
    for (int j = 0; j < arr.length; j++) { 
     if (arr[i][j] > max) { 
      max = arr[i][j]; 
      maxI = i; 
      maxJ = j; 
     } 
    } 
} 
System.out.println(max); 
System.out.println(maxI + "," + maxJ); 
1
//C++ code 
#include<iostream> 
#include<vector> 
#include<algorithm> 
using namespace std; 
vector<int> b; 
vector<int> c; 
int Func(int a[][10],int n) 
{ 
    int max; 
    max=a[0][0]; 
    for(int i=0;i<n;i++) 
    { 
      for(int j=0;j<n;j++) 
      { 
        if(a[i][j]>max) 
        { 
            max=a[i][j]; 
            b.push_back(i); 
            c.push_back(j); 
            } 

        } 
        } 
        b.push_back(0); 
        c.push_back(0); 
        return max; 
        } 
    void display(int a[][10],int n) 
    { 
     for(int i=0;i<n;i++) 
    { 
      for(int j=0;j<n;j++) 
      { 
        cout<<a[i][j]<<"\t"; 
        } 
        cout<<endl; 
        } 
        } 

int main() 
{ 
    int a[10][10],n; 
    cin>>n; 
    for(int i=0;i<n;i++) 
    { 
      for(int j=0;j<n;j++) 
      { 
        cin>>a[i][j]; 
        } 
        } 
        cout<<endl; 
        display(a,n); 
        cout<<endl; 
        cout<<Func(a,n)<<" is the greatest "<<endl; 
        if(b.size()==1&&c.size()==1) 
        { 
              cout<<"Location is (1,1)"<<endl; 
              } 
              else 
              { 
               b.erase(b.end() - 1); 
               c.erase(c.end() - 1); 
        cout<<"Location is "<<"("<<b.back()+1<<","<<c.back()+1<<")"<<endl; 
        } 
        return 0; 
        } 
+0

나는 당신이 그를 더 혼란시키고 싶지 않다면 왜 자바 질문에 C++ 코드를 올렸는지 모르겠다. – sreya

+0

이것은 자바 질문이다. 장래에, 일반적인 개념이나 java로 java 질문에 대답하십시오. –

1

: 그것은 최대 에 도착 [I] .length로 이동합니다. 전체 루프를 돌면서 2 * arr.length-2와 같을 것입니다. 당신이해야 할 일은 새로운 최대 값을 만났을 때 i와 j의 값을 저장하는 것입니다. 예를 들어

:

int[][] arr = {{4, 44, 5, 7, 63, 1}, {7, 88, 31, 95, 9, 6}, {88, 99, 6, 5, 77, 4}}; 

int max = arr[0][0]; //dunno why you made it double when you're dealing with integers 
int max_row=0; 
int max_column=0; 
for (int i = 0; i < arr.length; i++) { 
    for (int j = 0; j < arr.length; j++) { 
     if (arr[i][j] > max) { 
      max = arr[i][j]; 
      max_row=i; 
      max_column=j; 

     } 
    } 
System.out.println("The max is: "+max+" at index ["+max_row+"]["+max_column+"]"); 
관련 문제