esercizi sull array

Blog Forum Java esercizi sull array

  • Il topic è vuoto.
Stai visualizzando 2 post - dal 1 a 2 (di 2 totali)
  • Autore
    Post
  • #5570
    luigi corvasce
    Ospite
    Up
    0
    Down
    ::

    salve professor Pagano, sto riscontrando difficoltà nella risoluzione del seguente esercio:
    “1. Scrivere un programma Java per verificare se un dato array contiene un sottoarray con somma 0.

    Esempio:
    Ingresso:
    nums1 = {1, 2, -2, 3, 4, 5, 6}
    nums2 = {1, 2, 3, 4, 5, 6}
    nums3 = {1, 2, -3, 4, 5, 6}
    Produzione:
    Il suddetto array contiene un sottoarray con 0 sum: true
    Il suddetto array contiene un sottoarray con 0 sum: false
    Il suddetto array contiene un sottoarray con 0 sum: true”.
    sono giorni che provo a venirne a capo. Grazie mille per la risposta.

    #5575
    ANTONIO PAGANO
    Ospite
    Up
    0
    Down
    ::

    Buongiorno,
    una possibile soluzione è la seguente:

    	public static void main(String[] args) {
    		// int[] tmp = {1, 2, -2, 3, 4, 5, 6};
    		// int[] tmp = {1, 2, 3, 4, 5, 6};
    		int[] tmp = { 1, 2, -3, 4, 5, 6 };
    
    		boolean trovato = false;
    		for (int i = 0; i < tmp.length; i++) {
    			int curr_sum = 0;
    
    			// try all subarrays starting with 'i'
    			for (int j = i; j < tmp.length; j++) {
    				curr_sum = curr_sum + tmp[j];
    
    				if (curr_sum == 0) {
    					trovato = true;
    
    				}
    
    			}
    		}
    		System.out.print("Il suddetto array contiene un sottoarray con 0 sum: " + trovato);
    
    	}
    
Stai visualizzando 2 post - dal 1 a 2 (di 2 totali)
  • Devi essere connesso per rispondere a questo topic.