Przejdź do głównej zawartości

Posty

Wyświetlanie postów z luty, 2019

String-2 > repeatFront

Given a string and an int n, return a string made of the first n characters of the string, followed by the first n-1 characters of the string, and so on. You may assume that n is between 0 and the length of the string, inclusive (i.e. n >= 0 and n <= str.length()). repeatFront("Chocolate", 4) → "ChocChoChC" repeatFront("Chocolate", 3) → "ChoChC" repeatFront("Ice Cream", 2) → "IcI" Definiujemy zmienna newStr , loop reverse schodzimy od n do 0 i kazdy substring dodajemy do nwoego newStr public String repeatFront ( String str , int n ) { String newStr = "" ; for ( int i = n ; i >= 0 ; i --){ newStr += str . substring ( 0 , i ); } return newStr ; }

String-2 > mixString

Given two strings, a and b, create a bigger string made of the first char of a, the first char of b, the second char of a, the second char of b, and so on. Any leftover chars go at the end of the result. mixString("abc", "xyz") → "axbycz" mixString("Hi", "There") → "HTihere" mixString("xxxx", "There") → "xTxhxexre" Mix String: dwa stringi o roznej dlugosci Musimy przejsc loopem przez oba i zlozyc nowy string . aby miec pewnosc ze iterujemy po wszystkich char w stringu wybieramy dluzszy. Konieczne zadeklarowanie zmiennej String str ktora bedzie przechowywala kolejne char public String mixString ( String a , String b ){ String str = "" ; int len = 0 ; if ( a . length () >= b . length ()) { len = a . length (); } else len = b . length (); for ( int i = 0 ; i < len ; i ++) { if ( i

String-2 > xyBalance

We'll say that a String is xy-balanced if for all the 'x' chars in the string, there exists a 'y' char somewhere later in the string. So "xxy" is balanced, but "xyx" is not. One 'y' can balance multiple 'x's. Return true if the given string is xy-balanced. xyBalance("aaxbby") → true xyBalance("aaxbb") → false xyBalance("yaaxbb") → false Szukam char i rownego x, nastepnie musimy spwardzic czy po tym x jest y tj generujemy string i drugi warunek ten substring zaczyna sie od i w ktorym zostal odnotowany x i jedzie do konca szukajac y - jesli true to oba true jesli false wtedy false public boolean xyBalance ( String str ) { for ( int i = 0 ; i < str . length (); i ++){ if ( str . charAt ( i )== 'x' ){ if ( str . substring ( i + 1 , str . length ()). contains ( "y" )&& str . charAt ( str . length ()- 1 )!= 'x' ){

String-2 > xyzThere - java

Return true if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not.  xyzThere("abcxyz") → true xyzThere("abc.xyz") → false xyzThere("xyz.abc") → true Definiujemy loop ktory sprawdza za kazdym podejsciem czy kolejne indexy i,i+1 oraz i+2 i zdefiniowane dla nich char.  Nalezy tu pamietac ze jesli sprawdamy po indeksach np i+2 to tzreba zostawic "miejsce" na koncu aby nie bylo outOfBoudnExeption tj przekroczenia rlugosci stringa. Jezeli pierwszy warunek jest spelniony tj mamy na kolejnych indexach interesujace nas char-y sprawdzamy czy na poprzedzajacych nasza trojkę indexach pojawia sie "." zaczynamy od indexu 0 - tzreba to uwzglednić w warunku tj albo index 0 == 0 lub i-1 == 0 public boolean xyzThere ( String str ) { int len = str . length () - 2 ; for ( int i = 0 ; i < len ; i

Skrócony zapis if - instrukcja warunkowa java

Instrukcja warunkowa - warunek i rezultat. if (warunek) { jesli spełniony wykonań operacje i zwróć wynik; } warunek nie spełniony Możliwości skrócenia kodu instrukcji warunkowej if (i < 0) ? i-- : i++; Jeżeli i mniejsze od zera to i-- jezeli false to i++ if (i < 0) {     i--; } else {     i++; } Skrócony zapis instrukcji warunkowej else if (i < 0) ? i--;  inna_zmienna=4; : i++; if (i < 0) {     i--; } else {     i++;     inna_zmienna = 4; } Skrócony zapis if
Given a string, return a string where for every char in the original, there are two chars.  doubleChar("The") → "TThhee" doubleChar("AAbb") → "AAAAbbbb" doubleChar("Hi-There") → "HHii--TThheerree" Solution: easy public String doubleChar ( String str ) { String str1 = "" ; for ( int i = 0 ; i < str . length (); i ++) { str1 = str1 + str . charAt ( i ) + str . charAt ( i ); } return str1 ; } more complicated solution with Character.toString() - https://www.javatpoint.com/java-char-to-string for ( int i = 0 ; i < str . length (); i ++){ String strChar = Character . toString ( str . charAt ( i ))+ Character . toString ( str . charAt ( i )); System . out . print ( strChar ); }
Your cell phone rings. Return true if you should answer it. Normally you answer, except in the morning you only answer if it is your mom calling. In all cases, if you are asleep, you do not answer. answerCell(false, false, false) → true answerCell(false, false, true) → false answerCell(true, false, false) → false public boolean answerCell ( boolean isMorning , boolean isMom , boolean isAsleep ) { if ( isMom && ! isAsleep ){ return true ; } if ( isMorning && ! isMom ){ return false ; } if ( isAsleep ){ return false ; } return true ; }

Logic-1 > alarmClock - if(true) - instrukcja warunkowa

Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, ...6=Sat, and a boolean indicating if we are on vacation, return a string of the form "7:00" indicating when the alarm clock should ring. Weekdays, the alarm should be "7:00" and on the weekend it should be "10:00". Unless we are on vacation -- then on weekdays it should be "10:00" and weekends it should be "off" larmClock(1, false) → "7:00" alarmClock(5, false) → "7:00" alarmClock(0, false) → "10:00" mamy warunek isVacation true or false ktory determinuje ktorym torem pojdziemy. Instrukcja warunkowa powinna ten warunek sprawdzic jako pierwszy. if (isVacation){ . . . } else { . . . } public String alarmClock ( int day , boolean vacation ) { if ( vacation ) { if ( day == 0 || day == 6 ) return "off" ; return "10:00" ; } else { if ( day == 0 ||

String-1 > endsLy

Given a string, return true if it ends in "ly". endsLy("oddly") → true endsLy("y") → false endsLy("oddy") → false public boolean endsLy ( String str ) { if ( str . length ()< 2 ){ return false ; } if (( str . substring ( str . length ()- 2 , str . length ())). equals ( "ly" )){ return true ; } return false ; }

String-1 > middleTwo

Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string length will be at least 2. middleTwo("string") → "ri" middleTwo("code") → "od" middleTwo("Practice") → "ct" public String middleTwo ( String str ) { return str . substring (( str . length ()/ 2 - 1 ), str . length ()/ 2 + 1 ); }

String-1 > withouEnd2

Given a string, return a version without both the first and last char of the string. The string may be any length, including 0. withouEnd2("Hello") → "ell" withouEnd2("abc") → "b" withouEnd2("ab") → "" public String withouEnd2 ( String str ) { if ( str . length ()== 1 ){ return str . substring ( 1 ); } else if ( str . length ()== 0 ){ return str ; } return ( str . substring ( 1 , str . length ()- 1 )); }

String-1 > theEnd

Given a string, return a string length 1 from its front, unless  front  is false, in which case return a string length 1 from its back. The string will be non-empty. theEnd("Hello", true) → "H" theEnd("Hello", false) → "o" theEnd("oh", true) → "o" public String theEnd ( String str , boolean front ) { char cf = str . charAt ( 0 ); char ct = str . charAt ( str . length ()- 1 ); String strcf = String . valueOf ( cf ); String strct = String . valueOf ( ct ); if ( front != false ){ return strcf ; } return strct ; }

Java Boolean Operators

Operatory logiczne dla Boolean: A B A|B A&B A^B !A false false false false false true true false true false true false false true true false true true true true true true false false | the OR operator & the AND operator ^ the XOR operator ! the NOT operator || the short-circuit OR operator && the short-circuit AND operator == the EQUAL TO operator != the NOT EQUAL TO operator 

Array-2 > bigDiff

Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array. Note: the built-in Math.min(v1, v2) and Math.max(v1, v2) methods return the smaller or larger of two values. public class bigDiff { public static void main ( String [] args ) { int [] nums ={ 2 , 10 , 7 , 2 }; //min and max value of array int min = Integer . MAX_VALUE ; int max = Integer . MIN_VALUE ; // for each loop for ( int minInt: nums ) { if ( minInt < min ){ min = minInt ; } } System . out . println ( min ); // max value of array for ( int maxInt: nums ) { if ( maxInt > max ){ max = maxInt ; } } System . out . println ( max ); System . out . println ( max - min ); } } or public static void main ( String [] args ) {

String - najczęściej używane metody

Substring public String substring(int startIndex)  public String substring(int startIndex, int endIndex) String s = "Hello World" ; System . out . println ( s . substring ( 3 )); System . out . println ( s . substring ( 1 , 3 )); StringBuffer - creates mutable string. String is originally immutable. Used operation on Strings StringBuffer buffer = new StringBuffer ( "Hello World" ); buffer . append ( " GREAT ADDITION" ); System . out . println ( buffer ); StringBuilder - more efficient than StringBuffor https://www.javatpoint.com/StringBuilder-class charAt() - returns char on defined index contains() - true false endsWith()  startsWith() -  indexOf() - returns index of char isEmpty() - true false length() -  replace() - replace char  split() trim() -  toLowerCase() i toUpperCase String format() -  method returns the formatted string by given locale, format and arguments

Operatory - Java basic

Konwersja typu zmiennej tzn casting - zawężający lub rozszerzający (int -> double) Przykład: // Object Type Casting double d = 13.4587d ; int aInt = 11 ; System . out . println ( d ); System . out . println ( a + "\n" ); System . out . println ( "Object Type Casting\n" ); System . out . println (( int ) d ); System . out . println (( double ) aInt ); Object Type Casting 13 11.0 Operatory skrócone: //Przykłady operatorów skróconych int aInt2 = 11 ; aInt2 += 5 ; System . out . println ( aInt2 ); aInt2 -= 5 ; System . out . println ( aInt2 ); aInt2 /= 5 ; System . out . println ( aInt2 ); aInt2 *= 5 ; System . out . println ( aInt2 ); aInt2 &= 5 ; System . out . println ( aInt2 ); Inkrementacja i dekrymentacja // Inkrementacja int i = 0 ;

JAVA - Typy zmiennych, String, If else - podstawy jeszcze raz

Typy zmiennych JAVA: typy proste typy złożone. liczbowe int double etc znakowy char String - typ obiektowy logiczny true/false boolean Typy złożone - inaczej referencyjne lub obiektowe Typ referencyjny posiada własną referencję do pamięci gdzie przechowywana jest jego wartosć Typ złożony składa się z kilku typów prostych wtedy staje się obiektem. Przykładem typu złożonego jest klasa String Zmienna final - przykład zmiennej któej wartość nie można zmienić podczas działania programu Przykład kodu: package com . company ; public class Main { public static void main ( String [] args ) { // write your code here int intMax = Integer . MAX_VALUE ; int intMin = Integer . MIN_VALUE ; System . out . println ( "Integer" ); System . out . println ( intMax ); System . out . println ( intMin + "\n" ); long longMax = Long . MAX_VALUE ; long longMin = Long . MIN_V