Как найти минимальный элемент в каждой строке

Вы же используете numpy. Ну так и воспользуйтесь его инструментарием:

import numpy as np

a=np.array ([[0, 2.4, -6, 5, 0.8], 
             [1.5, 0, 0, -4.3, -3.5], 
             [0, 1.8, 3.2, -1.2, -1.3],
             [0, 0, -2.3, 0, -7.2],
             [3.3, -0.8, 0, 3.5, 8]])
res = a.min(axis=1)
print(res)

[-6. -4.3 -1.3 -7.2 -0.8]

параметр axis указывает, где искать минимумы — 0 — строки, 1 — столбцы

0 / 0 / 0

Регистрация: 10.12.2011

Сообщений: 36

1

В каждой строке матрицы найти минимальный элемент

31.05.2012, 19:42. Показов 41076. Ответов 6


Студворк — интернет-сервис помощи студентам

Дана матрица размера M × N. В каждой строке матрицы найти минимальный элемент



0



AAA-

14 / 14 / 5

Регистрация: 14.02.2012

Сообщений: 46

31.05.2012, 20:18

2

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
int main()
{  setlocale(0,"rus");
   srand(time(0));
   int matrix[100][100];
   int mass[100];
   int M,N;
   cout<<"Введите кол-во строк: ";
   cin>>M;
   cout<<"Введите кол-во столбцов: ";
   cin>>N;
   for(int i=0;i<M;i++){
       int count=0;
       if(i%M)
           cout<<endl;
       for(int j=0;j<N;j++){
           matrix[i][j]=rand()%100;
           cout<<matrix[i][j]<<" ";}
   }
  int min=matrix[0][0];
  for(int i=0;i<M;i++){
      int min=matrix[i][0];
      for(int j=0;j<N;j++){
          if(matrix[i][j]<min)
              min=matrix[i][j];}
          mass[i]=min;}
  
  cout<<endl<<endl;
  for(int i=0;i<M;i++)
      cout<<mass[i]<<" ";
   cout<<endl;
    return 0;
}



2



HappyAndRu

13 / 13 / 7

Регистрация: 19.05.2012

Сообщений: 46

31.05.2012, 21:02

3

вот мой вариант:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <cstdlib>
#include <time.h>
 
using namespace std;
 
int main ()
{ 
    srand(time(NULL));
    
    int m,n,min;
    cout << "M: ";
    cin >> m;
    cout << "N: ";
    cin >> n;
    int aMN[m][n];
    
    for (int i=0; i<m; i++)
    {
        for (int j=0; j<n; j++)
        {
            aMN[i][j]=rand()%201-100;
            if (j==0)
               min=aMN[i][j];
            else if (min>aMN[i][j])
               min=aMN[i][j];  
            cout << " " << aMN[i][j];
        }
    cout << " (" << min << ")" << endl;
    }
 
    system("pause");
    return 0;
}



1



DanilAREFY

19 / 19 / 6

Регистрация: 12.04.2011

Сообщений: 35

31.05.2012, 21:55

4

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
 
using namespace std;
 
int const nX=5, nY=10;
 
int search(int, int nArr[nX][nY]);
void input(int nArr[nX][nY]);
void output(int nArr[nX][nY]);
 
int main(void)
{
    int nArray[nX][nY];
    input(nArray);
    output(nArray);
    for(int nI=0; nI<nX; nI++)
    {
        cout << "Minimum: "
            << search(nI, nArray)
            << endl;
    }
    system("pause");
    return 0;
}
 
void input(int nArr[nX][nY])
{
    for(int nI=0; nI<nX; nI++)
    {
        for(int nJ=0; nJ<nY; nJ++)
        {
            cin >> nArr[nI][nJ];
        }
    }
}
 
int search(int nI, int nArr[nX][nY])
{
    int temp=1000;
    for(int nJ=0; nJ<nY; nJ++)
    {
        if(nArr[nI][nJ]<temp)
        {
            temp=nArr[nI][nJ];
        }
    }
    return temp;
}
 
void output(int nArr[nX][nY])
{
    for(int nI=0; nI<nX; nI++)
    {
        for(int nJ=0; nJ<nY; nJ++)
        {
            cout << nArr[nI][nJ]
                << " "; 
        }
        cout << endl;
    }
}



1



alkagolik

Заблокирован

31.05.2012, 22:33

5

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <array>
#include <cstdlib>
#include <ctime>
#include <iomanip>
 
using namespace std;
 
int main() {
 
    const size_t s = 6;
    size_t iter = 0;
    array< array< size_t, s >, s > matr;
    array< size_t, s > min;
 
    min.fill( 0xffffffff );
    srand( time( 0 ) );
 
    for ( size_t i = 0; i < s; ++i ) {
        for ( size_t j = 0; j < s; ++j ) {
            matr.at(i).at(j) = rand() % ( s * s );
            if ( min.at(i) > matr.at(i).at(j) )
                min.at(i) = matr.at(i).at(j);
            cout << hex << setw( 3 ) << matr.at(i).at(j);
        }
        cout << endl;
    }
    
    cout << endl;
    for ( auto it = min.begin(); it != min.end(); ++it )
        cout << hex << setw( 3 ) << min.at(iter++);
    cout << endl;
 
    return 0;
}



1



MrGluck

Форумчанин

Эксперт CЭксперт С++

8194 / 5044 / 1437

Регистрация: 29.11.2010

Сообщений: 13,453

01.06.2012, 01:02

6

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <algorithm>
#include <iterator>
#include <random>
 
int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> uid(0, 99); 
    const std::size_t M = 10, N = 15;
    int arr[M][N];
    std::for_each(arr, arr + M, [&uid, &gen](int* pvalue)
    {
        std::generate(pvalue, pvalue + N, [&uid, &gen] {return uid(gen); } );
        std::copy(pvalue, pvalue + N, std::ostream_iterator<int> (std::cout, " ") ); 
        std::cout<< "Min: "<< *std::min_element(pvalue, pvalue + N)<< std::endl; 
    } );
    return 0;
}



1



Aniotri

0 / 0 / 0

Регистрация: 22.12.2020

Сообщений: 2

01.01.2021, 21:59

7

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <limits.h>
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
 
int main(int argc, char* argv[]){
    int m, n;
    std::cin >>m>>n;
    float M[m][n];
    int i, j=0, t;
    for (int i = 0; i < m; i++){
        for (int j = 0; j < n; j++){
        
           std:: cin>> M[i][j];
        }
    }
 
    int arr[m];
 
    for (int i=0, mini; i<m; i++){
        mini = INT_MAX;
        for (int j=0; j<n; j++)
            if (M[i][j]<mini) mini = M[i][j];
        arr[i] = mini;
    }
 
    printf("n");
 
    for (int i=0; i<m; i++)
        printf ("%dt",arr[i]);
 
    printf("n");
        system("pause");
 
    return 0;
}



0



Given a matrix, the task is to find the minimum element of each row and each column.

Examples: 

Input: [1, 2, 3]
        [1, 4, 9]
        [76, 34, 21]
Output: Minimum element of each row is {1, 1, 21}
Minimum element of each column is {1, 2, 3}

Input: [1, 2, 3, 21]
       [12, 1, 65, 9]
       [11, 56, 34, 2]
Output: Minimum element of each row is {1, 1, 2}
Minimum element of each column is {1, 2, 3 , 2}

Approach: The idea is to run the loop for no_of_rows. Check each element inside the row and find for the minimum element. Finally, print the element. Similarly, check each element inside the column and find for the minimum element. Finally, print the element.

Below is the implementation of the above approach:

C++

#include<bits/stdc++.h>

using namespace std;

const int MAX = 100;

void smallestInRow(int mat[][MAX], int n, int m)

{

    cout << " { ";

    for (int i = 0; i < n; i++) {

        int minm = mat[i][0];

        for (int j = 1; j < m; j++) {

            if (mat[i][j] < minm)

                minm = mat[i][j];

        }

        cout << minm << ", ";

    }

    cout << "}";

}

void smallestInCol(int mat[][MAX], int n, int m)

{

    cout << " { ";

    for (int i = 0; i < m; i++) {

        int minm = mat[0][i];

        for (int j = 1; j < n; j++) {

            if (mat[j][i] < minm)

                minm = mat[j][i];

        }

        cout << minm << ", ";

    }

    cout << "}";

}

int main()

{

    int n = 3, m = 3;

    int mat[][MAX] = { { 2, 1, 7 },

                       { 3, 7, 2 },

                       { 5, 4, 9 } };

    cout << "Minimum element of each row is ";

    smallestInRow(mat, n, m);

    cout << "nMinimum element of each column is ";

    smallestInCol(mat, n, m);

    return 0;

}

C

#include <stdio.h>

#define MAX 100

void smallestInRow(int mat[][MAX], int n, int m)

{

  printf(" { ");

  for (int i = 0; i < n; i++) {

    int minm = mat[i][0];

    for (int j = 1; j < m; j++) {

      if (mat[i][j] < minm)

        minm = mat[i][j];

    }

    printf("%d, ",minm);

  }

  printf("}");

}

void smallestInCol(int mat[][MAX], int n, int m)

{

  printf(" { ");

  for (int i = 0; i < m; i++) {

    int minm = mat[0][i];

    for (int j = 1; j < n; j++) {

      if (mat[j][i] < minm)

        minm = mat[j][i];

    }

    printf("%d, ",minm);

  }

  printf("}");

}

int main()

{

  int n = 3, m = 3;

  int mat[][MAX] = { { 2, 1, 7 },

                    { 3, 7, 2 },

                    { 5, 4, 9 } };

  printf("Minimum element of each row is ");

  smallestInRow(mat, n, m);

  printf("nMinimum element of each column is ");

  smallestInCol(mat, n, m);

  return 0;

}

Java

public class GFG {

    final static int MAX = 100;

    static void smallestInRow(int mat[][], int n, int m) {

        System.out.print(" { ");

        for (int i = 0; i < n; i++) {

            int minm = mat[i][0];

            for (int j = 1; j < m; j++) {

                if (mat[i][j] < minm) {

                    minm = mat[i][j];

                }

            }

            System.out.print(minm + ", ");

        }

        System.out.println("}");

    }

    static void smallestInCol(int mat[][], int n, int m) {

        System.out.print(" { ");

        for (int i = 0; i < m; i++) {

            int minm = mat[0][i];

            for (int j = 1; j < n; j++) {

                if (mat[j][i] < minm) {

                    minm = mat[j][i];

                }

            }

            System.out.print(minm + ", ");

        }

        System.out.print("}");

    }

    public static void main(String args[]) {

        int n = 3, m = 3;

        int mat[][] = {{2, 1, 7},

        {3, 7, 2},

        {5, 4, 9}};

        System.out.print("Minimum element of each row is ");

        smallestInRow(mat, n, m);

        System.out.print("nMinimum element of each column is ");

        smallestInCol(mat, n, m);

    }

}

Python3

MAX = 100

def smallestInRow(mat, n, m):

    print("{", end = "")

    for i in range(n):

        minm = mat[i][0]

        for j in range(1, m, 1):

            if (mat[i][j] < minm):

                minm = mat[i][j]

        print(minm, end = ",")

    print("}")

def smallestInCol(mat, n, m):

    print("{", end = "")

    for i in range(m):

        minm = mat[0][i]

        for j in range(1, n, 1):

            if (mat[j][i] < minm):

                minm = mat[j][i]

        print(minm, end = ",")

    print("}")

if __name__ == '__main__':

    n = 3

    m = 3

    mat = [[2, 1, 7],

           [3, 7, 2 ],

           [ 5, 4, 9 ]];

    print("Minimum element of each row is",

                                 end = " ")

    smallestInRow(mat, n, m)

    print("Minimum element of each column is",

                                    end = " ")

    smallestInCol(mat, n, m)

C#

using System;

class GFG

{

readonly static int MAX = 100;

static void smallestInRow(int [,]mat,

                          int n, int m)

{

    Console.Write(" { ");

    for (int i = 0; i < n; i++)

    {

        int minm = mat[i, 0];

        for (int j = 1; j < m; j++)

        {

            if (mat[i, j] < minm)

            {

                minm = mat[i, j];

            }

        }

        Console.Write(minm + ", ");

    }

    Console.WriteLine("}");

}

static void smallestInCol(int [,]mat,

                          int n, int m)

{

    Console.Write(" { ");

    for (int i = 0; i < m; i++)

    {

        int minm = mat[0, i];

        for (int j = 1; j < n; j++)

        {

            if (mat[j, i] < minm)

            {

                minm = mat[j, i];

            }

        }

        Console.Write(minm + ", ");

    }

    Console.Write("}");

}

public static void Main()

{

    int n = 3, m = 3;

    int [,]mat = {{2, 1, 7},

                   {3, 7, 2},

                  {5, 4, 9}};

    Console.Write("Minimum element of " +

                         "each row is ");

    smallestInRow(mat, n, m);

    Console.Write("nMinimum element of " +

                        "each column is ");

    smallestInCol(mat, n, m);

}

}

PHP

<?php

$MAX = 100;

function smallestInRow(&$mat, $n, $m)

{

    echo " { ";

    for ($i = 0; $i < $n; $i++)

    {

        $minm = $mat[$i][0];

        for ($j = 1; $j < $m; $j++)

        {

            if ($mat[$i][$j] < $minm)

                $minm = $mat[$i][$j];

        }

        echo $minm . ", ";

    }

    echo "}";

}

function smallestInCol(&$mat, $n, $m)

{

    echo " { ";

    for ($i = 0; $i < $m; $i++)

    {

        $minm = $mat[0][$i];

        for ($j = 1; $j < $n; $j++)

        {

            if ($mat[$j][$i] < $minm)

                $minm = $mat[$j][$i];

        }

        echo $minm . ", ";

    }

    echo "}";

}

$n = 3;

$m = 3;

$mat = array(array( 2, 1, 7 ),

             array( 3, 7, 2 ),

             array( 5, 4, 9 ));

echo "Minimum element of each row is ";

smallestInRow($mat, $n, $m);

echo "nMinimum element of each column is ";

smallestInCol($mat, $n, $m);

?>

Javascript

<script>

let MAX = 100;

    function smallestInRow(mat,n,m) {

        document.write(" { ");

        for (let i = 0; i < n; i++) {

            let minm = mat[i][0];

            for (let j = 1; j < m; j++) {

                if (mat[i][j] < minm) {

                    minm = mat[i][j];

                }

            }

            document.write(minm + ", ");

        }

        document.write("}"+"<br>");

    }

    function smallestInCol(mat,n,m) {

        document.write(" { ");

        for (let i = 0; i < m; i++) {

            let minm = mat[0][i];

            for (let j = 1; j < n; j++) {

                if (mat[j][i] < minm) {

                    minm = mat[j][i];

                }

            }

            document.write(minm + ", ");

        }

        document.write("}");

    }

        let n = 3, m = 3;

        let mat = [[2, 1, 7],

        [3, 7, 2],

        [5, 4, 9]];

        document.write("Minimum element of each row is ");

        smallestInRow(mat, n, m);

        document.write("nMinimum element of each column is ");

        smallestInCol(mat, n, m);

</script>

Output

Minimum element of each row is  { 1, 2, 4, }
Minimum element of each column is  { 2, 1, 2, }

Complexity Analysis:

  • Time complexity: O(n*m), as we are using nested for loops to traverse the Matrix.
  • Auxiliary Space: O(1), as we are not using any extra space.

Last Updated :
09 Sep, 2022

Like Article

Save Article

Matrix23. Дана матрица размера $$M times N$$. В каждой строке матрицы найти минимальный элемент.

Решение:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

program Matrix23;

var

  a:array [1..10,1..10] of integer;

  Min,M, N, i, j:Integer;

begin

Write(‘N: ‘);

Readln(N);

Write(‘M: ‘);

Readln(M);

for  i:=1 to M do

  begin

   writeln(i,‘: ‘);

   for j:=1 to N do

    begin

     Write(j,‘ : ‘);

     Read(a[i,j]);

    end;

  end;

for  i:=1 to M do

  begin

   writeln(i,‘: ‘);

   Min:=a[i,1];

   for j:=2 to N do

    begin

     if a[i,j]<Min then Min:=a[i,j];

    end;

   writeln(‘Минимальный элемент:’,Min);

  end;

end.

Другие задачи из раздела Matrix можно посмотреть здесь.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
           Console.WriteLine("Введите размерность матрецы n m = ");
            int m =  Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("n n = ");
            int n = Convert.ToInt32(Console.ReadLine());
            // Объявляем двумерный массив
            int[,] matrix = new int[m, n];
 
            Random ran = new Random();
 
            // Инициализируем данный массив
            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    matrix[i, j] = ran.Next(1, 15);
                    Console.Write("{0}t", matrix[i, j]);
                }
                Console.WriteLine();
            }
 
            Console.WriteLine("nМинимальное значение в строках: ");
            for (int i = 0; i < m; i++)
            {
                int minLine = matrix[i, 0];
                for (int j = 0; j < n; j++)
                {
                    if (matrix[i, j] < minLine)
                    {
                        minLine = matrix[i, j];
                    }                   
                }
                Console.WriteLine("Строка {0}, значение: {1}", i, minLine);
                Console.WriteLine();
            }
 
            Console.ReadKey();
        }
    }
}

Понравилась статья? Поделить с друзьями:
  • Как найти улиц в париже
  • Как найти домашний wifi
  • Как найти талла тихоню
  • Как найти узника освенцима
  • Как исправить пересоленное вареное мясо