I have an array of 5 integers, from 1 to 5. My destination tells me that I need to determine at least one element in the array is greater than zero. Only if all the elements are empty, I would say that var isEmpty is true and then returns a value.
The code:
public static bool is_empty(int[] S, int n) { bool isEmpty = false; for (int i = 0; i < n; i++) { if (S[i] != 0) { isEmpty = false; } else { isEmpty = true; } } return isEmpty; }
Your code does not work as it only considers the last element in the loop element. Try this: return that the array is not empty if you find a non-empty element; otherwise return that all elements are empty:
public static bool is_empty(int[] S, int n) { for (int i = 0; i < n; i++) { if (S[i] > 0) // negative values still count towards "being empty" return false; } return true; }
, n. . foreach .
static bool IsEmpty(int[] S) { foreach (int x in S) { if (x != 0) { return false; //If any element is not zero just return false now } } return true; //If we reach this far then the array isEmpty }
, you don't need variables , bool isEmpty, LINQ, , , , .
you don't need variables
isEmpty
, " , , ". , , . :
for (int i = 0; i < n; i++) { if (S[i] != 0) { return false; } } return true;
bool isEmpty = false; int count = 0; for(int i=0;i<n;i++){ if(S[i] == 0){ count++; } } isEmpty = (count==n);
S.Any(x => x != 0);
true, 0.
, All , .
S.All(x => x == 0);
public static bool is_empty(int[] S) { // return true if no element is 0 return !S.Any(x => x != 0); // or use return S.All(x => x == 0); }
it’s even better not to create this method, since you can directly call this operator from where you call this method (if its call is not called from several places).
Source: https://habr.com/ru/post/1583863/More articles:Where in the page life cycle is the main page load event (not OnLoad and Page_Load)? - asp.netloading multiple properties using a configuration server - spring-cloudhttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1583860/djangodbutilsoperationalerror-1071-specified-key-was-too-long-max-key-length-is-767-bytes&usg=ALkJrhjfacvE0n5kl22OlhW9xCZIVCm2jQDocker: Nginx & PHP Container: нет такого файла или каталога - phpInherited from Set.prototype - javascriptlogstash output to a file and ignores the codec - fileDoes a Javascript object property, available through parentheses, assign a different property value? - javascriptКак уничтожить карусель Bootstrap для мобильных решений - javascriptЗагрузите содержимое некоторого файла в Firefox SDK main.js - javascriptcomponent branch origin and local synchronization after reinstallation - gitAll Articles