├── .gitignore ├── .travis.yml ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── kotlin.iml ├── readme.md ├── settings.gradle ├── src ├── scripts │ ├── PullFromRosettaCode.kt │ ├── PushToRosettaCode.kt │ └── implementation │ │ ├── code-snippets.kt │ │ ├── http │ │ ├── Cookies.kt │ │ ├── DiskCookieStorage.kt │ │ ├── DiskHttpCache.kt │ │ └── RCClient.kt │ │ ├── pages │ │ ├── EditPage.kt │ │ ├── EditPageUrl.kt │ │ ├── LanguagePage.kt │ │ ├── LoginPage.kt │ │ └── TaskPage.kt │ │ ├── push-changes-dialog-ui.kt │ │ ├── scripts.kt │ │ └── util.kt └── tasks │ ├── A-plus-B.kt │ ├── A-star-_search_algorithm.kt │ ├── ABC_Problem.kt │ ├── AKS_test_for_primes.kt │ ├── AVL_tree.kt │ ├── Abbreviations,_automatic.kt │ ├── Abbreviations,_easy.kt │ ├── Abbreviations,_simple.kt │ ├── Abstract_type.kt │ ├── Abundant,_deficient_and_perfect_number_classifications.kt │ ├── Accumulator_factory.kt │ ├── Ackermann_function.kt │ ├── Active_Directory-Connect.kt │ ├── Active_object.kt │ ├── Add_a_variable_to_a_class_instance_at_runtime.kt │ ├── Addition_chains.kt │ ├── Align_columns.kt │ ├── Aliquot_sequence_classifications.kt │ ├── Almost_prime.kt │ ├── Amb.kt │ ├── Amicable_pairs.kt │ ├── Anagrams-Deranged_anagrams.kt │ ├── Anagrams.kt │ ├── Angle_difference_between_two_bearings.kt │ ├── Animate_a_pendulum.kt │ ├── Animation.kt │ ├── Anonymous_recursion.kt │ ├── Anti-primes.kt │ ├── Append_a_record_to_the_end_of_a_text_file.kt │ ├── Apply_a_callback_to_an_array.kt │ ├── Apply_a_digital_filter_(direct_form_II_transposed).kt │ ├── Apply_a_digitial_filter_(direct_form_II_transposed).kt │ ├── Arbitrary-precision_integers_(included).kt │ ├── Archimedean_spiral.kt │ ├── Arithmetic-Complex.kt │ ├── Arithmetic-Integer.kt │ ├── Arithmetic-Rational.kt │ ├── Arithmetic-geometric_mean-Calculate_Pi.kt │ ├── Arithmetic-geometric_mean.kt │ ├── Arithmetic_coding-As_a_generalized_change_of_radix.kt │ ├── Arithmetic_evaluation.kt │ ├── Array_concatenation-1.kt │ ├── Array_concatenation-2.kt │ ├── Array_concatenation.kt │ ├── Array_length.kt │ ├── Arrays.kt │ ├── Assertions.kt │ ├── Assertions_in_design_by_contract.kt │ ├── Associative_array-Creation.kt │ ├── Associative_array-Iteration.kt │ ├── Atomic_updates.kt │ ├── AudioAlarm.kt │ ├── Average_loop_length.kt │ ├── Averages-Arithmetic_mean.kt │ ├── Averages-Mean_angle.kt │ ├── Averages-Mean_time_of_day.kt │ ├── Averages-Median.kt │ ├── Averages-Mode.kt │ ├── Averages-Pythagorean_means.kt │ ├── Averages-Root_mean_square.kt │ ├── Averages-Simple_moving_average.kt │ ├── Babbage_problem.kt │ ├── Bacon_cipher.kt │ ├── Balanced_brackets.kt │ ├── Balanced_ternary.kt │ ├── Bankers_algorithm.kt │ ├── Barnsley_fern.kt │ ├── Base58Check_encoding.kt │ ├── Base64_encode_data.kt │ ├── Benfords_law.kt │ ├── Bernoulli_numbers.kt │ ├── Best_shuffle.kt │ ├── Bilinear_interpolation.kt │ ├── Binary_digits.kt │ ├── Binary_search.kt │ ├── Binary_strings.kt │ ├── Birthday_problem.kt │ ├── Bitcoin-address_validation.kt │ ├── Bitmap-Bezier_curves-Cubic.kt │ ├── Bitmap-Bezier_curves-Quadratic.kt │ ├── Bitmap-Bresenhams_line_algorithm.kt │ ├── Bitmap-Flood_fill.kt │ ├── Bitmap-Histogram.kt │ ├── Bitmap-Midpoint_circle_algorithm.kt │ ├── Bitmap-PPM_conversion_through_a_pipe.kt │ ├── Bitmap-Read_a_PPM_file.kt │ ├── Bitmap-Read_an_image_through_a_pipe.kt │ ├── Bitmap-Write_a_PPM_file.kt │ ├── Bitmap.kt │ ├── Bitwise_IO.kt │ ├── Bitwise_operations.kt │ ├── Box_the_compass.kt │ ├── Brace_expansion.kt │ ├── Break_OO_privacy.kt │ ├── Brownian_tree.kt │ ├── Bulls_and_cows-Player.kt │ ├── Bulls_and_cows.kt │ ├── Burrows%E2%80%93Wheeler_transform.kt │ ├── CRC-32.kt │ ├── CSV_data_manipulation.kt │ ├── CSV_to_HTML_translation.kt │ ├── CUSIP.kt │ ├── Caesar_cipher.kt │ ├── Calculate_P-Value.kt │ ├── Calculating_the_value_of_e.kt │ ├── Calendar.kt │ ├── Call_a_function.kt │ ├── Call_an_object_method.kt │ ├── Cantor_set.kt │ ├── Card_shuffles.kt │ ├── Carmichael_3_strong_pseudoprimes.kt │ ├── Cartesian_product_of_two_or_more_lists.kt │ ├── Case-sensitivity_of_identifiers.kt │ ├── Casting_out_nines.kt │ ├── Catalan_numbers-Pascals_triangle.kt │ ├── Catalan_numbers.kt │ ├── Catamorphism.kt │ ├── Chaocipher.kt │ ├── Chaos_game.kt │ ├── Character_codes.kt │ ├── Chat_server.kt │ ├── Chebyshev_coefficients.kt │ ├── Check_Machin-like_formulas.kt │ ├── Check_that_file_exists.kt │ ├── Checkpoint_synchronization.kt │ ├── Cheryls_Birthday.kt │ ├── Chinese_remainder_theorem.kt │ ├── Chinese_zodiac.kt │ ├── Cholesky_decomposition.kt │ ├── Cipollas_algorithm.kt │ ├── Circles_of_given_radius_through_two_points.kt │ ├── Classes.kt │ ├── Closest-pair_problem.kt │ ├── Closures-Value_capture.kt │ ├── Collections.kt │ ├── Color_of_a_screen_pixel.kt │ ├── Color_quantization.kt │ ├── Color_wheel.kt │ ├── Colour_bars-Display.kt │ ├── Colour_pinstripe-Display.kt │ ├── Combinations.kt │ ├── Combinations_and_permutations.kt │ ├── Combinations_with_repetitions-Square_Digit_Chain.kt │ ├── Combinations_with_repetitions.kt │ ├── Comma_quibbling.kt │ ├── Command-line_arguments.kt │ ├── Commatizing_numbers.kt │ ├── Comments.kt │ ├── Compare_a_list_of_strings.kt │ ├── Compare_sorting_algorithms_performance.kt │ ├── Compile-time_calculation.kt │ ├── Compound_data_type.kt │ ├── Concurrent_computing.kt │ ├── Conditional_structures.kt │ ├── Conjugate_transpose.kt │ ├── Constrained_genericity.kt │ ├── Constrained_random_points_on_a_circle.kt │ ├── Continued_fraction-Arithmetic-Construct_from_rational_number.kt │ ├── Continued_fraction.kt │ ├── Convert_decimal_number_to_rational.kt │ ├── Convert_seconds_to_compound_duration.kt │ ├── Convex_hull.kt │ ├── Conways_Game_of_Life.kt │ ├── Copy_a_string.kt │ ├── Count_in_factors.kt │ ├── Count_in_octal.kt │ ├── Count_occurrences_of_a_substring.kt │ ├── Count_the_coins.kt │ ├── Cramers_rule.kt │ ├── Create_a_file.kt │ ├── Create_a_file_on_magnetic_tape.kt │ ├── Create_a_two-dimensional_array_at_runtime.kt │ ├── Create_an_HTML_table.kt │ ├── Create_an_object-Native_demonstration.kt │ ├── Cumulative_standard_deviation.kt │ ├── Currency.kt │ ├── Currying.kt │ ├── Cut_a_rectangle.kt │ ├── Cycle_detection.kt │ ├── DNS_query.kt │ ├── Damm_algorithm.kt │ ├── Data_Encryption_Standard-1.kt │ ├── Data_Encryption_Standard.kt │ ├── Date_format.kt │ ├── Date_manipulation.kt │ ├── Day_of_the_week.kt │ ├── Deal_cards_for_FreeCell.kt │ ├── Decimal_floating_point_number_to_binary.kt │ ├── Decision_tables.kt │ ├── Deconvolution-1D.kt │ ├── Deepcopy.kt │ ├── Define_a_primitive_data_type.kt │ ├── Delegates.kt │ ├── Delete_a_file.kt │ ├── Demings_Funnel.kt │ ├── Department_Numbers.kt │ ├── Detect_division_by_zero.kt │ ├── Determinant_and_permanent.kt │ ├── Determine_if_a_string_is_numeric.kt │ ├── Determine_if_only_one_instance_is_running.kt │ ├── Determine_if_two_triangles_overlap.kt │ ├── Dice_game_probabilities.kt │ ├── Digital_root-Multiplicative_digital_root.kt │ ├── Digital_root.kt │ ├── Dijkstras_algorithm.kt │ ├── Dinesmans_multiple-dwelling_problem.kt │ ├── Dining_philosophers.kt │ ├── Discordian_date.kt │ ├── Display_a_linear_combination.kt │ ├── Diversity_prediction_theorem.kt │ ├── Documentation.kt │ ├── Dot_product.kt │ ├── Doubly-linked_list-Definition.kt │ ├── Doubly-linked_list-Element_definition.kt │ ├── Doubly-linked_list-Element_insertion.kt │ ├── Doubly-linked_list-Traversal.kt │ ├── Dragon_curve.kt │ ├── Draw_a_clock.kt │ ├── Draw_a_cuboid.kt │ ├── Draw_a_pixel.kt │ ├── Draw_a_rotating_cube.kt │ ├── Draw_a_sphere.kt │ ├── Draw_pixel_2.kt │ ├── Dutch_national_flag_problem.kt │ ├── Dynamic_variable_names.kt │ ├── EKG_sequence_convergence.kt │ ├── Echo_server.kt │ ├── Eertree.kt │ ├── Egyptian_division.kt │ ├── Egyptian_fractions.kt │ ├── Element-wise_operations.kt │ ├── Elementary_cellular_automaton-Infinite_length.kt │ ├── Elementary_cellular_automaton-Random_Number_Generator.kt │ ├── Elementary_cellular_automaton.kt │ ├── Elliptic_curve_arithmetic.kt │ ├── Emirp_primes.kt │ ├── Empty_directory.kt │ ├── Empty_program.kt │ ├── Empty_string.kt │ ├── Enforced_immutability.kt │ ├── Entropy-Narcissist.kt │ ├── Entropy.kt │ ├── Enumerations.kt │ ├── Environment_variables.kt │ ├── Equilibrium_index.kt │ ├── Ethiopian_multiplication.kt │ ├── Euler_method.kt │ ├── Eulers_identity.kt │ ├── Eulers_sum_of_powers_conjecture.kt │ ├── Evaluate_binomial_coefficients.kt │ ├── Even_or_odd.kt │ ├── Evolutionary_algorithm.kt │ ├── Exceptions-Catch_an_exception_thrown_in_a_nested_call.kt │ ├── Exceptions.kt │ ├── Execute_Brain-star--star--star--star-.kt │ ├── Execute_HQ9-plus-.kt │ ├── Execute_SNUSP.kt │ ├── Execute_a_Markov_algorithm.kt │ ├── Execute_a_system_command.kt │ ├── Exponentiation_operator.kt │ ├── Exponentiation_order.kt │ ├── Extend_your_language.kt │ ├── Extensible_prime_generator.kt │ ├── Extract_file_extension.kt │ ├── Extreme_floating_point_values.kt │ ├── FASTA_format.kt │ ├── Factorial.kt │ ├── Factors_of_a_Mersenne_number.kt │ ├── Factors_of_an_integer.kt │ ├── Farey_sequence.kt │ ├── Fast_Fourier_transform-1.kt │ ├── Fast_Fourier_transform-2.kt │ ├── Fast_Fourier_transform.kt │ ├── Faulhabers_formula.kt │ ├── Faulhabers_triangle.kt │ ├── Feigenbaum_constant_calculation.kt │ ├── Fibonacci_heap.kt │ ├── Fibonacci_n-step_number_sequences.kt │ ├── Fibonacci_sequence.kt │ ├── Fibonacci_word-fractal.kt │ ├── Fibonacci_word.kt │ ├── File_extension_is_in_extensions_list.kt │ ├── File_input-output.kt │ ├── File_modification_time.kt │ ├── File_size.kt │ ├── File_size_distribution.kt │ ├── Filter.kt │ ├── Find_URI_in_text.kt │ ├── Find_common_directory_path.kt │ ├── Find_first_and_last_set_bit_of_a_long_integer.kt │ ├── Find_largest_left_truncatable_prime_in_a_given_base.kt │ ├── Find_limit_of_recursion.kt │ ├── Find_palindromic_numbers_in_both_binary_and_ternary_bases.kt │ ├── Find_the_intersection_of_a_line_with_a_plane.kt │ ├── Find_the_intersection_of_two_lines.kt │ ├── Find_the_last_Sunday_of_each_month.kt │ ├── Find_the_missing_permutation.kt │ ├── Finite_state_machine.kt │ ├── First-class_functions-Use_numbers_analogously.kt │ ├── First-class_functions.kt │ ├── First_class_environments.kt │ ├── Five_weekends.kt │ ├── Fivenum.kt │ ├── FizzBuzz-1.kt │ ├── FizzBuzz-2.kt │ ├── FizzBuzz.kt │ ├── Flatten_a_list-1.kt │ ├── Flatten_a_list.kt │ ├── Flipping_bits_game.kt │ ├── Flow-control_structures.kt │ ├── Floyd-Warshall_algorithm.kt │ ├── Floyds_triangle.kt │ ├── Fork.kt │ ├── Formal_power_series.kt │ ├── Formatted_numeric_output.kt │ ├── Forward_difference.kt │ ├── Four_bit_adder.kt │ ├── Four_is_magic.kt │ ├── Four_is_the_number_of_letters_in_the_.kt │ ├── Fractal_tree.kt │ ├── Fractran.kt │ ├── Free_polyominoes_enumeration.kt │ ├── French_Republican_calendar.kt │ ├── Function_composition.kt │ ├── Function_definition.kt │ ├── Function_prototype.kt │ ├── Functional_coverage_tree.kt │ ├── GUI-Maximum_window_dimensions.kt │ ├── GUI_component_interaction.kt │ ├── GUI_enabling-disabling_of_controls.kt │ ├── Galton_box_animation.kt │ ├── Gamma_function.kt │ ├── Gauss-Jordan_matrix_inversion.kt │ ├── Gaussian_elimination.kt │ ├── General_FizzBuzz.kt │ ├── Generalised_floating_point_addition.kt │ ├── Generate_Chess960_starting_position.kt │ ├── Generate_lower_case_ASCII_alphabet.kt │ ├── Generate_random_chess_position.kt │ ├── Generator-Exponential.kt │ ├── Generic_swap.kt │ ├── Get_system_command_output.kt │ ├── Globally_replace_text_in_several_files.kt │ ├── Gray_code.kt │ ├── Grayscale_image.kt │ ├── Greatest_common_divisor.kt │ ├── Greatest_element_of_a_list.kt │ ├── Greatest_subsequential_sum.kt │ ├── Greyscale_bars-Display.kt │ ├── Guess_the_number-With_feedback.kt │ ├── Guess_the_number-With_feedback_(player).kt │ ├── Guess_the_number.kt │ ├── HTTP.kt │ ├── HTTPS-Authenticated.kt │ ├── HTTPS-Client-authenticated.kt │ ├── HTTPS.kt │ ├── Hailstone_sequence.kt │ ├── Hamming_numbers-1.kt │ ├── Hamming_numbers-2.kt │ ├── Hamming_numbers-3.kt │ ├── Hamming_numbers.kt │ ├── Handle_a_signal.kt │ ├── Happy_numbers.kt │ ├── Harshad_or_Niven_series.kt │ ├── Hash_from_two_arrays.kt │ ├── Hash_join.kt │ ├── Haversine_formula.kt │ ├── Hello_world-Graphical.kt │ ├── Hello_world-Line_printer.kt │ ├── Hello_world-Newbie.kt │ ├── Hello_world-Newline_omission.kt │ ├── Hello_world-Standard_error.kt │ ├── Hello_world-Text.kt │ ├── Hello_world-Web_server.kt │ ├── Here_document.kt │ ├── Heronian_triangles.kt │ ├── Hickerson_series_of_almost_integers.kt │ ├── Higher-order_functions-1.kt │ ├── Higher-order_functions.kt │ ├── Hilbert_curve.kt │ ├── History_variables.kt │ ├── Hofstadter-Conway_$10,000_sequence.kt │ ├── Hofstadter_Figure-Figure_sequences.kt │ ├── Hofstadter_Q_sequence.kt │ ├── Holidays_related_to_Easter.kt │ ├── Honeycombs.kt │ ├── Horizontal_sundial_calculations.kt │ ├── Horners_rule_for_polynomial_evaluation.kt │ ├── Host_introspection.kt │ ├── Hostname.kt │ ├── Hough_transform.kt │ ├── Huffman_coding.kt │ ├── IBAN.kt │ ├── IQ_Puzzle.kt │ ├── I_before_E_except_after_C.kt │ ├── Identity_matrix.kt │ ├── Idiomatically_determine_all_the_characters_that_can_be_used_for_symbols.kt │ ├── Idiomatically_determine_all_the_lowercase_and_uppercase_letters.kt │ ├── Image_convolution.kt │ ├── Image_noise.kt │ ├── Imaginary_base_numbers.kt │ ├── Implicit_type_conversion.kt │ ├── Include_a_file-1.kt │ ├── Include_a_file.kt │ ├── Increment_a_numerical_string.kt │ ├── Index_finite_lists_of_positive_integers.kt │ ├── Infinity.kt │ ├── Inheritance-Multiple.kt │ ├── Inheritance-Single.kt │ ├── Input-Output_for_Lines_of_Text.kt │ ├── Input-Output_for_Pairs_of_Numbers.kt │ ├── Input_loop.kt │ ├── Integer_comparison.kt │ ├── Integer_overflow.kt │ ├── Integer_roots.kt │ ├── Integer_sequence.kt │ ├── Introspection.kt │ ├── Inverted_index.kt │ ├── Inverted_syntax.kt │ ├── Iterated_digits_squaring.kt │ ├── Jaro_distance.kt │ ├── Jensens_Device.kt │ ├── Jewels_and_Stones.kt │ ├── JortSort.kt │ ├── Josephus_problem.kt │ ├── Julia_set.kt │ ├── Jump_anywhere.kt │ ├── Just_in_time_processing_on_a_character_stream.kt │ ├── K-d_tree.kt │ ├── K-means-plus--plus-_clustering.kt │ ├── Kahan_summation.kt │ ├── Kaprekar_numbers.kt │ ├── Kernighans_large_earthquake_problem.kt │ ├── Keyboard_input-Flush_the_keyboard_buffer.kt │ ├── Keyboard_input-Keypress_check.kt │ ├── Keyboard_input-Obtain_a_Y_or_N_response.kt │ ├── Keyboard_macros.kt │ ├── Knapsack_problem-0-1.kt │ ├── Knapsack_problem-Bounded.kt │ ├── Knapsack_problem-Continuous.kt │ ├── Knapsack_problem-Unbounded.kt │ ├── Knights_tour.kt │ ├── Knuth_shuffle.kt │ ├── Knuths_algorithm_S-1.kt │ ├── Knuths_algorithm_S.kt │ ├── Knuths_power_tree.kt │ ├── Koch_curve.kt │ ├── Kolakoski_sequence.kt │ ├── Kosaraju.kt │ ├── Kronecker_product.kt │ ├── Kronecker_product_based_fractals.kt │ ├── LU_decomposition.kt │ ├── LZW_compression.kt │ ├── Langtons_ant.kt │ ├── Largest_int_from_concatenated_ints.kt │ ├── Largest_number_divisible_by_its_digits-1.kt │ ├── Largest_number_divisible_by_its_digits.kt │ ├── Last_Friday_of_each_month.kt │ ├── Last_letter-first_letter.kt │ ├── Law_of_cosines_-_triples.kt │ ├── Leap_year.kt │ ├── Least_common_multiple.kt │ ├── Left_factorials.kt │ ├── Leonardo_numbers.kt │ ├── Letter_frequency.kt │ ├── Levenshtein_distance-1.kt │ ├── Levenshtein_distance-Alignment.kt │ ├── Levenshtein_distance.kt │ ├── Linear_congruential_generator.kt │ ├── Linux_CPU_utilization.kt │ ├── List_comprehensions.kt │ ├── List_rooted_trees.kt │ ├── Literals-Floating_point.kt │ ├── Literals-Integer.kt │ ├── Literals-String.kt │ ├── Logical_operations.kt │ ├── Long_multiplication.kt │ ├── Long_primes.kt │ ├── Longest_Common_Substring.kt │ ├── Longest_common_prefix.kt │ ├── Longest_common_subsequence.kt │ ├── Longest_increasing_subsequence.kt │ ├── Longest_string_challenge.kt │ ├── Look-and-say_sequence.kt │ ├── Loop_over_multiple_arrays_simultaneously.kt │ ├── Loops-Break.kt │ ├── Loops-Continue.kt │ ├── Loops-Do-while.kt │ ├── Loops-Downward_for.kt │ ├── Loops-For.kt │ ├── Loops-For_with_a_specified_step.kt │ ├── Loops-Foreach.kt │ ├── Loops-Increment_loop_index_within_loop_body-1.kt │ ├── Loops-Increment_loop_index_within_loop_body.kt │ ├── Loops-Infinite.kt │ ├── Loops-N_plus_one_half.kt │ ├── Loops-Nested.kt │ ├── Loops-While.kt │ ├── Loops-Wrong_ranges.kt │ ├── Loops-with_multiple_ranges.kt │ ├── Lucas-Lehmer_test.kt │ ├── Lucky_and_even_lucky_numbers.kt │ ├── Ludic_numbers.kt │ ├── Luhn_test_of_credit_card_numbers.kt │ ├── Lychrel_numbers.kt │ ├── MAC_Vendor_Lookup.kt │ ├── MD4.kt │ ├── MD5-Implementation.kt │ ├── MD5.kt │ ├── Mad_Libs.kt │ ├── Magic_8-Ball.kt │ ├── Magic_squares_of_doubly_even_order.kt │ ├── Magic_squares_of_odd_order.kt │ ├── Magic_squares_of_singly_even_order.kt │ ├── Main_step_of_GOST_28147-89.kt │ ├── Make_a_backup_file.kt │ ├── Make_directory_path.kt │ ├── Man_or_boy_test.kt │ ├── Mandelbrot_set.kt │ ├── Map_range.kt │ ├── Markov_chain_text_generator.kt │ ├── Mastermind.kt │ ├── Matrix-exponentiation_operator.kt │ ├── Matrix_arithmetic.kt │ ├── Matrix_chain_multiplication.kt │ ├── Matrix_multiplication.kt │ ├── Matrix_transposition.kt │ ├── Maximum_triangle_path_sum.kt │ ├── Maze_generation.kt │ ├── Maze_solving.kt │ ├── McNuggets_Problem.kt │ ├── Median_filter.kt │ ├── Memory_allocation.kt │ ├── Memory_layout_of_a_data_structure.kt │ ├── Menu.kt │ ├── Mersenne_primes.kt │ ├── Metaprogramming.kt │ ├── Metered_concurrency.kt │ ├── Metronome.kt │ ├── Middle_three_digits.kt │ ├── Miller%E2%80%93Rabin_primality_test.kt │ ├── Mind_boggling_card_trick.kt │ ├── Modular_arithmetic.kt │ ├── Modular_exponentiation.kt │ ├── Modular_inverse.kt │ ├── Monads-List_monad.kt │ ├── Monads-Maybe_monad.kt │ ├── Monads-Writer_monad.kt │ ├── Monte_Carlo_methods.kt │ ├── Montgomery_reduction.kt │ ├── Monty_Hall_problem.kt │ ├── Morse_code.kt │ ├── Most_frequent_k_chars_distance.kt │ ├── Mouse_position.kt │ ├── Move-to-front_algorithm.kt │ ├── Multi-dimensional_array.kt │ ├── Multidimensional_Newton-Raphson_method.kt │ ├── Multifactorial.kt │ ├── Multiple_distinct_objects.kt │ ├── Multiple_regression.kt │ ├── Multiplication_tables.kt │ ├── Multiplicative_order.kt │ ├── Multisplit.kt │ ├── Munchausen_numbers.kt │ ├── Munching_squares.kt │ ├── Mutual_recursion.kt │ ├── N-body_problem.kt │ ├── N-queens_problem.kt │ ├── NYSIIS.kt │ ├── Named_parameters.kt │ ├── Names_to_numbers.kt │ ├── Naming_conventions.kt │ ├── Narcissist.kt │ ├── Narcissistic_decimal_number.kt │ ├── Natural_sorting.kt │ ├── Nautical_bell.kt │ ├── Negative_base_numbers.kt │ ├── Nested_function.kt │ ├── Non-continuous_subsequences.kt │ ├── Non-decimal_radices-Convert.kt │ ├── Non-decimal_radices-Input.kt │ ├── Non-decimal_radices-Output.kt │ ├── Nonoblock.kt │ ├── Nonogram_solver.kt │ ├── Nth.kt │ ├── Nth_root.kt │ ├── Null_object.kt │ ├── Number_names.kt │ ├── Number_reversal_game.kt │ ├── Numeric_error_propagation.kt │ ├── Numerical_integration-Adaptive_Simpsons_method.kt │ ├── Numerical_integration-Gauss-Legendre_Quadrature.kt │ ├── Numerical_integration.kt │ ├── Object_serialization.kt │ ├── Odd_word_problem.kt │ ├── Old_Russian_measure_of_length.kt │ ├── Old_lady_swallowed_a_fly.kt │ ├── One-dimensional_cellular_automata.kt │ ├── One-time_pad.kt │ ├── One_of_n_lines_in_a_file.kt │ ├── OpenWebNet_Password.kt │ ├── Optional_parameters.kt │ ├── Orbital_elements.kt │ ├── Order_disjoint_list_items.kt │ ├── Order_two_numerical_lists.kt │ ├── Ordered_Partitions.kt │ ├── Ordered_words.kt │ ├── P-value_correction-1.kt │ ├── P-value_correction.kt │ ├── Palindrome_detection.kt │ ├── Pangram_checker.kt │ ├── Paraffins.kt │ ├── Parallel_Brute_Force.kt │ ├── Parallel_calculations.kt │ ├── Parametric_polymorphism.kt │ ├── Parametrized_SQL_statement.kt │ ├── Parse_an_IP_Address.kt │ ├── Parse_command-line_arguments.kt │ ├── Parsing-RPN_calculator_algorithm.kt │ ├── Parsing-RPN_to_infix_conversion.kt │ ├── Parsing-Shunting-yard_algorithm.kt │ ├── Partial_function_application.kt │ ├── Particle_Swarm_Optimization.kt │ ├── Partition_an_integer_X_into_N_primes.kt │ ├── Pascal_matrix_generation.kt │ ├── Pascals_triangle-Puzzle.kt │ ├── Pascals_triangle.kt │ ├── Password_generator.kt │ ├── Pathological_floating_point_problems.kt │ ├── Penneys_game.kt │ ├── Penrose_tiling.kt │ ├── Pentagram.kt │ ├── Pentomino_tiling.kt │ ├── Percentage_difference_between_images.kt │ ├── Perceptron.kt │ ├── Percolation-Bond_percolation.kt │ ├── Percolation-Mean_cluster_density.kt │ ├── Percolation-Mean_run_density.kt │ ├── Percolation-Site_percolation.kt │ ├── Perfect_numbers.kt │ ├── Perfect_shuffle.kt │ ├── Perlin_noise.kt │ ├── Permutation_test.kt │ ├── Permutations-Derangements.kt │ ├── Permutations-Rank_of_a_permutation.kt │ ├── Permutations.kt │ ├── Permutations_by_swapping.kt │ ├── Permutations_with_repetitions.kt │ ├── Pernicious_numbers.kt │ ├── Phrase_reversals.kt │ ├── Pi.kt │ ├── Pick_random_element.kt │ ├── Pig_the_dice_game.kt │ ├── Pinstripe-Display.kt │ ├── Plasma_effect.kt │ ├── Playfair_cipher.kt │ ├── Playing_cards.kt │ ├── Plot_coordinate_pairs.kt │ ├── Poker_hand_analyser-1.kt │ ├── Poker_hand_analyser.kt │ ├── Polymorphic_copy.kt │ ├── Polymorphism.kt │ ├── Polynomial_long_division.kt │ ├── Polynomial_regression.kt │ ├── Polynomial_synthetic_division.kt │ ├── Polyspiral.kt │ ├── Population_count.kt │ ├── Power_set.kt │ ├── Pragmatic_directives.kt │ ├── Price_fraction.kt │ ├── Primality_by_trial_division.kt │ ├── Prime_conspiracy.kt │ ├── Prime_decomposition.kt │ ├── Primes_-_allocate_descendants_to_their_ancestors.kt │ ├── Primorial_numbers.kt │ ├── Priority_queue.kt │ ├── Probabilistic_choice.kt │ ├── Problem_of_Apollonius.kt │ ├── Program_name.kt │ ├── Program_termination.kt │ ├── Proper_divisors.kt │ ├── Pythagoras_tree.kt │ ├── Pythagorean_quadruples-1.kt │ ├── Pythagorean_quadruples.kt │ ├── Pythagorean_triples.kt │ ├── Quaternion_type.kt │ ├── Queue-Definition.kt │ ├── Queue-Usage.kt │ ├── Quickselect_algorithm.kt │ ├── Quine.kt │ ├── RIPEMD-160.kt │ ├── RPG_Attributes_Generator.kt │ ├── RSA_code.kt │ ├── Railway_circuit.kt │ ├── Ramer-Douglas-Peucker_line_simplification.kt │ ├── Ramseys_theorem.kt │ ├── Random_number_generator_(device).kt │ ├── Random_numbers.kt │ ├── Range_expansion.kt │ ├── Range_extraction.kt │ ├── Ranking_methods.kt │ ├── Rate_counter.kt │ ├── Ray-casting_algorithm-1.kt │ ├── Ray-casting_algorithm.kt │ ├── Read_a_configuration_file.kt │ ├── Read_a_file_character_by_character-UTF8.kt │ ├── Read_a_file_line_by_line.kt │ ├── Read_a_specific_line_from_a_file.kt │ ├── Read_entire_file.kt │ ├── Readline_interface.kt │ ├── Real_constants_and_functions.kt │ ├── Recamans_sequence.kt │ ├── Record_sound.kt │ ├── Reduced_row_echelon_form.kt │ ├── Reflection-List_methods.kt │ ├── Reflection-List_properties.kt │ ├── Regular_expressions.kt │ ├── Remove_duplicate_elements.kt │ ├── Remove_lines_from_a_file.kt │ ├── Rename_a_file.kt │ ├── Rep-string.kt │ ├── Repeat.kt │ ├── Repeat_a_string-1.kt │ ├── Repeat_a_string.kt │ ├── Resistor_mesh.kt │ ├── Return_multiple_values.kt │ ├── Reverse_a_string.kt │ ├── Reverse_the_gender_of_a_string.kt │ ├── Reverse_words_in_a_string.kt │ ├── Rock-paper-scissors.kt │ ├── Roman_numerals-Decode.kt │ ├── Roman_numerals-Encode-1.kt │ ├── Roman_numerals-Encode.kt │ ├── Roots_of_a_function.kt │ ├── Roots_of_a_quadratic_function.kt │ ├── Roots_of_unity.kt │ ├── Rosetta_Code-Rank_languages_by_popularity.kt │ ├── Rot-13.kt │ ├── Run-length_encoding.kt │ ├── Runge-Kutta_method.kt │ ├── S-Expressions.kt │ ├── SEDOLs.kt │ ├── SHA-1.kt │ ├── SHA-256.kt │ ├── SQL-based_authentication.kt │ ├── Safe_addition.kt │ ├── Safe_primes_and_unsafe_primes.kt │ ├── Sailors,_coconuts_and_a_monkey_problem.kt │ ├── Sattolo_cycle.kt │ ├── Scope-Function_names_and_labels.kt │ ├── Scope_modifiers.kt │ ├── Search_a_list.kt │ ├── Search_a_list_of_records.kt │ ├── Secure_temporary_file.kt │ ├── Selective_File_Copy.kt │ ├── Self-describing_numbers.kt │ ├── Self-referential_sequence.kt │ ├── Semiprime.kt │ ├── Semordnilap.kt │ ├── Send_email.kt │ ├── Separate_the_house_number_from_the_street_name.kt │ ├── Sequence_of_non-squares.kt │ ├── Sequence_of_primes_by_Trial_Division.kt │ ├── Sequence_of_primorial_primes.kt │ ├── Set.kt │ ├── Set_consolidation.kt │ ├── Set_of_real_numbers.kt │ ├── Set_puzzle.kt │ ├── Seven-sided_dice_from_five-sided_dice.kt │ ├── Sexy_primes.kt │ ├── Shoelace_formula_for_polygonal_area.kt │ ├── Short-circuit_evaluation.kt │ ├── Shortest_common_supersequence.kt │ ├── Show_Ascii_table.kt │ ├── Show_the_epoch.kt │ ├── Sierpinski_carpet-1.kt │ ├── Sierpinski_carpet.kt │ ├── Sierpinski_pentagon.kt │ ├── Sierpinski_triangle-Graphical.kt │ ├── Sierpinski_triangle.kt │ ├── Sieve_of_Eratosthenes-1.kt │ ├── Sieve_of_Eratosthenes-2.kt │ ├── Sieve_of_Eratosthenes-3.kt │ ├── Sieve_of_Eratosthenes.kt │ ├── Simple_database.kt │ ├── Simple_windowed_application-1.kt │ ├── Simple_windowed_application.kt │ ├── Simulate_input-Keyboard.kt │ ├── Simulate_input-Mouse.kt │ ├── Sine_wave-1.kt │ ├── Sine_wave.kt │ ├── Singleton.kt │ ├── Singly-linked_list-Element_definition.kt │ ├── Singly-linked_list-Element_insertion.kt │ ├── Singly-linked_list-Element_removal.kt │ ├── Singly-linked_list-Traversal.kt │ ├── Sleep.kt │ ├── Smith_numbers.kt │ ├── Snake_And_Ladder.kt │ ├── Sockets.kt │ ├── Sokoban.kt │ ├── Solve_a_Hidato_puzzle.kt │ ├── Solve_a_Holy_Knights_tour.kt │ ├── Solve_a_Hopido_puzzle.kt │ ├── Solve_a_Numbrix_puzzle.kt │ ├── Solve_a_Rubiks_Cube.kt │ ├── Solve_the_no_connection_puzzle.kt │ ├── Sort_a_list_of_object_identifiers.kt │ ├── Sort_an_array_of_composite_structures.kt │ ├── Sort_an_integer_array.kt │ ├── Sort_disjoint_sublist.kt │ ├── Sort_numbers_lexicographically.kt │ ├── Sort_stability.kt │ ├── Sort_three_variables.kt │ ├── Sort_using_a_custom_comparator.kt │ ├── Sorting_Algorithms-Circle_Sort.kt │ ├── Sorting_algorithms-Bead_sort.kt │ ├── Sorting_algorithms-Bogosort.kt │ ├── Sorting_algorithms-Bubble_sort.kt │ ├── Sorting_algorithms-Cocktail_sort.kt │ ├── Sorting_algorithms-Comb_sort.kt │ ├── Sorting_algorithms-Counting_sort.kt │ ├── Sorting_algorithms-Cycle_sort.kt │ ├── Sorting_algorithms-Gnome_sort.kt │ ├── Sorting_algorithms-Heapsort.kt │ ├── Sorting_algorithms-Insertion_sort.kt │ ├── Sorting_algorithms-Merge_sort.kt │ ├── Sorting_algorithms-Pancake_sort.kt │ ├── Sorting_algorithms-Patience_sort.kt │ ├── Sorting_algorithms-Permutation_sort.kt │ ├── Sorting_algorithms-Quicksort-1.kt │ ├── Sorting_algorithms-Quicksort.kt │ ├── Sorting_algorithms-Radix_sort.kt │ ├── Sorting_algorithms-Selection_sort.kt │ ├── Sorting_algorithms-Shell_sort.kt │ ├── Sorting_algorithms-Sleep_sort.kt │ ├── Sorting_algorithms-Stooge_sort.kt │ ├── Sorting_algorithms-Strand_sort.kt │ ├── Sorting_algorithms-Tree_sort_on_a_linked_list.kt │ ├── Soundex.kt │ ├── Sparkline_in_unicode.kt │ ├── Special_variables.kt │ ├── Spelling_of_ordinal_numbers.kt │ ├── Spinning_rod_animation-Text.kt │ ├── Spiral_matrix.kt │ ├── Split_a_character_string_based_on_change_of_character.kt │ ├── Spoof_game.kt │ ├── Square-free_integers.kt │ ├── Square_but_not_cube.kt │ ├── Stable_marriage_problem.kt │ ├── Stack.kt │ ├── Stack_traces.kt │ ├── Stair-climbing_puzzle.kt │ ├── State_name_puzzle.kt │ ├── Statistics-Basic.kt │ ├── Statistics-Normal_distribution.kt │ ├── Stem-and-leaf_plot.kt │ ├── Stern-Brocot_sequence.kt │ ├── Straddling_checkerboard.kt │ ├── Stream_Merge.kt │ ├── String_append.kt │ ├── String_case.kt │ ├── String_comparison.kt │ ├── String_concatenation.kt │ ├── String_interpolation_(included).kt │ ├── String_length.kt │ ├── String_matching.kt │ ├── String_prepend.kt │ ├── Strip_a_set_of_characters_from_a_string.kt │ ├── Strip_block_comments.kt │ ├── Strip_comments_from_a_string.kt │ ├── Strip_control_codes_and_extended_characters_from_a_string.kt │ ├── Strip_whitespace_from_a_string-Top_and_tail.kt │ ├── Subleq.kt │ ├── Subset_sum_problem.kt │ ├── Substitution_Cipher.kt │ ├── Substring-Top_and_tail.kt │ ├── Substring.kt │ ├── Subtractive_generator.kt │ ├── Sudoku.kt │ ├── Suffix_tree.kt │ ├── Sum_and_Product_Puzzle.kt │ ├── Sum_and_product_of_an_array.kt │ ├── Sum_digits_of_an_integer.kt │ ├── Sum_multiples_of_3_and_5.kt │ ├── Sum_of_a_series.kt │ ├── Sum_of_squares.kt │ ├── Sum_to_100.kt │ ├── Superellipse.kt │ ├── Superpermutation_minimisation.kt │ ├── Sutherland-Hodgman_polygon_clipping.kt │ ├── Symmetric_difference.kt │ ├── Synchronous_concurrency.kt │ ├── System_time.kt │ ├── Table_creation-Postal_addresses.kt │ ├── Take_notes_on_the_command_line.kt │ ├── Tarjan.kt │ ├── Taxicab_numbers.kt │ ├── Temperature_conversion.kt │ ├── Terminal_control-Clear_the_screen.kt │ ├── Terminal_control-Coloured_text.kt │ ├── Terminal_control-Cursor_movement.kt │ ├── Terminal_control-Cursor_positioning.kt │ ├── Terminal_control-Dimensions.kt │ ├── Terminal_control-Display_an_extended_character.kt │ ├── Terminal_control-Hiding_the_cursor.kt │ ├── Terminal_control-Inverse_video.kt │ ├── Terminal_control-Preserve_screen.kt │ ├── Terminal_control-Ringing_the_terminal_bell.kt │ ├── Terminal_control-Unicode_output.kt │ ├── Ternary_logic.kt │ ├── Test_a_function.kt │ ├── Test_integerness.kt │ ├── Text_between.kt │ ├── Text_processing-1.kt │ ├── Text_processing-2.kt │ ├── Text_processing-Max_licenses_in_use.kt │ ├── Textonyms.kt │ ├── The_ISAAC_Cipher.kt │ ├── The_Name_Game.kt │ ├── The_Twelve_Days_of_Christmas.kt │ ├── Thieles_interpolation_formula.kt │ ├── Thue-Morse.kt │ ├── Tic-tac-toe.kt │ ├── Time_a_function.kt │ ├── Tokenize_a_string.kt │ ├── Tokenize_a_string_with_escaping.kt │ ├── Tonelli-Shanks_algorithm.kt │ ├── Top_rank_per_group.kt │ ├── Topic_variable.kt │ ├── Topological_sort-1.kt │ ├── Topological_sort-Extracted_top_item.kt │ ├── Topological_sort.kt │ ├── Topswops.kt │ ├── Total_circles_area-1.kt │ ├── Total_circles_area.kt │ ├── Towers_of_Hanoi.kt │ ├── Trabb_Pardo%E2%80%93Knuth_algorithm.kt │ ├── Transportation_problem.kt │ ├── Tree_traversal-1.kt │ ├── Tree_traversal.kt │ ├── Trigonometric_functions.kt │ ├── Truncatable_primes.kt │ ├── Truncate_a_file.kt │ ├── Truth_table.kt │ ├── Twelve_statements.kt │ ├── Two_Sum.kt │ ├── Type_detection.kt │ ├── URL_decoding.kt │ ├── URL_encoding.kt │ ├── URL_parser.kt │ ├── UTF-8_encode_and_decode.kt │ ├── Ulam_spiral_(for_primes).kt │ ├── Unbias_a_random_generator.kt │ ├── Undefined_values.kt │ ├── Unicode_strings.kt │ ├── Unicode_variable_names.kt │ ├── Universal_Turing_machine.kt │ ├── Unix-ls.kt │ ├── Update_a_configuration_file.kt │ ├── User_input-Graphical.kt │ ├── User_input-Text.kt │ ├── VList.kt │ ├── Validate_International_Securities_Identification_Number.kt │ ├── Vampire_number.kt │ ├── Van_der_Corput_sequence.kt │ ├── Variable-length_quantity.kt │ ├── Variable_size-Get.kt │ ├── Variable_size-Set.kt │ ├── Variables.kt │ ├── Variadic_function.kt │ ├── Vector.kt │ ├── Vector_products.kt │ ├── Verify_distribution_uniformity-Chi-squared_test.kt │ ├── Verify_distribution_uniformity-Naive.kt │ ├── Video_display_modes.kt │ ├── Vigenere_cipher-Cryptanalysis.kt │ ├── Vigenere_cipher.kt │ ├── Visualize_a_tree.kt │ ├── Vogels_approximation_method.kt │ ├── Voronoi_diagram.kt │ ├── Walk_a_directory-Non-recursively.kt │ ├── Walk_a_directory-Recursively.kt │ ├── Water_collected_between_towers.kt │ ├── Web_scraping.kt │ ├── Welchs_t-test.kt │ ├── Window_creation.kt │ ├── Word_break_problem.kt │ ├── Word_count.kt │ ├── Word_search.kt │ ├── Word_wrap.kt │ ├── World_Cup_group_stage.kt │ ├── Write_entire_file.kt │ ├── Write_float_arrays_to_a_text_file.kt │ ├── Write_language_name_in_3D_ASCII.kt │ ├── Write_to_Windows_event_log.kt │ ├── XML-DOM_serialization.kt │ ├── XML-Input.kt │ ├── XML-Output.kt │ ├── XML-XPath.kt │ ├── Xiaolin_Wus_line_algorithm.kt │ ├── Y_combinator.kt │ ├── Yahoo-bang-_search_interface.kt │ ├── Yin_and_yang.kt │ ├── Zebra_puzzle.kt │ ├── Zeckendorf_arithmetic.kt │ ├── Zeckendorf_number_representation.kt │ ├── Zero_to_the_zero_power.kt │ ├── Zhang-Suen_thinning_algorithm.kt │ ├── Zig-zag_matrix.kt │ ├── _100_doors.kt │ ├── _15_Puzzle_Game.kt │ ├── _2048.kt │ ├── _24_game-Solve.kt │ ├── _24_game.kt │ ├── _4-rings_or_4-squares_puzzle.kt │ ├── _99_Bottles_of_Beer.kt │ ├── _9_billion_names_of_God_the_integer.kt │ └── configuration.txt └── test └── scripts └── implementation ├── CodeSnippetsSpec.kt └── pages ├── EditPageSpec.kt ├── EditPageUrlSpec.kt ├── LanguagesPageSpec.kt ├── TaskPageSpec.kt ├── array-concatenation-edit-page.txt ├── array-concatenation-page.txt ├── kotlin-page.txt ├── marriage-problem-edit-page.txt └── test-util-script.kt /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea/ 2 | /build/ 3 | /.gradle/ 4 | /urls.xml 5 | /codeEntries.xml 6 | /editPageUrls.xml 7 | *~ 8 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dkandalov/rosettacode-kotlin/60c4c20dac070d9d1e1b652c614e839e5dbc3025/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Aug 27 22:17:00 BST 2018 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https://services.gradle.org/distributions/gradle-5.0-all.zip 7 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'Rosetta-Code-Kotlin' 2 | -------------------------------------------------------------------------------- /src/scripts/PullFromRosettaCode.kt: -------------------------------------------------------------------------------- 1 | package scripts 2 | 3 | import scripts.implementation.http.newRCClient 4 | import scripts.implementation.pullFromRosettaCodeWebsite 5 | 6 | fun main() { 7 | pullFromRosettaCodeWebsite( 8 | rcClient = newRCClient(), 9 | overwriteLocalFiles = System.getProperty("overwriteLocalFiles", "false")!!.toBoolean(), 10 | useCachedHttpClient = System.getProperty("dirty", "true")!!.toBoolean() 11 | ) 12 | } -------------------------------------------------------------------------------- /src/scripts/PushToRosettaCode.kt: -------------------------------------------------------------------------------- 1 | package scripts 2 | 3 | import scripts.implementation.http.newRCClient 4 | import scripts.implementation.http.withDebug 5 | import scripts.implementation.pushLocalChangesToRosettaCode 6 | 7 | fun main() { 8 | pushLocalChangesToRosettaCode(newRCClient().withDebug()) 9 | } -------------------------------------------------------------------------------- /src/scripts/implementation/pages/TaskPage.kt: -------------------------------------------------------------------------------- 1 | package scripts.implementation.pages 2 | 3 | import org.http4k.core.HttpHandler 4 | import org.http4k.core.Method.GET 5 | import org.http4k.core.Request 6 | import scripts.implementation.extractUrl 7 | 8 | data class TaskPage(private val html: String) { 9 | fun extractKotlinEditPageUrl(): EditPageUrl { 10 | val s = html.split("\n") 11 | .dropWhile { !it.contains("") } 12 | .find { it.contains(" Double { 6 | var nn = n 7 | return { nn += it; nn } 8 | } 9 | 10 | fun foo(n: Int): (i: Int) -> Int { 11 | var nn = n 12 | return { nn += it; nn } 13 | } 14 | 15 | fun main(args: Array) { 16 | val x = foo(1.0) // calls 'Double' overload 17 | x(5.0) 18 | foo(3.0) 19 | println(x(2.3)) 20 | val y = foo(1) // calls 'Int' overload 21 | y(5) 22 | foo(5) 23 | println(y(2)) 24 | } -------------------------------------------------------------------------------- /src/tasks/Almost_prime.kt: -------------------------------------------------------------------------------- 1 | package `almost_prime` 2 | 3 | fun Int.k_prime(x: Int): Boolean { 4 | var n = x 5 | var f = 0 6 | var p = 2 7 | while (f < this && p * p <= n) { 8 | while (0 == n % p) { n /= p; f++ } 9 | p++ 10 | } 11 | return f + (if (n > 1) 1 else 0) == this 12 | } 13 | 14 | fun Int.primes(n : Int) : List { 15 | var i = 2 16 | var list = mutableListOf() 17 | while (list.size < n) { 18 | if (k_prime(i)) list.add(i) 19 | i++ 20 | } 21 | return list 22 | } 23 | 24 | fun main(args: Array) { 25 | for (k in 1..5) 26 | println("k = $k: " + k.primes(10)) 27 | } -------------------------------------------------------------------------------- /src/tasks/Amicable_pairs.kt: -------------------------------------------------------------------------------- 1 | package `amicable_pairs` 2 | 3 | // version 1.1 4 | 5 | fun sumProperDivisors(n: Int): Int { 6 | if (n < 2) return 0 7 | return (1..n / 2).filter{ (n % it) == 0 }.sum() 8 | } 9 | 10 | fun main(args: Array) { 11 | val sum = IntArray(20000, { sumProperDivisors(it) } ) 12 | println("The pairs of amicable numbers below 20,000 are:\n") 13 | for(n in 2..19998) { 14 | val m = sum[n] 15 | if (m > n && m < 20000 && n == sum[m]) { 16 | println(n.toString().padStart(5) + " and " + m.toString().padStart(5)) 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /src/tasks/Anonymous_recursion.kt: -------------------------------------------------------------------------------- 1 | package `anonymous_recursion` 2 | 3 | fun fib(n: Int): Int { 4 | require(n >= 0) 5 | fun fib1(k: Int, a: Int, b: Int): Int = 6 | if (k == 0) a else fib1(k - 1, b, a + b) 7 | return fib1(n, 0, 1) 8 | } 9 | 10 | fun main(args: Array) { 11 | for (i in 0..20) print("${fib(i)} ") 12 | println() 13 | } -------------------------------------------------------------------------------- /src/tasks/Anti-primes.kt: -------------------------------------------------------------------------------- 1 | package `anti_primes` 2 | 3 | // Version 1.3.10 4 | 5 | fun countDivisors(n: Int): Int { 6 | if (n < 2) return 1; 7 | var count = 2 // 1 and n 8 | for (i in 2..n / 2) { 9 | if (n % i == 0) count++ 10 | } 11 | return count; 12 | } 13 | 14 | fun main(args: Array) { 15 | println("The first 20 anti-primes are:") 16 | var maxDiv = 0 17 | var count = 0 18 | var n = 1 19 | while (count < 20) { 20 | val d = countDivisors(n) 21 | if (d > maxDiv) { 22 | print("$n ") 23 | maxDiv = d 24 | count++ 25 | } 26 | n++ 27 | } 28 | println() 29 | } -------------------------------------------------------------------------------- /src/tasks/Apply_a_callback_to_an_array.kt: -------------------------------------------------------------------------------- 1 | package `apply_a_callback_to_an_array` 2 | 3 | fun main(args: Array) { 4 | val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // build 5 | val function = { i: Int -> i * i } // function to apply 6 | val list = array.map { function(it) } // process each item 7 | println(list) // print results 8 | } -------------------------------------------------------------------------------- /src/tasks/Arbitrary-precision_integers_(included).kt: -------------------------------------------------------------------------------- 1 | package `arbitrary_precision_integers_(included)` 2 | 3 | import java.math.BigInteger 4 | 5 | fun main(args: Array) { 6 | val x = BigInteger.valueOf(5).pow(Math.pow(4.0, 3.0 * 3.0).toInt()) 7 | val y = x.toString() 8 | val len = y.length 9 | println("5^4^3^2 = ${y.substring(0, 20)}...${y.substring(len - 20)} and has $len digits") 10 | } -------------------------------------------------------------------------------- /src/tasks/Arithmetic-geometric_mean.kt: -------------------------------------------------------------------------------- 1 | package `arithmetic_geometric_mean` 2 | 3 | // version 1.0.5-2 4 | 5 | fun agm(a: Double, g: Double): Double { 6 | var aa = a // mutable 'a' 7 | var gg = g // mutable 'g' 8 | var ta: Double // temporary variable to hold next iteration of 'aa' 9 | val epsilon = 1.0e-16 // tolerance for checking if limit has been reached 10 | 11 | while (true) { 12 | ta = (aa + gg) / 2.0 13 | if (Math.abs(aa - ta) <= epsilon) return ta 14 | gg = Math.sqrt(aa * gg) 15 | aa = ta 16 | } 17 | } 18 | 19 | fun main(args: Array) { 20 | println(agm(1.0, 1.0 / Math.sqrt(2.0))) 21 | } -------------------------------------------------------------------------------- /src/tasks/Array_concatenation-1.kt: -------------------------------------------------------------------------------- 1 | package `array_concatenation_1` 2 | 3 | fun arrayConcat(a: Array, b: Array): Array { 4 | return Array(a.size + b.size, { if (it in a.indices) a[it] else b[it - a.size] }) 5 | } -------------------------------------------------------------------------------- /src/tasks/Array_concatenation-2.kt: -------------------------------------------------------------------------------- 1 | package `array_concatenation_2` 2 | 3 | fun main(args: Array) { 4 | val a: Collection = listOf(1, 2, 3) // initialise a 5 | val b: Collection = listOf(4, 5, 6) // initialise b 6 | val c: Collection = a + b 7 | println(c) 8 | } -------------------------------------------------------------------------------- /src/tasks/Array_concatenation.kt: -------------------------------------------------------------------------------- 1 | package `array_concatenation` 2 | 3 | fun main(args: Array) { 4 | val a: Array = arrayOf(1, 2, 3) // initialise a 5 | val b: Array = arrayOf(4, 5, 6) // initialise b 6 | val c: Array = (a.toList() + b.toList()).toTypedArray() 7 | println(c) 8 | } -------------------------------------------------------------------------------- /src/tasks/Array_length.kt: -------------------------------------------------------------------------------- 1 | package `array_length` 2 | 3 | fun main(args: Array) { 4 | println(arrayOf("apple", "orange").size) 5 | } -------------------------------------------------------------------------------- /src/tasks/Arrays.kt: -------------------------------------------------------------------------------- 1 | package `arrays` 2 | 3 | fun main(x: Array) { 4 | var a = arrayOf(1, 2, 3, 4) 5 | println(a.asList()) 6 | a += 5 7 | println(a.asList()) 8 | println(a.reversedArray().asList()) 9 | } -------------------------------------------------------------------------------- /src/tasks/Assertions.kt: -------------------------------------------------------------------------------- 1 | package `assertions` 2 | 3 | // version 1.0.6 (assert.kt) 4 | 5 | fun main(args: Array) { 6 | val a = 42 7 | assert(a == 43) 8 | } -------------------------------------------------------------------------------- /src/tasks/Assertions_in_design_by_contract.kt: -------------------------------------------------------------------------------- 1 | package `assertions_in_design_by_contract` 2 | 3 | // version 1.1.2 4 | // requires -ea JVM option 5 | 6 | fun main(args: Array) { 7 | assert(args.size > 0) { "At least one command line argument must be passed to the program" } 8 | println("The following command line arguments have been passed:") 9 | for (arg in args) println(arg) 10 | } -------------------------------------------------------------------------------- /src/tasks/Associative_array-Creation.kt: -------------------------------------------------------------------------------- 1 | package `associative_array_creation` 2 | 3 | fun main(args: Array) { 4 | // map definition: 5 | val map = mapOf("foo" to 5, 6 | "bar" to 10, 7 | "baz" to 15, 8 | "foo" to 6) 9 | 10 | // retrieval: 11 | println(map["foo"]) // => 6 12 | println(map["invalid"]) // => null 13 | 14 | // check keys: 15 | println("foo" in map) // => true 16 | println("invalid" in map) // => false 17 | 18 | // iterate over keys: 19 | for (k in map.keys) print("$k ") 20 | println() 21 | 22 | // iterate over values: 23 | for (v in map.values) print("$v ") 24 | println() 25 | 26 | // iterate over key, value pairs: 27 | for ((k, v) in map) println("$k => $v") 28 | } -------------------------------------------------------------------------------- /src/tasks/Associative_array-Iteration.kt: -------------------------------------------------------------------------------- 1 | package `associative_array_iteration` 2 | 3 | fun main(a: Array) { 4 | val map = mapOf("hello" to 1, "world" to 2, "!" to 3) 5 | 6 | with(map) { 7 | entries.forEach { println("key = ${it.key}, value = ${it.value}") } 8 | keys.forEach { println("key = $it") } 9 | values.forEach { println("value = $it") } 10 | } 11 | } -------------------------------------------------------------------------------- /src/tasks/Averages-Arithmetic_mean.kt: -------------------------------------------------------------------------------- 1 | package `averages_arithmetic_mean` 2 | 3 | fun main(args: Array) { 4 | val nums = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) 5 | println("average = %f".format(nums.average())) 6 | } -------------------------------------------------------------------------------- /src/tasks/Averages-Median.kt: -------------------------------------------------------------------------------- 1 | package `averages_median` 2 | 3 | fun median(l: List) = l.sorted().let { (it[it.size / 2] + it[(it.size - 1) / 2]) / 2 } 4 | 5 | fun main(args: Array) { 6 | median(listOf(5.0, 3.0, 4.0)).let { println(it) } // 4 7 | median(listOf(5.0, 4.0, 2.0, 3.0)).let { println(it) } // 3.5 8 | median(listOf(3.0, 4.0, 1.0, -8.4, 7.2, 4.0, 1.0, 1.2)).let { println(it) } // 2.1 9 | } -------------------------------------------------------------------------------- /src/tasks/Averages-Pythagorean_means.kt: -------------------------------------------------------------------------------- 1 | package `averages_pythagorean_means` 2 | 3 | fun Collection.geometricMean() = 4 | if (isEmpty()) Double.NaN 5 | else Math.pow(reduce { n1, n2 -> n1 * n2 }, 1.0 / size) 6 | 7 | fun Collection.harmonicMean() = 8 | if (isEmpty() || contains(0.0)) Double.NaN 9 | else size / reduce { n1, n2 -> n1 + 1.0 / n2 } 10 | 11 | fun main(args: Array) { 12 | val list = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) 13 | val a = list.average() // arithmetic mean 14 | val g = list.geometricMean() 15 | val h = list.harmonicMean() 16 | println("A = %f G = %f H = %f".format(a, g, h)) 17 | println("A >= G is %b, G >= H is %b".format(a >= g, g >= h)) 18 | require(g in h..a) 19 | } -------------------------------------------------------------------------------- /src/tasks/Averages-Root_mean_square.kt: -------------------------------------------------------------------------------- 1 | package `averages_root_mean_square` 2 | 3 | // version 1.0.5-2 4 | 5 | fun quadraticMean(vector: Array) : Double { 6 | val sum = vector.sumByDouble { it * it } 7 | return Math.sqrt(sum / vector.size) 8 | } 9 | 10 | fun main(args: Array) { 11 | val vector = Array(10, { (it + 1).toDouble() }) 12 | print("Quadratic mean of numbers 1 to 10 is ${quadraticMean(vector)}") 13 | } -------------------------------------------------------------------------------- /src/tasks/Averages-Simple_moving_average.kt: -------------------------------------------------------------------------------- 1 | package `averages_simple_moving_average` 2 | 3 | // version 1.0.6 4 | 5 | fun initMovingAverage(p: Int): (Double) -> Double { 6 | if (p < 1) throw IllegalArgumentException("Period must be a positive integer") 7 | val list = mutableListOf() 8 | return { 9 | list.add(it) 10 | if (list.size > p) list.removeAt(0) 11 | list.average() 12 | } 13 | } 14 | 15 | fun main(args: Array) { 16 | val sma4 = initMovingAverage(4) 17 | val sma5 = initMovingAverage(5) 18 | val numbers = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 4.0, 3.0, 2.0, 1.0) 19 | println("num\tsma4\tsma5\n") 20 | for (number in numbers) println("${number}\t${sma4(number)}\t${sma5(number)}") 21 | } -------------------------------------------------------------------------------- /src/tasks/Babbage_problem.kt: -------------------------------------------------------------------------------- 1 | package `babbage_problem` 2 | 3 | fun main(args: Array) { 4 | var number = 520L 5 | var square = 520 * 520L 6 | 7 | while (true) { 8 | val last6 = square.toString().takeLast(6) 9 | if (last6 == "269696") { 10 | println("The smallest number is $number whose square is $square") 11 | return 12 | } 13 | number += 2 14 | square = number * number 15 | } 16 | } -------------------------------------------------------------------------------- /src/tasks/Base64_encode_data.kt: -------------------------------------------------------------------------------- 1 | package `base64_encode_data` 2 | 3 | // version 1.1.2 4 | 5 | import java.io.File 6 | import java.util.Base64 7 | 8 | fun main(args: Array) { 9 | val path = "favicon.ico" // already downloaded to current directory 10 | val bytes = File(path).readBytes() 11 | val base64 = Base64.getEncoder().encodeToString(bytes) 12 | println(base64) 13 | } -------------------------------------------------------------------------------- /src/tasks/Bernoulli_numbers.kt: -------------------------------------------------------------------------------- 1 | package `bernoulli_numbers` 2 | 3 | import org.apache.commons.math3.fraction.BigFraction 4 | 5 | object Bernoulli { 6 | operator fun invoke(n: Int) : BigFraction { 7 | val A = Array(n + 1, init) 8 | for (m in 0..n) 9 | for (j in m downTo 1) 10 | A[j - 1] = A[j - 1].subtract(A[j]).multiply(integers[j]) 11 | return A.first() 12 | } 13 | 14 | val max = 60 15 | 16 | private val init = { m: Int -> BigFraction(1, m + 1) } 17 | private val integers = Array(max + 1, { m: Int -> BigFraction(m) } ) 18 | } 19 | 20 | fun main(args: Array) { 21 | for (n in 0..Bernoulli.max) 22 | if (n % 2 == 0 || n == 1) 23 | System.out.printf("B(%-2d) = %-1s%n", n, Bernoulli(n)) 24 | } -------------------------------------------------------------------------------- /src/tasks/Binary_digits.kt: -------------------------------------------------------------------------------- 1 | package `binary_digits` 2 | 3 | // version 1.0.5-2 4 | 5 | fun main(args: Array) { 6 | val numbers = intArrayOf(5, 50, 9000) 7 | for (number in numbers) println("%4d".format(number) + " -> " + Integer.toBinaryString(number)) 8 | } -------------------------------------------------------------------------------- /src/tasks/Break_OO_privacy.kt: -------------------------------------------------------------------------------- 1 | package `break_oo_privacy` 2 | 3 | import kotlin.reflect.full.declaredMemberProperties 4 | import kotlin.reflect.jvm.isAccessible 5 | 6 | class ToBeBroken { 7 | @Suppress("unused") 8 | private val secret: Int = 42 9 | } 10 | 11 | fun main(args: Array) { 12 | val tbb = ToBeBroken() 13 | val props = ToBeBroken::class.declaredMemberProperties 14 | for (prop in props) { 15 | prop.isAccessible = true // make private properties accessible 16 | println("${prop.name} -> ${prop.get(tbb)}") 17 | } 18 | } -------------------------------------------------------------------------------- /src/tasks/CRC-32.kt: -------------------------------------------------------------------------------- 1 | package `crc_32` 2 | 3 | // version 1.0.6 4 | 5 | import java.util.zip.CRC32 6 | 7 | fun main(args: Array) { 8 | val text = "The quick brown fox jumps over the lazy dog" 9 | val crc = CRC32() 10 | with (crc) { 11 | update(text.toByteArray()) 12 | println("The CRC-32 checksum of '$text' = ${"%x".format(value)}") 13 | } 14 | } -------------------------------------------------------------------------------- /src/tasks/CSV_data_manipulation.kt: -------------------------------------------------------------------------------- 1 | package `csv_data_manipulation` 2 | 3 | // version 1.1.3 4 | 5 | import java.io.File 6 | 7 | fun main(args: Array) { 8 | val lines = File("example.csv").readLines().toMutableList() 9 | lines[0] += ",SUM" 10 | for (i in 1 until lines.size) { 11 | lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } 12 | } 13 | val text = lines.joinToString("\n") 14 | File("example2.csv").writeText(text) // write to new file 15 | println(text) // print to console 16 | } -------------------------------------------------------------------------------- /src/tasks/Calculating_the_value_of_e.kt: -------------------------------------------------------------------------------- 1 | package `calculating_the_value_of_e` 2 | 3 | // Version 1.2.40 4 | 5 | import kotlin.math.abs 6 | 7 | const val EPSILON = 1.0e-15 8 | 9 | fun main(args: Array) { 10 | var fact = 1L 11 | var e = 2.0 12 | var n = 2 13 | do { 14 | val e0 = e 15 | fact *= n++ 16 | e += 1.0 / fact 17 | } 18 | while (abs(e - e0) >= EPSILON) 19 | println("e = %.15f".format(e)) 20 | } -------------------------------------------------------------------------------- /src/tasks/Call_an_object_method.kt: -------------------------------------------------------------------------------- 1 | package `call_an_object_method` 2 | 3 | class MyClass { 4 | fun instanceMethod(s: String) = println(s) 5 | 6 | companion object { 7 | fun staticMethod(s: String) = println(s) 8 | } 9 | } 10 | 11 | fun main(args: Array) { 12 | val mc = MyClass() 13 | mc.instanceMethod("Hello instance world!") 14 | MyClass.staticMethod("Hello static world!") 15 | } -------------------------------------------------------------------------------- /src/tasks/Cantor_set.kt: -------------------------------------------------------------------------------- 1 | package `cantor_set` 2 | 3 | // Version 1.2.31 4 | 5 | const val WIDTH = 81 6 | const val HEIGHT = 5 7 | 8 | val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } } 9 | 10 | fun cantor(start: Int, len: Int, index: Int) { 11 | val seg = len / 3 12 | if (seg == 0) return 13 | for (i in index until HEIGHT) { 14 | for (j in start + seg until start + seg * 2) lines[i][j] = ' ' 15 | } 16 | cantor(start, seg, index + 1) 17 | cantor(start + seg * 2, seg, index + 1) 18 | } 19 | 20 | fun main(args: Array) { 21 | cantor(0, WIDTH, 1) 22 | lines.forEach { println(it) } 23 | } -------------------------------------------------------------------------------- /src/tasks/Case-sensitivity_of_identifiers.kt: -------------------------------------------------------------------------------- 1 | package `case_sensitivity_of_identifiers` 2 | 3 | fun main(args: Array) { 4 | val dog = "Benjamin" 5 | val Dog = "Samba" 6 | val DOG = "Bernie" 7 | println("The three dogs are named $dog, $Dog and $DOG") 8 | } -------------------------------------------------------------------------------- /src/tasks/Casting_out_nines.kt: -------------------------------------------------------------------------------- 1 | package `casting_out_nines` 2 | 3 | // version 1.1.3 4 | 5 | fun castOut(base: Int, start: Int, end: Int): List { 6 | val b = base - 1 7 | val ran = (0 until b).filter { it % b == (it * it) % b } 8 | var x = start / b 9 | val result = mutableListOf() 10 | while (true) { 11 | for (n in ran) { 12 | val k = b * x + n 13 | if (k < start) continue 14 | if (k > end) return result 15 | result.add(k) 16 | } 17 | x++ 18 | } 19 | } 20 | 21 | fun main(args: Array) { 22 | println(castOut(16, 1, 255)) 23 | println() 24 | println(castOut(10, 1, 99)) 25 | println() 26 | println(castOut(17, 1, 288)) 27 | } -------------------------------------------------------------------------------- /src/tasks/Catalan_numbers-Pascals_triangle.kt: -------------------------------------------------------------------------------- 1 | package `catalan_numbers_pascals_triangle` 2 | 3 | // version 1.1.2 4 | 5 | import java.math.BigInteger 6 | 7 | val ONE = BigInteger.ONE 8 | 9 | fun pascal(n: Int, k: Int): BigInteger { 10 | if (n == 0 || k == 0) return ONE 11 | val num = (k + 1..n).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) } 12 | val den = (2..n - k).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) } 13 | return num / den 14 | } 15 | 16 | fun catalanFromPascal(n: Int) { 17 | for (i in 1 until n step 2) { 18 | val mi = i / 2 + 1 19 | val catalan = pascal(i, mi) - pascal(i, mi - 2) 20 | println("${"%2d".format(mi)} : $catalan") 21 | } 22 | } 23 | 24 | fun main(args: Array) { 25 | val n = 15 26 | catalanFromPascal(n * 2) 27 | } -------------------------------------------------------------------------------- /src/tasks/Catamorphism.kt: -------------------------------------------------------------------------------- 1 | package `catamorphism` 2 | 3 | fun main(args: Array) { 4 | val a = intArrayOf(1, 2, 3, 4, 5) 5 | println("Array : ${a.joinToString(", ")}") 6 | println("Sum : ${a.reduce { x, y -> x + y }}") 7 | println("Difference : ${a.reduce { x, y -> x - y }}") 8 | println("Product : ${a.reduce { x, y -> x * y }}") 9 | println("Minimum : ${a.reduce { x, y -> if (x < y) x else y }}") 10 | println("Maximum : ${a.reduce { x, y -> if (x > y) x else y }}") 11 | } -------------------------------------------------------------------------------- /src/tasks/Character_codes.kt: -------------------------------------------------------------------------------- 1 | package `character_codes` 2 | 3 | fun main(args: Array) { 4 | var c = 'a' 5 | var i = c.toInt() 6 | println("$c <-> $i") 7 | i += 2 8 | c = i.toChar() 9 | println("$i <-> $c") 10 | } -------------------------------------------------------------------------------- /src/tasks/Check_that_file_exists.kt: -------------------------------------------------------------------------------- 1 | package `check_that_file_exists` 2 | 3 | // version 1.0.6 4 | 5 | import java.io.File 6 | 7 | fun main(args: Array) { 8 | val filePaths = arrayOf("input.txt", "c:\\input.txt", "zero_length.txt", "`Abdu'l-Bahá.txt") 9 | val dirPaths = arrayOf("docs", "c:\\docs") 10 | for (filePath in filePaths) { 11 | val f = File(filePath) 12 | println("$filePath ${if (f.exists() && !f.isDirectory) "exists" else "does not exist"}") 13 | } 14 | for (dirPath in dirPaths) { 15 | val d = File(dirPath) 16 | println("$dirPath ${if (d.exists() && d.isDirectory) "exists" else "does not exist"}") 17 | } 18 | } -------------------------------------------------------------------------------- /src/tasks/Classes.kt: -------------------------------------------------------------------------------- 1 | package `classes` 2 | 3 | class MyClass(val myInt: Int) { 4 | fun treble(): Int = myInt * 3 5 | } 6 | 7 | fun main(args: Array) { 8 | val mc = MyClass(24) 9 | print("${mc.myInt}, ${mc.treble()}") 10 | } -------------------------------------------------------------------------------- /src/tasks/Closures-Value_capture.kt: -------------------------------------------------------------------------------- 1 | package `closures_value_capture` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | // create an array of 10 anonymous functions which return the square of their index 7 | val funcs = Array(10){ fun(): Int = it * it } 8 | // call all but the last 9 | (0 .. 8).forEach { println(funcs[it]()) } 10 | } -------------------------------------------------------------------------------- /src/tasks/Color_of_a_screen_pixel.kt: -------------------------------------------------------------------------------- 1 | package `color_of_a_screen_pixel` 2 | 3 | import java.awt.* 4 | 5 | fun getMouseColor(): Color { 6 | val location = MouseInfo.getPointerInfo().location 7 | return getColorAt(location.x, location.y) 8 | } 9 | 10 | fun getColorAt(x: Int, y: Int): Color { 11 | return Robot().getPixelColor(x, y) 12 | } -------------------------------------------------------------------------------- /src/tasks/Colour_bars-Display.kt: -------------------------------------------------------------------------------- 1 | package `colour_bars_display` 2 | 3 | import java.awt.Color 4 | import java.awt.Graphics 5 | import javax.swing.JFrame 6 | 7 | class ColorFrame(width: Int, height: Int): JFrame() { 8 | init { 9 | defaultCloseOperation = EXIT_ON_CLOSE 10 | setSize(width, height) 11 | isVisible = true 12 | } 13 | 14 | override fun paint(g: Graphics) { 15 | val colors = listOf(Color.black, Color.red, Color.green, Color.blue, 16 | Color.pink, Color.cyan, Color.yellow, Color.white) 17 | val size = colors.size 18 | for (i in 0 until size) { 19 | g.color = colors[i] 20 | g.fillRect(width / size * i, 0, width / size, height) 21 | } 22 | } 23 | } 24 | 25 | fun main(args: Array) { 26 | ColorFrame(400, 400) 27 | } -------------------------------------------------------------------------------- /src/tasks/Combinations.kt: -------------------------------------------------------------------------------- 1 | package `combinations` 2 | 3 | class Combinations(val m: Int, val n: Int) { 4 | private val combination = IntArray(m) 5 | 6 | init { 7 | generate(0) 8 | } 9 | 10 | private fun generate(k: Int) { 11 | if (k >= m) { 12 | for (i in 0 until m) print("${combination[i]} ") 13 | println() 14 | } 15 | else { 16 | for (j in 0 until n) 17 | if (k == 0 || j > combination[k - 1]) { 18 | combination[k] = j 19 | generate(k + 1) 20 | } 21 | } 22 | } 23 | } 24 | 25 | fun main(args: Array) { 26 | Combinations(3, 5) 27 | } -------------------------------------------------------------------------------- /src/tasks/Command-line_arguments.kt: -------------------------------------------------------------------------------- 1 | package `command_line_arguments` 2 | 3 | fun main(args: Array) { 4 | println("There are " + args.size + " arguments given.") 5 | args.forEachIndexed { i, a -> println("The argument #${i+1} is $a and is at index $i") } 6 | } -------------------------------------------------------------------------------- /src/tasks/Compile-time_calculation.kt: -------------------------------------------------------------------------------- 1 | package `compile_time_calculation` 2 | 3 | // version 1.0.6 4 | const val TEN_FACTORIAL = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 5 | 6 | fun main(args: Array) { 7 | println("10! = $TEN_FACTORIAL") 8 | } -------------------------------------------------------------------------------- /src/tasks/Compound_data_type.kt: -------------------------------------------------------------------------------- 1 | package `compound_data_type` 2 | 3 | data class Point(var x: Int, var y: Int) 4 | 5 | fun main(args: Array) { 6 | val p = Point(1, 2) 7 | println(p) 8 | p.x = 3 9 | p.y = 4 10 | println(p) 11 | } -------------------------------------------------------------------------------- /src/tasks/Concurrent_computing.kt: -------------------------------------------------------------------------------- 1 | package `concurrent_computing` 2 | 3 | // version 1.1.2 4 | 5 | import java.util.concurrent.CyclicBarrier 6 | 7 | class DelayedMessagePrinter(val barrier: CyclicBarrier, val msg: String) : Runnable { 8 | override fun run() { 9 | barrier.await() 10 | println(msg) 11 | } 12 | } 13 | 14 | fun main(args: Array) { 15 | val msgs = listOf("Enjoy", "Rosetta", "Code") 16 | val barrier = CyclicBarrier(msgs.size) 17 | for (msg in msgs) Thread(DelayedMessagePrinter(barrier, msg)).start() 18 | } -------------------------------------------------------------------------------- /src/tasks/Constrained_random_points_on_a_circle.kt: -------------------------------------------------------------------------------- 1 | package `constrained_random_points_on_a_circle` 2 | 3 | // version 1.1.3 4 | 5 | fun main(args: Array) { 6 | val r = java.util.Random() 7 | val points = Array(31) { CharArray(31) { ' ' } } 8 | var count = 0 9 | while (count < 100) { 10 | val x = r.nextInt(31) - 15 11 | val y = r.nextInt(31) - 15 12 | val h = x * x + y * y 13 | if (h in 100..225) { 14 | points[x + 15][y + 15] = 'o' 15 | count++ 16 | } 17 | } 18 | for (i in 0..30) println(points[i].joinToString("")) 19 | } -------------------------------------------------------------------------------- /src/tasks/Continued_fraction.kt: -------------------------------------------------------------------------------- 1 | package `continued_fraction` 2 | 3 | // version 1.1.2 4 | 5 | typealias Func = (Int) -> IntArray 6 | 7 | fun calc(f: Func, n: Int): Double { 8 | var temp = 0.0 9 | for (i in n downTo 1) { 10 | val p = f(i) 11 | temp = p[1] / (p[0] + temp) 12 | } 13 | return f(0)[0] + temp 14 | } 15 | 16 | fun main(args: Array) { 17 | val pList = listOf>( 18 | "sqrt(2)" to { n -> intArrayOf(if (n > 0) 2 else 1, 1) }, 19 | "e " to { n -> intArrayOf(if (n > 0) n else 2, if (n > 1) n - 1 else 1) }, 20 | "pi " to { n -> intArrayOf(if (n > 0) 6 else 3, (2 * n - 1) * (2 * n - 1)) } 21 | ) 22 | for (pair in pList) println("${pair.first} = ${calc(pair.second, 200)}") 23 | } -------------------------------------------------------------------------------- /src/tasks/Copy_a_string.kt: -------------------------------------------------------------------------------- 1 | package `copy_a_string` 2 | 3 | val s = "Hello" 4 | val alias = s // alias === s 5 | val copy = "" + s // copy !== s -------------------------------------------------------------------------------- /src/tasks/Count_in_octal.kt: -------------------------------------------------------------------------------- 1 | package `count_in_octal` 2 | 3 | // version 1.1 4 | 5 | // counts up to 177 octal i.e. 127 decimal 6 | fun main(args: Array) { 7 | (0..Byte.MAX_VALUE).forEach { println("%03o".format(it)) } 8 | } -------------------------------------------------------------------------------- /src/tasks/Count_occurrences_of_a_substring.kt: -------------------------------------------------------------------------------- 1 | package `count_occurrences_of_a_substring` 2 | 3 | // version 1.0.6 4 | 5 | fun countSubstring(s: String, sub: String): Int = s.split(sub).size - 1 6 | 7 | fun main(args: Array) { 8 | println(countSubstring("the three truths","th")) 9 | println(countSubstring("ababababab","abab")) 10 | println(countSubstring("","")) 11 | } -------------------------------------------------------------------------------- /src/tasks/Count_the_coins.kt: -------------------------------------------------------------------------------- 1 | package `count_the_coins` 2 | 3 | // version 1.0.6 4 | 5 | fun countCoins(c: IntArray, m: Int, n: Int): Long { 6 | val table = LongArray(n + 1) 7 | table[0] = 1 8 | for (i in 0 until m) 9 | for (j in c[i]..n) table[j] += table[j - c[i]] 10 | return table[n] 11 | } 12 | 13 | fun main(args: Array) { 14 | val c = intArrayOf(1, 5, 10, 25, 50, 100) 15 | println(countCoins(c, 4, 100)) 16 | println(countCoins(c, 6, 1000 * 100)) 17 | } -------------------------------------------------------------------------------- /src/tasks/Create_a_file.kt: -------------------------------------------------------------------------------- 1 | package `create_a_file` 2 | 3 | /* testing on Windows 10 which needs administrative privileges 4 | to create files in the root */ 5 | 6 | import java.io.File 7 | 8 | fun main(args: Array) { 9 | val filePaths = arrayOf("output.txt", "c:\\output.txt") 10 | val dirPaths = arrayOf("docs", "c:\\docs") 11 | var f: File 12 | for (path in filePaths) { 13 | f = File(path) 14 | if (f.createNewFile()) 15 | println("$path successfully created") 16 | else 17 | println("$path already exists") 18 | } 19 | for (path in dirPaths) { 20 | f = File(path) 21 | if (f.mkdir()) 22 | println("$path successfully created") 23 | else 24 | println("$path already exists") 25 | } 26 | } -------------------------------------------------------------------------------- /src/tasks/Create_a_file_on_magnetic_tape.kt: -------------------------------------------------------------------------------- 1 | package `create_a_file_on_magnetic_tape` 2 | 3 | // version 1.1.0 (Linux) 4 | 5 | import java.io.FileWriter 6 | 7 | fun main(args: Array) { 8 | val lp0 = FileWriter("/dev/tape") 9 | lp0.write("Hello, world!") 10 | lp0.close() 11 | } -------------------------------------------------------------------------------- /src/tasks/Create_a_two-dimensional_array_at_runtime.kt: -------------------------------------------------------------------------------- 1 | package `create_a_two_dimensional_array_at_runtime` 2 | 3 | fun main(args: Array) { 4 | // build 5 | val dim = arrayOf(10, 15) 6 | val array = Array(dim[0], { IntArray(dim[1]) } ) 7 | 8 | // fill 9 | array.forEachIndexed { i, it -> 10 | it.indices.forEach { j -> 11 | it[j] = 1 + i + j 12 | } 13 | } 14 | 15 | // print 16 | array.forEach { println(it.asList()) } 17 | } -------------------------------------------------------------------------------- /src/tasks/Create_an_object-Native_demonstration.kt: -------------------------------------------------------------------------------- 1 | package `create_an_object_native_demonstration` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args: Array) { 6 | // This line creates a read-only map which cannot be changed in any way nor cleared 7 | val map = mapOf('A' to 65, 'B' to 66, 'C' to 67) 8 | println(map) 9 | } -------------------------------------------------------------------------------- /src/tasks/Cumulative_standard_deviation.kt: -------------------------------------------------------------------------------- 1 | package `cumulative_standard_deviation` 2 | 3 | // version 1.0.5-2 4 | 5 | class CumStdDev { 6 | private var n = 0 7 | private var sum = 0.0 8 | private var sum2 = 0.0 9 | 10 | fun sd(x: Double): Double { 11 | n++ 12 | sum += x 13 | sum2 += x * x 14 | return Math.sqrt(sum2 / n - sum * sum / n / n) 15 | } 16 | } 17 | 18 | fun main(args: Array) { 19 | val testData = doubleArrayOf(2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0) 20 | val csd = CumStdDev() 21 | for (d in testData) println("Add $d => ${csd.sd(d)}") 22 | } -------------------------------------------------------------------------------- /src/tasks/Currency.kt: -------------------------------------------------------------------------------- 1 | package `currency` 2 | 3 | // version 1.1.2 4 | 5 | import java.math.BigDecimal 6 | import java.math.MathContext 7 | 8 | fun main(args: Array) { 9 | val mc = MathContext.DECIMAL128 10 | val nHamburger = BigDecimal("4000000000000000", mc) 11 | val pHamburger = BigDecimal("5.50") 12 | val nMilkshakes = BigDecimal("2", mc) 13 | val pMilkshakes = BigDecimal("2.86") 14 | val taxRate = BigDecimal("0.0765") 15 | val price = nHamburger * pHamburger + nMilkshakes * pMilkshakes 16 | val tax = price * taxRate 17 | val fmt = "%20.2f" 18 | println("Total price before tax : ${fmt.format(price)}") 19 | println("Tax thereon @ 7.65% : ${fmt.format(tax)}") 20 | println("Total price after tax : ${fmt.format(price + tax)}") 21 | } -------------------------------------------------------------------------------- /src/tasks/Currying.kt: -------------------------------------------------------------------------------- 1 | package `currying` 2 | 3 | // version 1.1.2 4 | 5 | fun curriedAdd(x: Int) = { y: Int -> x + y } 6 | 7 | fun main(args: Array) { 8 | val a = 2 9 | val b = 3 10 | val sum = curriedAdd(a)(b) 11 | println("$a + $b = $sum") 12 | } -------------------------------------------------------------------------------- /src/tasks/DNS_query.kt: -------------------------------------------------------------------------------- 1 | package `dns_query` 2 | 3 | // version 1.1.3 4 | 5 | import java.net.InetAddress 6 | import java.net.Inet4Address 7 | import java.net.Inet6Address 8 | 9 | fun showIPAddresses(host: String) { 10 | try { 11 | val ipas = InetAddress.getAllByName(host) 12 | println("The IP address(es) for '$host' is/are:\n") 13 | for (ipa in ipas) { 14 | print(when (ipa) { 15 | is Inet4Address -> " ipv4 : " 16 | is Inet6Address -> " ipv6 : " 17 | else -> " ipv? : " 18 | }) 19 | println(ipa.hostAddress) 20 | } 21 | } 22 | catch (ex: Exception) { 23 | println(ex.message) 24 | } 25 | } 26 | 27 | fun main(args: Array) { 28 | showIPAddresses("www.kame.net") 29 | } -------------------------------------------------------------------------------- /src/tasks/Date_format.kt: -------------------------------------------------------------------------------- 1 | package `date_format` 2 | 3 | // version 1.0.6 4 | 5 | import java.util.GregorianCalendar 6 | 7 | fun main(args: Array) { 8 | val now = GregorianCalendar() 9 | println("%tF".format(now)) 10 | println("%tA, %1\$tB %1\$te, %1\$tY".format(now)) 11 | } -------------------------------------------------------------------------------- /src/tasks/Date_manipulation.kt: -------------------------------------------------------------------------------- 1 | package `date_manipulation` 2 | 3 | // version 1.0.6 4 | 5 | import java.text.SimpleDateFormat 6 | import java.util.* 7 | 8 | fun main(args: Array) { 9 | val dts = "March 7 2009 7:30pm EST" 10 | val sdf = SimpleDateFormat("MMMM d yyyy h:mma z") 11 | val dt = sdf.parse(dts) 12 | val cal = GregorianCalendar(TimeZone.getTimeZone("EST")) // stay with EST 13 | cal.time = dt 14 | cal.add(Calendar.HOUR_OF_DAY, 12) // add 12 hours 15 | val fmt = "%tB %1\$td %1\$tY %1\$tl:%1\$tM%1\$tp %1\$tZ" 16 | println(fmt.format(cal)) // display new time 17 | 18 | // display time now in Mountain Standard Time which is 2 hours earlier than EST 19 | cal.timeZone = TimeZone.getTimeZone("MST") 20 | println(fmt.format(cal)) 21 | } -------------------------------------------------------------------------------- /src/tasks/Day_of_the_week.kt: -------------------------------------------------------------------------------- 1 | package `day_of_the_week` 2 | 3 | // version 1.0.6 4 | 5 | import java.util.* 6 | 7 | fun main(args: Array) { 8 | println("Christmas day in the following years falls on a Sunday:\n") 9 | val calendar = GregorianCalendar(2008, Calendar.DECEMBER, 25) 10 | for (year in 2008..2121) { 11 | if (Calendar.SUNDAY == calendar[Calendar.DAY_OF_WEEK]) println(year) 12 | calendar.add(Calendar.YEAR, 1) 13 | } 14 | } -------------------------------------------------------------------------------- /src/tasks/Delegates.kt: -------------------------------------------------------------------------------- 1 | package `delegates` 2 | 3 | // version 1.1.51 4 | 5 | interface Thingable { 6 | fun thing(): String? 7 | } 8 | 9 | class Delegate(val responds: Boolean) : Thingable { 10 | override fun thing() = if (responds) "delegate implementation" else null 11 | } 12 | 13 | class Delegator(d: Delegate) : Thingable by d { 14 | fun operation() = thing() ?: "default implementation" 15 | } 16 | 17 | fun main(args: Array) { 18 | // delegate doesn't respond to 'thing' 19 | val d = Delegate(false) 20 | val dd = Delegator(d) 21 | println(dd.operation()) 22 | 23 | // delegate responds to 'thing' 24 | val d2 = Delegate(true) 25 | val dd2 = Delegator(d2) 26 | println(dd2.operation()) 27 | } -------------------------------------------------------------------------------- /src/tasks/Delete_a_file.kt: -------------------------------------------------------------------------------- 1 | package `delete_a_file` 2 | 3 | // version 1.0.6 4 | 5 | /* testing on Windows 10 which needs administrative privileges 6 | to delete files from the root */ 7 | 8 | import java.io.File 9 | 10 | fun main(args: Array) { 11 | val paths = arrayOf("input.txt", "docs", "c:\\input.txt", "c:\\docs") 12 | var f: File 13 | for (path in paths) { 14 | f = File(path) 15 | if (f.delete()) 16 | println("$path successfully deleted") 17 | else 18 | println("$path could not be deleted") 19 | } 20 | } -------------------------------------------------------------------------------- /src/tasks/Department_Numbers.kt: -------------------------------------------------------------------------------- 1 | package `department_numbers` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args: Array) { 6 | println("Police Sanitation Fire") 7 | println("------ ---------- ----") 8 | var count = 0 9 | for (i in 2..6 step 2) { 10 | for (j in 1..7) { 11 | if (j == i) continue 12 | for (k in 1..7) { 13 | if (k == i || k == j) continue 14 | if (i + j + k != 12) continue 15 | println(" $i $j $k") 16 | count++ 17 | } 18 | } 19 | } 20 | println("\n$count valid combinations") 21 | } -------------------------------------------------------------------------------- /src/tasks/Detect_division_by_zero.kt: -------------------------------------------------------------------------------- 1 | package `detect_division_by_zero` 2 | 3 | // version 1.1 4 | 5 | fun divideByZero(x: Int, y:Int): Boolean = 6 | try { 7 | x / y 8 | false 9 | } catch(e: ArithmeticException) { 10 | true 11 | } 12 | 13 | fun main(args: Array) { 14 | val x = 1 15 | val y = 0 16 | if (divideByZero(x, y)) { 17 | println("Attempted to divide by zero") 18 | } else { 19 | @Suppress("DIVISION_BY_ZERO") 20 | println("$x / $y = ${x / y}") 21 | } 22 | } -------------------------------------------------------------------------------- /src/tasks/Determine_if_a_string_is_numeric.kt: -------------------------------------------------------------------------------- 1 | package `determine_if_a_string_is_numeric` 2 | 3 | // version 1.1 4 | 5 | fun isNumeric(input: String): Boolean = 6 | try { 7 | input.toDouble() 8 | true 9 | } catch(e: NumberFormatException) { 10 | false 11 | } 12 | 13 | fun main(args: Array) { 14 | val inputs = arrayOf("152", "-3.1415926", "Foo123", "-0", "456bar", "1.0E10") 15 | for (input in inputs) println("$input is ${if (isNumeric(input)) "numeric" else "not numeric"}") 16 | } -------------------------------------------------------------------------------- /src/tasks/Documentation.kt: -------------------------------------------------------------------------------- 1 | package `documentation` 2 | 3 | /** 4 | * A group of *members*. 5 | * @author A Programmer. 6 | * @since version 1.1.51. 7 | * 8 | * This class has no useful logic; it's just a documentation example. 9 | * 10 | * @param T the type of a member in this group. 11 | * @property name the name of this group. 12 | * @constructor Creates an empty group. 13 | */ 14 | class Group(val name: String) { 15 | /** 16 | * Adds a [member] to this group. 17 | * @throws AddException if the member can't be added. 18 | * @return the new size of the group. 19 | */ 20 | fun add(member: T): Int { TODO() } 21 | } -------------------------------------------------------------------------------- /src/tasks/Dot_product.kt: -------------------------------------------------------------------------------- 1 | package `dot_product` 2 | 3 | fun dot(v1: Array, v2: Array) = 4 | v1.zip(v2).map { it.first * it.second }.reduce { a, b -> a + b } 5 | 6 | fun main(args: Array) { 7 | dot(arrayOf(1.0, 3.0, -5.0), arrayOf(4.0, -2.0, -1.0)).let { println(it) } 8 | } -------------------------------------------------------------------------------- /src/tasks/Doubly-linked_list-Element_definition.kt: -------------------------------------------------------------------------------- 1 | package `doubly_linked_list_element_definition` 2 | 3 | // version 1.1.2 4 | 5 | class Node(var data: T, var prev: Node? = null, var next: Node? = null) { 6 | override fun toString(): String { 7 | val sb = StringBuilder(this.data.toString()) 8 | var node = this.next 9 | while (node != null) { 10 | sb.append(" -> ", node.data.toString()) 11 | node = node.next 12 | } 13 | return sb.toString() 14 | } 15 | } 16 | 17 | fun main(args: Array) { 18 | val n1 = Node(1) 19 | val n2 = Node(2, n1) 20 | n1.next = n2 21 | val n3 = Node(3, n2) 22 | n2.next = n3 23 | println(n1) 24 | println(n2) 25 | println(n3) 26 | } -------------------------------------------------------------------------------- /src/tasks/Empty_directory.kt: -------------------------------------------------------------------------------- 1 | package `empty_directory` 2 | 3 | // version 1.1.4 4 | 5 | import java.io.File 6 | 7 | fun main(args: Array) { 8 | val dirPath = "docs" // or whatever 9 | val isEmpty = (File(dirPath).list().isEmpty()) 10 | println("$dirPath is ${if (isEmpty) "empty" else "not empty"}") 11 | } -------------------------------------------------------------------------------- /src/tasks/Empty_program.kt: -------------------------------------------------------------------------------- 1 | package `empty_program` 2 | 3 | fun main(a: Array) {} -------------------------------------------------------------------------------- /src/tasks/Empty_string.kt: -------------------------------------------------------------------------------- 1 | package `empty_string` 2 | 3 | fun main(args: Array) { 4 | val s = "" 5 | println(s.isEmpty()) // true 6 | println(s.isNotEmpty()) // false 7 | println(s.length) // 0 8 | println(s.none()) // true 9 | println(s.any()) // false 10 | } -------------------------------------------------------------------------------- /src/tasks/Entropy-Narcissist.kt: -------------------------------------------------------------------------------- 1 | package `entropy_narcissist` 2 | 3 | // version 1.1.0 (entropy_narc.kt) 4 | 5 | fun log2(d: Double) = Math.log(d) / Math.log(2.0) 6 | 7 | fun shannon(s: String): Double { 8 | val counters = mutableMapOf() 9 | for (c in s) { 10 | if (counters.containsKey(c)) counters[c] = counters[c]!! + 1 11 | else counters.put(c, 1) 12 | } 13 | val nn = s.length.toDouble() 14 | var sum = 0.0 15 | for (key in counters.keys) { 16 | val term = counters[key]!! / nn 17 | sum += term * log2(term) 18 | } 19 | return -sum 20 | } 21 | 22 | fun main(args: Array) { 23 | val prog = java.io.File("entropy_narc.kt").readText() 24 | println("This program's entropy is ${"%18.16f".format(shannon(prog))}") 25 | } -------------------------------------------------------------------------------- /src/tasks/Enumerations.kt: -------------------------------------------------------------------------------- 1 | package `enumerations` 2 | 3 | // version 1.0.5-2 4 | 5 | enum class Animals { 6 | CAT, DOG, ZEBRA 7 | } 8 | 9 | enum class Dogs(val id: Int) { 10 | BULLDOG(1), TERRIER(2), WOLFHOUND(4) 11 | } 12 | 13 | fun main(args: Array) { 14 | for (value in Animals.values()) println("${value.name.padEnd(5)} : ${value.ordinal}") 15 | println() 16 | for (value in Dogs.values()) println("${value.name.padEnd(9)} : ${value.id}") 17 | } -------------------------------------------------------------------------------- /src/tasks/Environment_variables.kt: -------------------------------------------------------------------------------- 1 | package `environment_variables` 2 | 3 | // version 1.0.6 4 | 5 | // tested on Windows 10 6 | 7 | fun main(args: Array) { 8 | println(System.getenv("SystemRoot")) 9 | } -------------------------------------------------------------------------------- /src/tasks/Ethiopian_multiplication.kt: -------------------------------------------------------------------------------- 1 | package `ethiopian_multiplication` 2 | 3 | // version 1.1.2 4 | 5 | fun halve(n: Int) = n / 2 6 | 7 | fun double(n: Int) = n * 2 8 | 9 | fun isEven(n: Int) = n % 2 == 0 10 | 11 | fun ethiopianMultiply(x: Int, y: Int): Int { 12 | var xx = x 13 | var yy = y 14 | var sum = 0 15 | while (xx >= 1) { 16 | if (!isEven(xx)) sum += yy 17 | xx = halve(xx) 18 | yy = double(yy) 19 | } 20 | return sum 21 | } 22 | 23 | fun main(args: Array) { 24 | println("17 x 34 = ${ethiopianMultiply(17, 34)}") 25 | println("99 x 99 = ${ethiopianMultiply(99, 99)}") 26 | } -------------------------------------------------------------------------------- /src/tasks/Eulers_sum_of_powers_conjecture.kt: -------------------------------------------------------------------------------- 1 | package `eulers_sum_of_powers_conjecture` 2 | 3 | fun main(args: Array) { 4 | val p5 = LongArray(250){ it.toLong() * it * it * it * it } 5 | var sum: Long 6 | var y: Int 7 | var found = false 8 | loop@ for (x0 in 0 .. 249) 9 | for (x1 in 0 .. x0 - 1) 10 | for (x2 in 0 .. x1 - 1) 11 | for (x3 in 0 .. x2 - 1) { 12 | sum = p5[x0] + p5[x1] + p5[x2] + p5[x3] 13 | y = p5.binarySearch(sum) 14 | if (y >= 0) { 15 | println("$x0^5 + $x1^5 + $x2^5 + $x3^5 = $y^5") 16 | found = true 17 | break@loop 18 | } 19 | } 20 | if (!found) println("No solution was found") 21 | } -------------------------------------------------------------------------------- /src/tasks/Evaluate_binomial_coefficients.kt: -------------------------------------------------------------------------------- 1 | package `evaluate_binomial_coefficients` 2 | 3 | // version 1.0.5-2 4 | 5 | fun factorial(n: Int) = when { 6 | n < 0 -> throw IllegalArgumentException("negative numbers not allowed") 7 | else -> { 8 | var ans = 1L 9 | for (i in 2..n) ans *= i 10 | ans 11 | } 12 | } 13 | 14 | fun binomial(n: Int, k: Int) = when { 15 | n < 0 || k < 0 -> throw IllegalArgumentException("negative numbers not allowed") 16 | n == k -> 1L 17 | else -> { 18 | var ans = 1L 19 | for (i in n - k + 1..n) ans *= i 20 | ans / factorial(k) 21 | } 22 | } 23 | 24 | fun main(args: Array) { 25 | for (n in 0..14) { 26 | for (k in 0..n) 27 | print("%4d ".format(binomial(n, k))) 28 | println() 29 | } 30 | } -------------------------------------------------------------------------------- /src/tasks/Even_or_odd.kt: -------------------------------------------------------------------------------- 1 | package `even_or_odd` 2 | 3 | // version 1.0.5-2 4 | 5 | fun main(args: Array) { 6 | while (true) { 7 | print("Enter an integer or 0 to finish : ") 8 | val n = readLine()!!.toInt() 9 | when { 10 | n == 0 -> return 11 | n % 2 == 0 -> println("Your number is even") 12 | else -> println("Your number is odd") 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /src/tasks/Exceptions-Catch_an_exception_thrown_in_a_nested_call.kt: -------------------------------------------------------------------------------- 1 | package `exceptions_catch_an_exception_thrown_in_a_nested_call` 2 | 3 | // version 1.0.6 4 | 5 | class U0 : Throwable("U0 occurred") 6 | class U1 : Throwable("U1 occurred") 7 | 8 | fun foo() { 9 | for (i in 1..2) { 10 | try { 11 | bar(i) 12 | } catch(e: U0) { 13 | println(e.message) 14 | } 15 | } 16 | } 17 | 18 | fun bar(i: Int) { 19 | baz(i) 20 | } 21 | 22 | fun baz(i: Int) { 23 | when (i) { 24 | 1 -> throw U0() 25 | 2 -> throw U1() 26 | } 27 | } 28 | 29 | fun main(args: Array) { 30 | foo() 31 | } -------------------------------------------------------------------------------- /src/tasks/Exceptions.kt: -------------------------------------------------------------------------------- 1 | package `exceptions` 2 | 3 | // version 1.0.6 4 | 5 | // In Kotlin all Exception classes derive from Throwable and, by convention, end with the word 'Exception' 6 | class MyException (override val message: String?): Throwable(message) 7 | 8 | fun foo() { 9 | throw MyException("Bad foo!") 10 | } 11 | 12 | fun goo() { 13 | try { 14 | foo() 15 | } 16 | catch (me: MyException) { 17 | println("Caught MyException due to '${me.message}'") 18 | println("\nThe stack trace is:\n") 19 | me.printStackTrace() 20 | } 21 | } 22 | 23 | fun main(args: Array) { 24 | goo() 25 | } -------------------------------------------------------------------------------- /src/tasks/Execute_a_system_command.kt: -------------------------------------------------------------------------------- 1 | package `execute_a_system_command` 2 | 3 | // version 1.0.6 4 | 5 | import java.util.Scanner 6 | 7 | fun main(args: Array) { 8 | val proc = Runtime.getRuntime().exec("cmd /C dir") // testing on Windows 10 9 | Scanner(proc.inputStream).use { 10 | while (it.hasNextLine()) println(it.nextLine()) 11 | } 12 | } -------------------------------------------------------------------------------- /src/tasks/Exponentiation_order.kt: -------------------------------------------------------------------------------- 1 | package `exponentiation_order` 2 | 3 | // version 1.0.5-2 4 | 5 | infix fun Int.ipow(exp: Int): Int = when { 6 | exp < 0 -> throw IllegalArgumentException("negative exponents not allowed") 7 | exp == 0 -> 1 8 | else -> { 9 | var ans = 1 10 | var base = this 11 | var e = exp 12 | while(e != 0) { 13 | if (e and 1 == 1) ans *= base 14 | e = e shr 1 15 | base *= base 16 | } 17 | ans 18 | } 19 | } 20 | 21 | fun main(args: Array) { 22 | println("5**3**2 = ${5 ipow 3 ipow 2}") 23 | println("(5**3)**2 = ${(5 ipow 3) ipow 2}") 24 | println("5**(3**2) = ${5 ipow (3 ipow 2)}") 25 | } -------------------------------------------------------------------------------- /src/tasks/Factorial.kt: -------------------------------------------------------------------------------- 1 | package `factorial` 2 | 3 | fun facti(n: Int) = when { 4 | n < 0 -> throw IllegalArgumentException("negative numbers not allowed") 5 | else -> { 6 | var ans = 1L 7 | for (i in 2..n) ans *= i 8 | ans 9 | } 10 | } 11 | 12 | fun factr(n: Int): Long = when { 13 | n < 0 -> throw IllegalArgumentException("negative numbers not allowed") 14 | n < 2 -> 1L 15 | else -> n * factr(n - 1) 16 | } 17 | 18 | fun main(args: Array) { 19 | val n = 20 20 | println("$n! = " + facti(n)) 21 | println("$n! = " + factr(n)) 22 | } -------------------------------------------------------------------------------- /src/tasks/Factors_of_an_integer.kt: -------------------------------------------------------------------------------- 1 | package `factors_of_an_integer` 2 | 3 | fun printFactors(n: Int) { 4 | if (n < 1) return 5 | print("$n => ") 6 | (1..n / 2) 7 | .filter { n % it == 0 } 8 | .forEach { print("$it ") } 9 | println(n) 10 | } 11 | 12 | fun main(args: Array) { 13 | val numbers = intArrayOf(11, 21, 32, 45, 67, 96) 14 | for (number in numbers) printFactors(number) 15 | } -------------------------------------------------------------------------------- /src/tasks/Farey_sequence.kt: -------------------------------------------------------------------------------- 1 | package `farey_sequence` 2 | 3 | // version 1.1 4 | 5 | fun farey(n: Int): List { 6 | var a = 0 7 | var b = 1 8 | var c = 1 9 | var d = n 10 | val f = mutableListOf("$a/$b") 11 | while (c <= n) { 12 | val k = (n + b) / d 13 | val aa = a 14 | val bb = b 15 | a = c 16 | b = d 17 | c = k * c - aa 18 | d = k * d - bb 19 | f.add("$a/$b") 20 | } 21 | return f.toList() 22 | } 23 | 24 | fun main(args: Array) { 25 | for (i in 1..11) 26 | println("${"%2d".format(i)}: ${farey(i).joinToString(" ")}") 27 | println() 28 | for (i in 100..1000 step 100) 29 | println("${"%4d".format(i)}: ${"%6d".format(farey(i).size)} fractions") 30 | } -------------------------------------------------------------------------------- /src/tasks/Fast_Fourier_transform-2.kt: -------------------------------------------------------------------------------- 1 | package fft 2 | 3 | fun Array<*>.println() = println(joinToString(prefix = "[", postfix = "]")) 4 | 5 | fun main(args: Array) { 6 | val data = arrayOf(Complex(1.0, 0.0), Complex(1.0, 0.0), Complex(1.0, 0.0), Complex(1.0, 0.0), 7 | Complex(0.0, 0.0), Complex(0.0, 2.0), Complex(0.0, 0.0), Complex(0.0, 0.0)) 8 | 9 | val a = FFT.fft(data) 10 | a.println() 11 | FFT.rfft(a).println() 12 | } -------------------------------------------------------------------------------- /src/tasks/File_input-output.kt: -------------------------------------------------------------------------------- 1 | package `file_input_output` 2 | 3 | // version 1.1.2 4 | 5 | import java.io.File 6 | 7 | fun main(args: Array) { 8 | val text = File("input.txt").readText() 9 | File("output.txt").writeText(text) 10 | } -------------------------------------------------------------------------------- /src/tasks/File_modification_time.kt: -------------------------------------------------------------------------------- 1 | package `file_modification_time` 2 | 3 | // version 1.0.6 4 | 5 | import java.io.File 6 | 7 | fun main(args: Array) { 8 | val filePath = "input.txt" // or whatever 9 | val file = File(filePath) 10 | with (file) { 11 | println("%tc".format(lastModified())) 12 | // update to current time, say 13 | setLastModified(System.currentTimeMillis()) 14 | println("%tc".format(lastModified())) 15 | } 16 | } -------------------------------------------------------------------------------- /src/tasks/File_size.kt: -------------------------------------------------------------------------------- 1 | package `file_size` 2 | 3 | // version 1.0.6 4 | 5 | import java.io.File 6 | 7 | fun main(args: Array) { 8 | val paths = arrayOf("input.txt", "c:\\input.txt") 9 | for (path in paths) 10 | println("Length of $path is ${File(path).length()} bytes") 11 | } -------------------------------------------------------------------------------- /src/tasks/Filter.kt: -------------------------------------------------------------------------------- 1 | package `filter` 2 | 3 | // version 1.0.5-2 4 | 5 | fun main(args: Array) { 6 | val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9) 7 | println(array.joinToString(" ")) 8 | 9 | val filteredArray = array.filter{ it % 2 == 0 } 10 | println(filteredArray.joinToString(" ")) 11 | 12 | val mutableList = array.toMutableList() 13 | mutableList.retainAll { it % 2 == 0 } 14 | println(mutableList.joinToString(" ")) 15 | } -------------------------------------------------------------------------------- /src/tasks/Find_limit_of_recursion.kt: -------------------------------------------------------------------------------- 1 | package `find_limit_of_recursion` 2 | 3 | // version 1.1.2 4 | 5 | fun recurse(i: Int) { 6 | try { 7 | recurse(i + 1) 8 | } 9 | catch(e: StackOverflowError) { 10 | println("Limit of recursion is $i") 11 | } 12 | } 13 | 14 | fun main(args: Array) = recurse(0) -------------------------------------------------------------------------------- /src/tasks/First-class_functions-Use_numbers_analogously.kt: -------------------------------------------------------------------------------- 1 | package `first_class_functions_use_numbers_analogously` 2 | 3 | // version 1.1.2 4 | 5 | fun multiplier(n1: Double, n2: Double) = { m: Double -> n1 * n2 * m} 6 | 7 | fun main(args: Array) { 8 | val x = 2.0 9 | val xi = 0.5 10 | val y = 4.0 11 | val yi = 0.25 12 | val z = x + y 13 | val zi = 1.0 / ( x + y) 14 | val a = doubleArrayOf(x, y, z) 15 | val ai = doubleArrayOf(xi, yi, zi) 16 | val m = 0.5 17 | for (i in 0 until a.size) { 18 | println("${multiplier(a[i], ai[i])(m)} = multiplier(${a[i]}, ${ai[i]})($m)") 19 | } 20 | } -------------------------------------------------------------------------------- /src/tasks/First-class_functions.kt: -------------------------------------------------------------------------------- 1 | package `first_class_functions` 2 | 3 | // version 1.0.6 4 | 5 | fun compose(f: (Double) -> Double, g: (Double) -> Double ): (Double) -> Double = { f(g(it)) } 6 | 7 | fun cube(d: Double) = d * d * d 8 | 9 | fun main(args: Array) { 10 | val listA = listOf(Math::sin, Math::cos, ::cube) 11 | val listB = listOf(Math::asin, Math::acos, Math::cbrt) 12 | val x = 0.5 13 | for (i in 0..2) println(compose(listA[i], listB[i])(x)) 14 | } -------------------------------------------------------------------------------- /src/tasks/FizzBuzz-1.kt: -------------------------------------------------------------------------------- 1 | package `fizzbuzz_1` 2 | 3 | fun fizzBuzz1() { 4 | fun fizzBuzz(x: Int) = if (x % 15 == 0) "FizzBuzz" else x.toString() 5 | fun fizz(x: Any) = if (x is Int && x % 3 == 0) "Buzz" else x 6 | fun buzz(x: Any) = if (x is Int && x.toInt() % 5 == 0) "Fizz" else x 7 | 8 | (1..100).map { fizzBuzz(it) }.map { fizz(it) }.map { buzz(it) }.forEach { println(it) } 9 | } -------------------------------------------------------------------------------- /src/tasks/FizzBuzz-2.kt: -------------------------------------------------------------------------------- 1 | package `fizzbuzz_2` 2 | 3 | fun fizzBuzz2() { 4 | fun fizz(x: Pair) = if(x.first % 3 == 0) x.apply { second.append("Fizz") } else x 5 | fun buzz(x: Pair) = if(x.first % 5 == 0) x.apply { second.append("Buzz") } else x 6 | fun none(x: Pair) = if(x.second.isBlank()) x.second.apply { append(x.first) } else x.second 7 | 8 | (1..100).map { Pair(it, StringBuilder()) } 9 | .map { fizz(it) } 10 | .map { buzz(it) } 11 | .map { none(it) } 12 | .forEach { println(it) } 13 | } -------------------------------------------------------------------------------- /src/tasks/FizzBuzz.kt: -------------------------------------------------------------------------------- 1 | package `fizzbuzz` 2 | 3 | fun fizzBuzz() { 4 | for (i in 1..100) { 5 | when { 6 | i % 15 == 0 -> println("FizzBuzz") 7 | i % 3 == 0 -> println("Fizz") 8 | i % 5 == 0 -> println("Buzz") 9 | else -> println(i) 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /src/tasks/Flatten_a_list-1.kt: -------------------------------------------------------------------------------- 1 | package `flatten_a_list_1` 2 | 3 | fun flatten(list: List<*>): List<*> { 4 | fun flattenElement(elem: Any?): Iterable<*> { 5 | return if (elem is List<*>) 6 | if (elem.isEmpty()) elem 7 | else flattenElement(elem.first()) + flattenElement(elem.drop(1)) 8 | else listOf(elem) 9 | } 10 | return list.flatMap { elem -> flattenElement(elem) } 11 | } -------------------------------------------------------------------------------- /src/tasks/Flow-control_structures.kt: -------------------------------------------------------------------------------- 1 | package `flow_control_structures` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | for (i in 0 .. 2) { 7 | for (j in 0 .. 2) { 8 | if (i + j == 2) continue 9 | if (i + j == 3) break 10 | println(i + j) 11 | } 12 | } 13 | println() 14 | if (args.isNotEmpty()) throw IllegalArgumentException("No command line arguments should be supplied") 15 | println("Goodbye!") // won't be executed 16 | } -------------------------------------------------------------------------------- /src/tasks/Floyds_triangle.kt: -------------------------------------------------------------------------------- 1 | package `floyds_triangle` 2 | 3 | fun main(args: Array) = args.forEach { Triangle(it.toInt()) } 4 | 5 | internal class Triangle(n: Int) { 6 | init { 7 | println("$n rows:") 8 | var printMe = 1 9 | var printed = 0 10 | var row = 1 11 | while (row <= n) { 12 | val cols = Math.ceil(Math.log10(n * (n - 1) / 2 + printed + 2.0)).toInt() 13 | print("%${cols}d ".format(printMe)) 14 | if (++printed == row) { println(); row++; printed = 0 } 15 | printMe++ 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /src/tasks/Formatted_numeric_output.kt: -------------------------------------------------------------------------------- 1 | package `formatted_numeric_output` 2 | 3 | // version 1.0.5-2 4 | 5 | fun main(args: Array) { 6 | val num = 7.125 7 | println("%09.3f".format(num)) 8 | } -------------------------------------------------------------------------------- /src/tasks/Function_composition.kt: -------------------------------------------------------------------------------- 1 | package `function_composition` 2 | 3 | // version 1.0.6 4 | 5 | fun f(x: Int): Int = x * x 6 | 7 | fun g(x: Int): Int = x + 2 8 | 9 | fun compose(f: (Int) -> Int, g: (Int) -> Int): (Int) -> Int = { f(g(it)) } 10 | 11 | fun main(args: Array) { 12 | val x = 10 13 | println(compose(::f, ::g)(x)) 14 | } -------------------------------------------------------------------------------- /src/tasks/Function_definition.kt: -------------------------------------------------------------------------------- 1 | package `function_definition` 2 | 3 | // One-liner 4 | fun multiply(a: Int, b: Int) = a * b 5 | 6 | // Proper function definition 7 | fun multiplyProper(a: Int, b: Int): Int { 8 | return a * b 9 | } -------------------------------------------------------------------------------- /src/tasks/Generalised_floating_point_addition.kt: -------------------------------------------------------------------------------- 1 | package `generalised_floating_point_addition` 2 | 3 | // version 1.2.10 4 | 5 | import java.math.BigDecimal 6 | 7 | fun BigDecimal.repeatedAdd(times: Int): BigDecimal { 8 | var sum = BigDecimal.ZERO 9 | for (i in 0 until times) sum += this 10 | return sum 11 | } 12 | 13 | fun main(args: Array) { 14 | var s = "12345679" 15 | val t = "123456790" 16 | var e = 63 17 | for (n in -7..21) { 18 | val bd = BigDecimal("${s}e$e") 19 | val oneE = BigDecimal("1e$e") 20 | val temp = bd.repeatedAdd(9) 21 | val result = temp.repeatedAdd(9) + oneE 22 | println("%2d : %e".format(n, result)) 23 | s = t + s 24 | e -= 9 25 | } 26 | } -------------------------------------------------------------------------------- /src/tasks/Generate_lower_case_ASCII_alphabet.kt: -------------------------------------------------------------------------------- 1 | package `generate_lower_case_ascii_alphabet` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | val alphabet = CharArray(26) { (it + 97).toChar() }.joinToString("") 7 | println(alphabet) 8 | } -------------------------------------------------------------------------------- /src/tasks/Generic_swap.kt: -------------------------------------------------------------------------------- 1 | package `generic_swap` 2 | 3 | // version 1.1 4 | 5 | fun swap(t1: T, t2: T) = Pair(t2, t1) 6 | 7 | fun main(args: Array) { 8 | var a = 3 9 | var b = 4 10 | val c = swap(a, b) // infers that swap be used 11 | a = c.first 12 | b = c.second 13 | println("a = $a") 14 | println("b = $b") 15 | var d = false 16 | var e = true 17 | val f = swap(d, e) // infers that swap be used 18 | d = f.first 19 | e = f.second 20 | println("d = $d") 21 | println("e = $e") 22 | } -------------------------------------------------------------------------------- /src/tasks/Get_system_command_output.kt: -------------------------------------------------------------------------------- 1 | package `get_system_command_output` 2 | 3 | // version 1.0.6 4 | 5 | import java.util.Scanner 6 | 7 | fun main(args: Array) { 8 | val command = "cmd /c chcp" 9 | val p = Runtime.getRuntime().exec(command) 10 | val sc = Scanner(p.inputStream) 11 | println(sc.nextLine()) 12 | sc.close() 13 | } -------------------------------------------------------------------------------- /src/tasks/Globally_replace_text_in_several_files.kt: -------------------------------------------------------------------------------- 1 | package `globally_replace_text_in_several_files` 2 | 3 | // version 1.2.0 4 | 5 | import java.io.File 6 | 7 | fun main(args: Array) { 8 | val files = arrayOf("file1.txt", "file2.txt") 9 | for (file in files) { 10 | val f = File(file) 11 | var text = f.readText() 12 | println(text) 13 | text = text.replace("Goodbye London!", "Hello New York!") 14 | f.writeText(text) 15 | println(f.readText()) 16 | } 17 | } -------------------------------------------------------------------------------- /src/tasks/Gray_code.kt: -------------------------------------------------------------------------------- 1 | package `gray_code` 2 | 3 | // version 1.0.6 4 | 5 | object Gray { 6 | fun encode(n: Int) = n xor (n shr 1) 7 | 8 | fun decode(n: Int): Int { 9 | var p = n 10 | var nn = n 11 | while (nn != 0) { 12 | nn = nn shr 1 13 | p = p xor nn 14 | } 15 | return p 16 | } 17 | } 18 | 19 | fun main(args: Array) { 20 | println("Number\tBinary\tGray\tDecoded") 21 | for (i in 0..31) { 22 | print("$i\t${Integer.toBinaryString(i)}\t") 23 | val g = Gray.encode(i) 24 | println("${Integer.toBinaryString(g)}\t${Gray.decode(g)}") 25 | } 26 | } -------------------------------------------------------------------------------- /src/tasks/Greatest_common_divisor.kt: -------------------------------------------------------------------------------- 1 | package `greatest_common_divisor` 2 | 3 | fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) -------------------------------------------------------------------------------- /src/tasks/Greatest_element_of_a_list.kt: -------------------------------------------------------------------------------- 1 | package `greatest_element_of_a_list` 2 | 3 | // version 1.0.5-2 4 | fun main(args: Array) { 5 | print("Number of values to be input = ") 6 | val n = readLine()!!.toInt() 7 | val array = DoubleArray(n) 8 | for (i in 0 until n) { 9 | print("Value ${i + 1} = ") 10 | array[i] = readLine()!!.toDouble() 11 | } 12 | println("\nThe greatest element is ${array.max()}") 13 | } -------------------------------------------------------------------------------- /src/tasks/Guess_the_number-With_feedback.kt: -------------------------------------------------------------------------------- 1 | package `guess_the_number_with_feedback` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args: Array) { 6 | val rand = java.util.Random() 7 | val n = 1 + rand.nextInt(20) 8 | var guess :Int 9 | println("Guess which number I've chosen in the range 1 to 20\n") 10 | while (true) { 11 | print(" Your guess : ") 12 | guess = readLine()!!.toInt() 13 | when (guess) { 14 | n -> { println("Correct, well guessed!") ; return } 15 | in n + 1 .. 20 -> println("Your guess is higher than the chosen number, try again") 16 | in 1 .. n - 1 -> println("Your guess is lower than the chosen number, try again") 17 | else -> println("Your guess is inappropriate, try again") 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /src/tasks/Guess_the_number.kt: -------------------------------------------------------------------------------- 1 | package `guess_the_number` 2 | 3 | // version 1.0.5-2 4 | 5 | fun main(args: Array) { 6 | val rand = java.util.Random() 7 | val n = 1 + rand.nextInt(10) 8 | var guess: Int 9 | println("Guess which number I've chosen in the range 1 to 10\n") 10 | while (true) { 11 | print(" Your guess : ") 12 | guess = readLine()!!.toInt() 13 | if (n == guess) { 14 | println("\nWell guessed!") 15 | return 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /src/tasks/HTTP.kt: -------------------------------------------------------------------------------- 1 | package `http` 2 | 3 | // version 1.1.2 4 | 5 | import java.net.URL 6 | import java.io.InputStreamReader 7 | import java.util.Scanner 8 | 9 | fun main(args: Array) { 10 | val url = URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt") 11 | val isr = InputStreamReader(url.openStream()) 12 | val sc = Scanner(isr) 13 | while (sc.hasNextLine()) println(sc.nextLine()) 14 | sc.close() 15 | } -------------------------------------------------------------------------------- /src/tasks/HTTPS.kt: -------------------------------------------------------------------------------- 1 | package `https` 2 | 3 | // version 1.1.2 4 | import java.net.URL 5 | import javax.net.ssl.HttpsURLConnection 6 | import java.io.InputStreamReader 7 | import java.util.Scanner 8 | 9 | fun main(args: Array) { 10 | val url = URL("https://en.wikipedia.org/wiki/Main_Page") 11 | val connection = url.openConnection() as HttpsURLConnection 12 | val isr = InputStreamReader(connection.inputStream) 13 | val sc = Scanner(isr) 14 | while (sc.hasNextLine()) println(sc.nextLine()) 15 | sc.close() 16 | } -------------------------------------------------------------------------------- /src/tasks/Handle_a_signal.kt: -------------------------------------------------------------------------------- 1 | package `handle_a_signal` 2 | 3 | // version 1.1.3 4 | 5 | import sun.misc.Signal 6 | import sun.misc.SignalHandler 7 | 8 | fun main(args: Array) { 9 | val startTime = System.currentTimeMillis() 10 | 11 | Signal.handle(Signal("INT"), object : SignalHandler { 12 | override fun handle(sig: Signal) { 13 | val elapsedTime = (System.currentTimeMillis() - startTime) / 1000.0 14 | println("\nThe program has run for $elapsedTime seconds") 15 | System.exit(0) 16 | } 17 | }) 18 | 19 | var i = 0 20 | while(true) { 21 | println(i++) 22 | Thread.sleep(500) 23 | } 24 | } -------------------------------------------------------------------------------- /src/tasks/Happy_numbers.kt: -------------------------------------------------------------------------------- 1 | package `happy_numbers` 2 | 3 | // version 1.0.5-2 4 | 5 | fun isHappy(n: Int): Boolean { 6 | val cache = mutableListOf() 7 | var sum = 0 8 | var nn = n 9 | var digit: Int 10 | while (nn != 1) { 11 | if (nn in cache) return false 12 | cache.add(nn) 13 | while (nn != 0) { 14 | digit = nn % 10 15 | sum += digit * digit 16 | nn /= 10 17 | } 18 | nn = sum 19 | sum = 0 20 | } 21 | return true 22 | } 23 | 24 | fun main(args: Array) { 25 | var num = 1 26 | val happyNums = mutableListOf() 27 | while (happyNums.size < 8) { 28 | if (isHappy(num)) happyNums.add(num) 29 | num++ 30 | } 31 | println("First 8 happy numbers : " + happyNums.joinToString(", ")) 32 | } -------------------------------------------------------------------------------- /src/tasks/Hash_from_two_arrays.kt: -------------------------------------------------------------------------------- 1 | package `hash_from_two_arrays` 2 | 3 | // version 1.1.0 4 | 5 | fun main(args: Array) { 6 | val names = arrayOf("Jimmy", "Bill", "Barack", "Donald") 7 | val ages = arrayOf(92, 70, 55, 70) 8 | val hash = mapOf(*names.zip(ages).toTypedArray()) 9 | hash.forEach { println("${it.key.padEnd(6)} aged ${it.value}") } 10 | } -------------------------------------------------------------------------------- /src/tasks/Haversine_formula.kt: -------------------------------------------------------------------------------- 1 | package haversine 2 | 3 | import java.lang.Math.* 4 | 5 | const val R = 6372.8 // in kilometers 6 | 7 | fun haversine(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double { 8 | val λ1 = toRadians(lat1) 9 | val λ2 = toRadians(lat2) 10 | val Δλ = toRadians(lat2 - lat1) 11 | val Δφ = toRadians(lon2 - lon1) 12 | return 2 * R * asin(sqrt(pow(sin(Δλ / 2), 2.0) + pow(sin(Δφ / 2), 2.0) * cos(λ1) * cos(λ2))) 13 | } 14 | 15 | fun main(args: Array) = println("result: " + haversine(36.12, -86.67, 33.94, -118.40)) -------------------------------------------------------------------------------- /src/tasks/Hello_world-Graphical.kt: -------------------------------------------------------------------------------- 1 | package `hello_world_graphical` 2 | 3 | import java.awt.* 4 | import javax.swing.* 5 | 6 | fun main(args: Array) { 7 | JOptionPane.showMessageDialog(null, "Goodbye, World!") // in alert box 8 | with(JFrame("Goodbye, World!")) { // on title bar 9 | layout = FlowLayout() 10 | add(JButton("Goodbye, World!")) // on button 11 | add(JTextArea("Goodbye, World!")) // in editable area 12 | pack() 13 | defaultCloseOperation = JFrame.EXIT_ON_CLOSE 14 | isVisible = true 15 | } 16 | } -------------------------------------------------------------------------------- /src/tasks/Hello_world-Line_printer.kt: -------------------------------------------------------------------------------- 1 | package `hello_world_line_printer` 2 | 3 | import java.io.File 4 | 5 | fun main(args: Array) { 6 | val text = "Hello World!\n" 7 | File("/dev/lp0").writeText(text) 8 | } -------------------------------------------------------------------------------- /src/tasks/Hello_world-Newbie.kt: -------------------------------------------------------------------------------- 1 | package `hello_world_newbie` 2 | 3 | fun main(args: Array) { 4 | println("Hello, World!") 5 | } -------------------------------------------------------------------------------- /src/tasks/Hello_world-Newline_omission.kt: -------------------------------------------------------------------------------- 1 | package `hello_world_newline_omission` 2 | 3 | fun main(args: Array) = print("Goodbye, World!") -------------------------------------------------------------------------------- /src/tasks/Hello_world-Standard_error.kt: -------------------------------------------------------------------------------- 1 | package `hello_world_standard_error` 2 | 3 | fun main(args: Array) { 4 | System.err.println("Goodbye, World!") 5 | } -------------------------------------------------------------------------------- /src/tasks/Hello_world-Text.kt: -------------------------------------------------------------------------------- 1 | package `hello_world_text` 2 | 3 | fun main(args: Array) { 4 | println("Hello world!") 5 | } -------------------------------------------------------------------------------- /src/tasks/Hello_world-Web_server.kt: -------------------------------------------------------------------------------- 1 | package `hello_world_web_server` 2 | 3 | import java.io.PrintWriter 4 | import java.net.ServerSocket 5 | 6 | fun main(args: Array) { 7 | val listener = ServerSocket(8080) 8 | while(true) { 9 | val sock = listener.accept() 10 | PrintWriter(sock.outputStream, true).println("Goodbye, World!") 11 | sock.close() 12 | } 13 | } -------------------------------------------------------------------------------- /src/tasks/Higher-order_functions-1.kt: -------------------------------------------------------------------------------- 1 | package `higher_order_functions_1` 2 | 3 | inline fun higherOrderFunction(x: Int, y: Int, function: (Int, Int) -> Int) = function(x, y) 4 | 5 | fun main(args: Array) { 6 | val result = higherOrderFunction(3, 5) { x, y -> x + y } 7 | println(result) 8 | } -------------------------------------------------------------------------------- /src/tasks/Higher-order_functions.kt: -------------------------------------------------------------------------------- 1 | package `higher_order_functions` 2 | 3 | fun main(args: Array) { 4 | val list = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0) 5 | val a = list.map({ x -> x + 2 }).average() 6 | val h = list.map({ x -> x * x }).average() 7 | val g = list.map({ x -> x * x * x }).average() 8 | println("A = %f G = %f H = %f".format(a, g, h)) 9 | } -------------------------------------------------------------------------------- /src/tasks/History_variables.kt: -------------------------------------------------------------------------------- 1 | package `history_variables` 2 | 3 | // version 1.1.4 4 | 5 | class HistoryVariable(initialValue: T) { 6 | private val history = mutableListOf() 7 | 8 | var currentValue: T 9 | get() = history[history.size - 1] 10 | set(value) { 11 | history.add(value) 12 | } 13 | 14 | init { 15 | currentValue = initialValue 16 | } 17 | 18 | fun showHistory() { 19 | println("The variable's history, oldest values first, is:") 20 | for (item in history) println(item) 21 | } 22 | } 23 | 24 | fun main(args: Array) { 25 | val v = HistoryVariable(1) 26 | v.currentValue = 2 27 | v.currentValue = 3 28 | v.showHistory() 29 | println("\nCurrentvalue is ${v.currentValue}") 30 | } -------------------------------------------------------------------------------- /src/tasks/Hofstadter_Q_sequence.kt: -------------------------------------------------------------------------------- 1 | package `hofstadter_q_sequence` 2 | 3 | // version 1.1.4 4 | 5 | fun main(args: Array) { 6 | val q = IntArray(100_001) 7 | q[1] = 1 8 | q[2] = 1 9 | for (n in 3..100_000) q[n] = q[n - q[n - 1]] + q[n - q[n - 2]] 10 | print("The first 10 terms are : ") 11 | for (i in 1..10) print("${q[i]} ") 12 | println("\n\nThe 1000th term is : ${q[1000]}") 13 | val flips = (2..100_000).count { q[it] < q[it - 1] } 14 | println("\nThe number of flips for the first 100,000 terms is : $flips") 15 | } -------------------------------------------------------------------------------- /src/tasks/Horners_rule_for_polynomial_evaluation.kt: -------------------------------------------------------------------------------- 1 | package `horners_rule_for_polynomial_evaluation` 2 | 3 | // version 1.1.2 4 | 5 | fun horner(coeffs: DoubleArray, x: Double): Double { 6 | var sum = 0.0 7 | for (i in coeffs.size - 1 downTo 0) sum = sum * x + coeffs[i] 8 | return sum 9 | } 10 | 11 | fun main(args: Array) { 12 | val coeffs = doubleArrayOf(-19.0, 7.0, -4.0, 6.0) 13 | println(horner(coeffs, 3.0)) 14 | } -------------------------------------------------------------------------------- /src/tasks/Host_introspection.kt: -------------------------------------------------------------------------------- 1 | package `host_introspection` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | println("Word size : ${System.getProperty("sun.arch.data.model")} bits") 7 | println("Endianness: ${System.getProperty("sun.cpu.endian")}-endian") 8 | } -------------------------------------------------------------------------------- /src/tasks/Hostname.kt: -------------------------------------------------------------------------------- 1 | package `hostname` 2 | 3 | // version 1.1.4 4 | 5 | import java.net.InetAddress 6 | 7 | fun main(args: Array) { 8 | println(InetAddress.getLocalHost().hostName) 9 | } -------------------------------------------------------------------------------- /src/tasks/Identity_matrix.kt: -------------------------------------------------------------------------------- 1 | package `identity_matrix` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | print("Enter size of matrix : ") 7 | val n = readLine()!!.toInt() 8 | println() 9 | val identity = Array(n) { IntArray(n) } // create n x n matrix of integers 10 | 11 | // enter 1s in diagonal elements 12 | for(i in 0 until n) identity[i][i] = 1 13 | 14 | // print identity matrix if n <= 40 15 | if (n <= 40) 16 | for (i in 0 until n) println(identity[i].joinToString(" ")) 17 | else 18 | println("Matrix is too big to display on 80 column console") 19 | } -------------------------------------------------------------------------------- /src/tasks/Idiomatically_determine_all_the_lowercase_and_uppercase_letters.kt: -------------------------------------------------------------------------------- 1 | package `idiomatically_determine_all_the_lowercase_and_uppercase_letters` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | print("Lower case : ") 7 | for (ch in 'a'..'z') print(ch) 8 | print("\nUpper case : ") 9 | for (ch in 'A'..'Z') print(ch) 10 | println() 11 | } -------------------------------------------------------------------------------- /src/tasks/Implicit_type_conversion.kt: -------------------------------------------------------------------------------- 1 | package `implicit_type_conversion` 2 | 3 | // version 1.1.2 4 | 5 | open class C(val x: Int) 6 | 7 | class D(x: Int) : C(x) 8 | 9 | fun main(args: Array) { 10 | val c: C = D(42) // OK because D is a sub-class of C 11 | println(c.x) 12 | val b: Byte = 100 // OK because 100 is within the range of the Byte type 13 | println(b) 14 | val s: Short = 32000 // OK because 32000 is within the range of the Short Type 15 | println(s) 16 | val l: Long = 1_000_000 // OK because any Int literal is within the range of the Long type 17 | println(l) 18 | val n : Int? = c.x // OK because Int is a sub-class of its nullable type Int? (c.x is boxed on heap) 19 | println(n) 20 | } -------------------------------------------------------------------------------- /src/tasks/Include_a_file-1.kt: -------------------------------------------------------------------------------- 1 | package `include_a_file_1` 2 | 3 | // version 1.1.2 4 | 5 | import package1.f // import f from package `package1` 6 | 7 | fun main(args: Array) { 8 | f() // invoke f without qualification 9 | } -------------------------------------------------------------------------------- /src/tasks/Include_a_file.kt: -------------------------------------------------------------------------------- 1 | package package1 2 | 3 | fun f() = println("f called") -------------------------------------------------------------------------------- /src/tasks/Increment_a_numerical_string.kt: -------------------------------------------------------------------------------- 1 | package `increment_a_numerical_string` 2 | 3 | // version 1.0.5-2 4 | 5 | /** overload ++ operator to increment a numeric string */ 6 | operator fun String.inc(): String = 7 | try { 8 | val num = this.toInt() 9 | (num + 1).toString() 10 | } 11 | catch(e: NumberFormatException) { 12 | this // return string unaltered 13 | } 14 | 15 | fun main(args: Array) { 16 | var ns = "12345" 17 | println(++ns) 18 | ns = "ghijk" // not numeric, so won't be changed by increment operator 19 | println(++ns) 20 | } -------------------------------------------------------------------------------- /src/tasks/Infinity.kt: -------------------------------------------------------------------------------- 1 | package `infinity` 2 | 3 | fun main(args: Array) { 4 | val p = Double.POSITIVE_INFINITY // +∞ 5 | println(p.isInfinite()) // true 6 | println(p.isFinite()) // false 7 | println("${p < 0} ${p > 0}") // false true 8 | 9 | val n = Double.NEGATIVE_INFINITY // -∞ 10 | println(n.isInfinite()) // true 11 | println(n.isFinite()) // false 12 | println("${n < 0} ${n > 0}") // true false 13 | } -------------------------------------------------------------------------------- /src/tasks/Inheritance-Single.kt: -------------------------------------------------------------------------------- 1 | package `inheritance_single` 2 | 3 | // version 1.0.6 4 | 5 | open class Animal { 6 | override fun toString() = "animal" 7 | } 8 | 9 | open class Dog : Animal() { 10 | override fun toString() = "dog" 11 | } 12 | 13 | class Cat : Animal() { 14 | override fun toString() = "cat" 15 | } 16 | 17 | class Labrador : Dog() { 18 | override fun toString() = "labrador" 19 | } 20 | 21 | class Collie : Dog() { 22 | override fun toString() = "collie" 23 | } 24 | 25 | fun main(args: Array) { 26 | val felix: Animal = Cat() 27 | val rover: Animal = Dog() 28 | val bella: Dog = Labrador() 29 | val casey: Dog = Collie() 30 | println("Felix is a $felix") 31 | println("Rover is a $rover") 32 | println("Bella is a $bella") 33 | println("Casey is a $casey") 34 | } -------------------------------------------------------------------------------- /src/tasks/Input-Output_for_Lines_of_Text.kt: -------------------------------------------------------------------------------- 1 | package `input_output_for_lines_of_text` 2 | 3 | // version 1.1 4 | 5 | fun output(lines: Array) = println(lines.joinToString("\n")) 6 | 7 | fun main(args: Array) { 8 | println("Enter the number of lines to be input followed by those lines:\n") 9 | val n = readLine()!!.toInt() 10 | val lines = Array(n) { readLine()!! } 11 | println("\nThe lines you entered are:\n") 12 | output(lines) 13 | } -------------------------------------------------------------------------------- /src/tasks/Input-Output_for_Pairs_of_Numbers.kt: -------------------------------------------------------------------------------- 1 | package `input_output_for_pairs_of_numbers` 2 | 3 | // version 1.0.6 4 | 5 | import java.util.Scanner 6 | 7 | fun main(args: Array) { 8 | val sc = Scanner(System.`in`) // note: backticks required as 'in' is a Kotlin keyword 9 | val n = sc.nextInt() 10 | val x = IntArray(n) 11 | val y = IntArray(n) 12 | for (i in 0 until n) { 13 | x[i] = sc.nextInt() 14 | y[i] = sc.nextInt() 15 | } 16 | println() 17 | for (i in 0 until n) println(x[i] + y[i]) 18 | } -------------------------------------------------------------------------------- /src/tasks/Input_loop.kt: -------------------------------------------------------------------------------- 1 | package `input_loop` 2 | 3 | // version 1.1 4 | 5 | import java.util.* 6 | 7 | fun main(args: Array) { 8 | println("Keep entering text or the word 'quit' to end the program:") 9 | val sc = Scanner(System.`in`) 10 | val words = mutableListOf() 11 | while (true) { 12 | val input: String = sc.next() 13 | if (input.trim().toLowerCase() == "quit") { 14 | if (words.size > 0) println("\nYou entered the following words:\n${words.joinToString("\n")}") 15 | return 16 | } 17 | words.add(input) 18 | } 19 | } -------------------------------------------------------------------------------- /src/tasks/Integer_comparison.kt: -------------------------------------------------------------------------------- 1 | package `integer_comparison` 2 | 3 | fun main(args: Array) { 4 | val n1 = readLine()!!.toLong() 5 | val n2 = readLine()!!.toLong() 6 | println(when { 7 | n1 < n2 -> "$n1 is less than $n2" 8 | n1 > n2 -> "$n1 is greater than $n2" 9 | n1 == n2 -> "$n1 is equal to $n2" 10 | else -> "" 11 | }) 12 | } -------------------------------------------------------------------------------- /src/tasks/Integer_sequence.kt: -------------------------------------------------------------------------------- 1 | package `integer_sequence` 2 | 3 | import java.math.BigInteger 4 | 5 | // version 1.0.5-2 6 | 7 | fun main(args: Array) { 8 | // print until 2147483647 9 | (0..Int.MAX_VALUE).forEach { println(it) } 10 | 11 | // print forever 12 | var n = BigInteger.ZERO 13 | while (true) { 14 | println(n) 15 | n += BigInteger.ONE 16 | } 17 | } -------------------------------------------------------------------------------- /src/tasks/Inverted_syntax.kt: -------------------------------------------------------------------------------- 1 | package `inverted_syntax` 2 | 3 | // version 1.0.6 4 | 5 | infix fun Boolean.iif(cond: Boolean) = if (cond) this else !this 6 | 7 | fun main(args: Array) { 8 | val raining = true 9 | val needUmbrella = true iif (raining) 10 | println("Do I need an umbrella? ${if(needUmbrella) "Yes" else "No"}") 11 | } -------------------------------------------------------------------------------- /src/tasks/Jensens_Device.kt: -------------------------------------------------------------------------------- 1 | package `jensens_device` 2 | 3 | fun sum(lo: Int, hi: Int, f: (Int) -> Double) = (lo..hi).sumByDouble(f) 4 | 5 | fun main(args: Array) = println(sum(1, 100, { 1.0 / it })) -------------------------------------------------------------------------------- /src/tasks/Jewels_and_Stones.kt: -------------------------------------------------------------------------------- 1 | package `jewels_and_stones` 2 | 3 | // Version 1.2.40 4 | 5 | fun countJewels(s: String, j: String) = s.count { it in j } 6 | 7 | fun main(args: Array) { 8 | println(countJewels("aAAbbbb", "aA")) 9 | println(countJewels("ZZ", "z")) 10 | } -------------------------------------------------------------------------------- /src/tasks/JortSort.kt: -------------------------------------------------------------------------------- 1 | package `jortsort` 2 | 3 | // version 1.0.6 4 | 5 | fun jortSort(a: Array): Boolean { 6 | val b = a.copyOf() 7 | b.sort() 8 | for (i in 0 until a.size) 9 | if (a[i] != b[i]) return false 10 | return true 11 | } 12 | 13 | fun printResults(a: Array) { 14 | println(a.joinToString(" ") + " => " + if (jortSort(a)) "sorted" else "not sorted") 15 | } 16 | 17 | fun main(args: Array) { 18 | val a = arrayOf(1, 2, 3, 4, 5) 19 | printResults(a) 20 | val b = arrayOf(2, 1, 3, 4, 5) 21 | printResults(b) 22 | println() 23 | val c = arrayOf('A', 'B', 'C', 'D', 'E') 24 | printResults(c) 25 | val d = arrayOf('C', 'D', 'A', 'E', 'B') 26 | printResults(d) 27 | } -------------------------------------------------------------------------------- /src/tasks/Jump_anywhere.kt: -------------------------------------------------------------------------------- 1 | package `jump_anywhere` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | intArrayOf(4, 5, 6).forEach lambda@ { 7 | if (it == 5) return@lambda 8 | println(it) 9 | } 10 | println() 11 | loop@ for (i in 0 .. 3) { 12 | for (j in 0 .. 3) { 13 | if (i + j == 4) continue@loop 14 | if (i + j == 5) break@loop 15 | println(i + j) 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /src/tasks/Kahan_summation.kt: -------------------------------------------------------------------------------- 1 | package `kahan_summation` 2 | 3 | // version 1.1.2 4 | 5 | fun kahanSum(vararg fa: Float): Float { 6 | var sum = 0.0f 7 | var c = 0.0f 8 | for (f in fa) { 9 | val y = f - c 10 | val t = sum + y 11 | c = (t - sum) - y 12 | sum = t 13 | } 14 | return sum 15 | } 16 | 17 | fun epsilon(): Float { 18 | var eps = 1.0f 19 | while (1.0f + eps != 1.0f) eps /= 2.0f 20 | return eps 21 | } 22 | 23 | fun main(args: Array) { 24 | val a = 1.0f 25 | val b = epsilon() 26 | val c = -b 27 | println("Epsilon = $b") 28 | println("(a + b) + c = ${(a + b) + c}") 29 | println("Kahan sum = ${kahanSum(a, b, c)}") 30 | } -------------------------------------------------------------------------------- /src/tasks/Kernighans_large_earthquake_problem.kt: -------------------------------------------------------------------------------- 1 | package `kernighans_large_earthquake_problem` 2 | 3 | // Version 1.2.40 4 | 5 | import java.io.File 6 | 7 | fun main(args: Array) { 8 | val r = Regex("""\s+""") 9 | println("Those earthquakes with a magnitude > 6.0 are:\n") 10 | File("data.txt").forEachLine { 11 | if (it.split(r)[2].toDouble() > 6.0) println(it) 12 | } 13 | } -------------------------------------------------------------------------------- /src/tasks/Keyboard_input-Flush_the_keyboard_buffer.kt: -------------------------------------------------------------------------------- 1 | package `keyboard_input_flush_the_keyboard_buffer` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | while (System.`in`.available() > 0) System.`in`.read() 7 | println("Goodbye!") 8 | } -------------------------------------------------------------------------------- /src/tasks/Knuths_algorithm_S-1.kt: -------------------------------------------------------------------------------- 1 | package `knuths_algorithm_s_1` 2 | 3 | // version 1.2.51 4 | 5 | import java.util.Random 6 | 7 | val rand = Random() 8 | 9 | fun SOfNCreator(n: Int): (T) -> List { 10 | val sample = ArrayList(n) 11 | var i = 0 12 | return { 13 | if (++i <= n) 14 | sample.add(it) 15 | else if (rand.nextInt(i) < n) 16 | sample[rand.nextInt(n)] = it 17 | sample 18 | } 19 | } 20 | 21 | fun main(args: Array) { 22 | val bin = IntArray(10) 23 | (1..100_000).forEach { 24 | val sOfn = SOfNCreator(3) 25 | for (d in 0..8) sOfn(d) 26 | for (s in sOfn(9)) bin[s]++ 27 | } 28 | println(bin.contentToString()) 29 | } -------------------------------------------------------------------------------- /src/tasks/Largest_int_from_concatenated_ints.kt: -------------------------------------------------------------------------------- 1 | package `largest_int_from_concatenated_ints` 2 | 3 | import java.util.Comparator 4 | 5 | fun main(args: Array) { 6 | val comparator = Comparator { x, y -> 7 | val xy = (x.toString() + y).toInt() 8 | val yx = (y.toString() + x).toInt() 9 | xy.compareTo(yx) 10 | } 11 | 12 | fun findLargestSequence(array: IntArray): String { 13 | return array.sortedWith(comparator).reversed().map { it.toString() }.joinToString("") 14 | } 15 | 16 | val source1 = intArrayOf(1, 34, 3, 98, 9, 76, 45, 4) 17 | println(findLargestSequence(source1)) 18 | 19 | val source2 = intArrayOf(54, 546, 548, 60) 20 | println(findLargestSequence(source2)) 21 | } -------------------------------------------------------------------------------- /src/tasks/Largest_number_divisible_by_its_digits.kt: -------------------------------------------------------------------------------- 1 | package `largest_number_divisible_by_its_digits` 2 | 3 | // version 1.1.4-3 4 | 5 | fun Int.divByAll(digits: List) = digits.all { this % (it - '0') == 0 } 6 | 7 | fun main(args: Array) { 8 | val magic = 9 * 8 * 7 9 | val high = 9876432 / magic * magic 10 | for (i in high downTo magic step magic) { 11 | if (i % 10 == 0) continue // can't end in '0' 12 | val s = i.toString() 13 | if ('0' in s || '5' in s) continue // can't contain '0' or '5' 14 | val sd = s.toCharArray().distinct() 15 | if (sd.size != s.length) continue // digits must be unique 16 | if (i.divByAll(sd)) { 17 | println("Largest decimal number is $i") 18 | return 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /src/tasks/Leap_year.kt: -------------------------------------------------------------------------------- 1 | package `leap_year` 2 | 3 | fun isLeapYear(year: Int) = year % 400 == 0 || (year % 100 != 0 && year % 4 == 0) -------------------------------------------------------------------------------- /src/tasks/Least_common_multiple.kt: -------------------------------------------------------------------------------- 1 | package `least_common_multiple` 2 | 3 | fun main(args: Array) { 4 | fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) 5 | fun lcm(a: Int, b: Int) = a * b / gcd(a, b) 6 | println(lcm(15, 9)) 7 | } -------------------------------------------------------------------------------- /src/tasks/Left_factorials.kt: -------------------------------------------------------------------------------- 1 | package `left_factorials` 2 | 3 | // version 1.0.6 4 | 5 | import java.math.BigInteger 6 | 7 | fun leftFactorial(n: Int): BigInteger { 8 | if (n == 0) return BigInteger.ZERO 9 | var fact = BigInteger.ONE 10 | var sum = fact 11 | for (i in 1 until n) { 12 | fact *= BigInteger.valueOf(i.toLong()) 13 | sum += fact 14 | } 15 | return sum 16 | } 17 | 18 | fun main(args: Array) { 19 | for (i in 0..110) 20 | if (i <= 10 || (i % 10) == 0) 21 | println("!${i.toString().padEnd(3)} = ${leftFactorial(i)}") 22 | println("\nLength of the following left factorials:") 23 | for (i in 1000..10000 step 1000) 24 | println("!${i.toString().padEnd(5)} has ${leftFactorial(i).toString().length} digits") 25 | } -------------------------------------------------------------------------------- /src/tasks/Leonardo_numbers.kt: -------------------------------------------------------------------------------- 1 | package `leonardo_numbers` 2 | 3 | // version 1.1.2 4 | 5 | fun leonardo(n: Int, l0: Int = 1, l1: Int = 1, add: Int = 1): IntArray { 6 | val leo = IntArray(n) 7 | leo[0] = l0 8 | leo[1] = l1 9 | for (i in 2 until n) leo[i] = leo[i - 1] + leo[i - 2] + add 10 | return leo 11 | } 12 | 13 | fun main(args: Array) { 14 | println("The first 25 Leonardo numbers with L[0] = 1, L[1] = 1 and add number = 1 are:") 15 | println(leonardo(25).joinToString(" ")) 16 | println("\nThe first 25 Leonardo numbers with L[0] = 0, L[1] = 1 and add number = 0 are:") 17 | println(leonardo(25, 0, 1, 0).joinToString(" ")) 18 | } -------------------------------------------------------------------------------- /src/tasks/Letter_frequency.kt: -------------------------------------------------------------------------------- 1 | package `letter_frequency` 2 | 3 | // version 1.1.2 4 | 5 | import java.io.File 6 | 7 | fun main(args: Array) { 8 | val text = File("input.txt").readText().toLowerCase() 9 | val letterMap = text.filter { it in 'a'..'z' }.groupBy { it }.toSortedMap() 10 | for (letter in letterMap) println("${letter.key} = ${letter.value.size}") 11 | val sum = letterMap.values.sumBy { it.size } 12 | println("\nTotal letters = $sum") 13 | } -------------------------------------------------------------------------------- /src/tasks/Levenshtein_distance-1.kt: -------------------------------------------------------------------------------- 1 | package `levenshtein_distance_1` 2 | 3 | fun levenshtein(s: String, t: String, 4 | charScore : (Char, Char) -> Int = { c1, c2 -> if (c1 == c2) 0 else 1}) : Int { 5 | 6 | // Special cases 7 | if (s == t) return 0 8 | if (s == "") return t.length 9 | if (t == "") return s.length 10 | 11 | val initialRow : List = (0 until t.length + 1).map { it }.toList() 12 | return (0 until s.length).fold(initialRow, { previous, u -> 13 | (0 until t.length).fold( mutableListOf(u+1), { 14 | row, v -> row.add(listOf(row.last() + 1, 15 | previous[v+1] + 1, 16 | previous[v] + charScore(s[u],t[v])).min()!!) 17 | row 18 | }) 19 | }).last() 20 | 21 | } -------------------------------------------------------------------------------- /src/tasks/Linear_congruential_generator.kt: -------------------------------------------------------------------------------- 1 | package `linear_congruential_generator` 2 | 3 | // version 1.1.3 4 | 5 | class Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) { 6 | private var state = s 7 | 8 | fun nextInt(): Long { 9 | state = (a * state + c) % m 10 | return state / d 11 | } 12 | } 13 | 14 | fun main(args: Array) { 15 | println("First 10 BSD random numbers - seed 0") 16 | val bsd = Lcg(1103515245, 12345, 1 shl 31, 1, 0) 17 | for (i in 1..10) println("${bsd.nextInt()}") 18 | println("\nFirst 10 MSC random numbers - seed 0") 19 | val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, 0) 20 | for (i in 1..10) println("${msc.nextInt()}") 21 | } -------------------------------------------------------------------------------- /src/tasks/List_comprehensions.kt: -------------------------------------------------------------------------------- 1 | package `list_comprehensions` 2 | 3 | // version 1.0.6 4 | 5 | fun pythagoreanTriples(n: Int) = 6 | (1..n).flatMap { 7 | x -> (x..n).flatMap { 8 | y -> (y..n).filter { 9 | z -> x * x + y * y == z * z 10 | }.map { Triple(x, y, it) } 11 | } 12 | } 13 | 14 | fun main(args: Array) { 15 | println(pythagoreanTriples(20)) 16 | } -------------------------------------------------------------------------------- /src/tasks/Literals-Floating_point.kt: -------------------------------------------------------------------------------- 1 | package `literals_floating_point` 2 | 3 | val d: Double = 1.0 4 | val d2: Double = 1.234e-10 5 | val f: Float = 728832f 6 | val f2: Float = 728832F -------------------------------------------------------------------------------- /src/tasks/Logical_operations.kt: -------------------------------------------------------------------------------- 1 | package `logical_operations` 2 | 3 | // version 1.0.6 4 | 5 | fun logicalDemo(b1: Boolean, b2: Boolean) { 6 | println("b1 = $b1") 7 | println("b2 = $b2") 8 | println("b1 and b2 = ${b1 and b2}") 9 | println("b1 or b2 = ${b1 or b2}") 10 | println("b1 xor b2 = ${b1 xor b2}") 11 | println("not b1 = ${!b1}") 12 | println("b1 && b2 = ${b1 && b2}") 13 | println("b1 || b2 = ${b1 || b2}") 14 | println() 15 | } 16 | 17 | fun main(args: Array) { 18 | logicalDemo(true, true) 19 | logicalDemo(true, false) 20 | logicalDemo(false, false) 21 | logicalDemo(false, true) 22 | } -------------------------------------------------------------------------------- /src/tasks/Longest_Common_Substring.kt: -------------------------------------------------------------------------------- 1 | package `longest_common_substring` 2 | 3 | // version 1.1.2 4 | 5 | fun lcs(a: String, b: String): String { 6 | if (a.length > b.length) return lcs(b, a) 7 | var res = "" 8 | for (ai in 0 until a.length) { 9 | for (len in a.length - ai downTo 1) { 10 | for (bi in 0 until b.length - len) { 11 | if (a.regionMatches(ai, b, bi,len) && len > res.length) { 12 | res = a.substring(ai, ai + len) 13 | } 14 | } 15 | } 16 | } 17 | return res 18 | } 19 | 20 | fun main(args: Array) = println(lcs("testing123testing", "thisisatest")) -------------------------------------------------------------------------------- /src/tasks/Longest_common_subsequence.kt: -------------------------------------------------------------------------------- 1 | package `longest_common_subsequence` 2 | 3 | // version 1.1.2 4 | 5 | fun lcs(x: String, y: String): String { 6 | if (x.length == 0 || y.length == 0) return "" 7 | val x1 = x.dropLast(1) 8 | val y1 = y.dropLast(1) 9 | if (x.last() == y.last()) return lcs(x1, y1) + x.last() 10 | val x2 = lcs(x, y1) 11 | val y2 = lcs(x1, y) 12 | return if (x2.length > y2.length) x2 else y2 13 | } 14 | 15 | fun main(args: Array) { 16 | val x = "thisisatest" 17 | val y = "testing123testing" 18 | println(lcs(x, y)) 19 | } -------------------------------------------------------------------------------- /src/tasks/Look-and-say_sequence.kt: -------------------------------------------------------------------------------- 1 | package `look_and_say_sequence` 2 | 3 | // version 1.0.6 4 | 5 | fun lookAndSay(s: String): String { 6 | val sb = StringBuilder() 7 | var digit = s[0] 8 | var count = 1 9 | for (i in 1 until s.length) { 10 | if (s[i] == digit) 11 | count++ 12 | else { 13 | sb.append("$count$digit") 14 | digit = s[i] 15 | count = 1 16 | } 17 | } 18 | return sb.append("$count$digit").toString() 19 | } 20 | 21 | fun main(args: Array) { 22 | var las = "1" 23 | for (i in 1..15) { 24 | println(las) 25 | las = lookAndSay(las) 26 | } 27 | } -------------------------------------------------------------------------------- /src/tasks/Loop_over_multiple_arrays_simultaneously.kt: -------------------------------------------------------------------------------- 1 | package `loop_over_multiple_arrays_simultaneously` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | val a1 = charArrayOf('a', 'b', 'c') 7 | val a2 = charArrayOf('A', 'B', 'C') 8 | val a3 = intArrayOf(1, 2, 3) 9 | for(i in 0 .. 2) println("${a1[i]}${a2[i]}${a3[i]}") 10 | println() 11 | // For arrays of different sizes we would need to iterate up to the mimimm size of all 3 in order 12 | // to get a contribution from each one. 13 | val a4 = intArrayOf(4, 5, 6, 7) 14 | val a5 = charArrayOf('d', 'e') 15 | val minSize = Math.min(a2.size, Math.min(a4.size, a5.size)) // minimum size of a2, a4 and a5 16 | for(i in 0 until minSize) println("${a2[i]}${a4[i]}${a5[i]}") 17 | } -------------------------------------------------------------------------------- /src/tasks/Loops-Break.kt: -------------------------------------------------------------------------------- 1 | package `loops_break` 2 | 3 | import java.util.Random 4 | 5 | fun main(args: Array) { 6 | val rand = Random() 7 | while (true) { 8 | val a = rand.nextInt(20) 9 | println(a) 10 | if (a == 10) break 11 | println(rand.nextInt(20)) 12 | } 13 | } -------------------------------------------------------------------------------- /src/tasks/Loops-Continue.kt: -------------------------------------------------------------------------------- 1 | package `loops_continue` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args: Array) { 6 | for(i in 1 .. 10) { 7 | if (i % 5 == 0) { 8 | println(i) 9 | continue 10 | } 11 | print("$i, ") 12 | } 13 | } -------------------------------------------------------------------------------- /src/tasks/Loops-Do-while.kt: -------------------------------------------------------------------------------- 1 | package `loops_do_while` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | var value = 0 7 | do { 8 | println(++value) 9 | } 10 | while (value % 6 != 0) 11 | } -------------------------------------------------------------------------------- /src/tasks/Loops-Downward_for.kt: -------------------------------------------------------------------------------- 1 | package `loops_downward_for` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | for (i in 10 downTo 0) print("$i ") 7 | } -------------------------------------------------------------------------------- /src/tasks/Loops-For.kt: -------------------------------------------------------------------------------- 1 | package `loops_for` 2 | 3 | fun main(args: Array) { 4 | (1..5).forEach { 5 | (1..it).forEach { print('*') } 6 | println() 7 | } 8 | } -------------------------------------------------------------------------------- /src/tasks/Loops-For_with_a_specified_step.kt: -------------------------------------------------------------------------------- 1 | package `loops_for_with_a_specified_step` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | for (i in 1 .. 21 step 2) print("$i ") 7 | } -------------------------------------------------------------------------------- /src/tasks/Loops-Foreach.kt: -------------------------------------------------------------------------------- 1 | package `loops_foreach` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | val greek = arrayOf("alpha", "beta", "gamma", "delta") 7 | for (letter in greek) print("$letter ") 8 | println() 9 | // or alternatively 10 | greek.forEach { print("$it ") } 11 | println() 12 | } -------------------------------------------------------------------------------- /src/tasks/Loops-Increment_loop_index_within_loop_body.kt: -------------------------------------------------------------------------------- 1 | package `loops_increment_loop_index_within_loop_body` 2 | 3 | // version 1.2.21 4 | 5 | fun isPrime(n: Long): Boolean { 6 | if (n % 2L == 0L) return n == 2L 7 | if (n % 3L == 0L) return n == 3L 8 | var d = 5L 9 | while (d * d <= n) { 10 | if (n % d == 0L) return false 11 | d += 2L 12 | if (n % d == 0L) return false 13 | d += 4L 14 | } 15 | return true 16 | } 17 | 18 | fun main(args: Array) { 19 | var i = 42L 20 | var n = 0 21 | do { 22 | if (isPrime(i)) { 23 | n++ 24 | System.out.printf("n = %-2d %,19d\n", n, i) 25 | i += i - 1 26 | } 27 | i++ 28 | } 29 | while (n < 42) 30 | } -------------------------------------------------------------------------------- /src/tasks/Loops-Infinite.kt: -------------------------------------------------------------------------------- 1 | package `loops_infinite` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | while (true) println("SPAM") 7 | } -------------------------------------------------------------------------------- /src/tasks/Loops-N_plus_one_half.kt: -------------------------------------------------------------------------------- 1 | package `loops_n_plus_one_half` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | for (i in 1 .. 10) { 7 | print(i) 8 | if (i < 10) print(", ") 9 | } 10 | } -------------------------------------------------------------------------------- /src/tasks/Loops-Nested.kt: -------------------------------------------------------------------------------- 1 | package `loops_nested` 2 | 3 | import java.util.Random 4 | 5 | fun main(args: Array) { 6 | val r = Random() 7 | val a = Array(10) { IntArray(10) { r.nextInt(20) + 1 } } 8 | println("array:") 9 | for (i in a.indices) println("row $i: " + a[i].asList()) 10 | 11 | println("search:") 12 | Outer@ for (i in a.indices) { 13 | print("row $i: ") 14 | for (j in a[i].indices) { 15 | print(" " + a[i][j]) 16 | if (a[i][j] == 20) break@Outer 17 | } 18 | println() 19 | } 20 | println() 21 | } -------------------------------------------------------------------------------- /src/tasks/Loops-While.kt: -------------------------------------------------------------------------------- 1 | package `loops_while` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | var value = 1024 7 | while (value > 0) { 8 | println(value) 9 | value /= 2 10 | } 11 | } -------------------------------------------------------------------------------- /src/tasks/Luhn_test_of_credit_card_numbers.kt: -------------------------------------------------------------------------------- 1 | package `luhn_test_of_credit_card_numbers` 2 | 3 | // version 1.1 4 | 5 | fun luhn(s: String): Boolean { 6 | fun sumDigits(n : Int) = n / 10 + n % 10 7 | val t = s.reversed() 8 | val s1 = t.filterIndexed { i, _ -> i % 2 == 0 }.sumBy { it - '0' } 9 | val s2 = t.filterIndexed { i, _ -> i % 2 == 1 }.map { sumDigits((it - '0') * 2) }.sum() 10 | return (s1 + s2) % 10 == 0 11 | } 12 | 13 | fun main(args: Array) { 14 | val numbers = arrayOf("49927398716", "49927398717", "1234567812345678", "1234567812345670") 15 | for (number in numbers) println("${number.padEnd(16)} is ${if(luhn(number)) "valid" else "invalid"}") 16 | } -------------------------------------------------------------------------------- /src/tasks/MAC_Vendor_Lookup.kt: -------------------------------------------------------------------------------- 1 | package `mac_vendor_lookup` 2 | 3 | // version 1.1.2 4 | 5 | import java.net.URL 6 | 7 | fun lookupVendor(mac: String) = URL("http://api.macvendors.com/" + mac).readText() 8 | 9 | fun main(args: Array) { 10 | val macs = arrayOf("FC-A1-3E", "FC:FB:FB:01:FA:21", "88:53:2E:67:07:BE", "D4:F4:6F:C9:EF:8D") 11 | for (mac in macs) println(lookupVendor(mac)) 12 | } -------------------------------------------------------------------------------- /src/tasks/MD5.kt: -------------------------------------------------------------------------------- 1 | package `md5` 2 | 3 | // version 1.0.6 4 | 5 | import java.security.MessageDigest 6 | 7 | fun main(args: Array) { 8 | val text = "The quick brown fox jumped over the lazy dog's back" 9 | val bytes = text.toByteArray() 10 | val md = MessageDigest.getInstance("MD5") 11 | val digest = md.digest(bytes) 12 | for (byte in digest) print("%02x".format(byte)) 13 | println() 14 | } -------------------------------------------------------------------------------- /src/tasks/Magic_squares_of_odd_order.kt: -------------------------------------------------------------------------------- 1 | package `magic_squares_of_odd_order` 2 | 3 | // version 1.0.6 4 | 5 | fun f(n: Int, x: Int, y: Int) = (x + y * 2 + 1) % n 6 | 7 | fun main(args: Array) { 8 | var n: Int 9 | while (true) { 10 | print("Enter the order of the magic square : ") 11 | n = readLine()!!.toInt() 12 | if (n < 1 || n % 2 == 0) println("Must be odd and >= 1, try again") 13 | else break 14 | } 15 | println() 16 | for (i in 0 until n) { 17 | for (j in 0 until n) print("%4d".format(f(n, n - j - 1, i) * n + f(n, j, i) + 1)) 18 | println() 19 | } 20 | println("\nThe magic constant is ${(n * n + 1) / 2 * n}") 21 | } -------------------------------------------------------------------------------- /src/tasks/Make_a_backup_file.kt: -------------------------------------------------------------------------------- 1 | package `make_a_backup_file` 2 | 3 | // version 1.1.51 4 | 5 | import java.io.File 6 | 7 | fun saveWithBackup(fileName: String, vararg data: String) { 8 | val orig = File(fileName) 9 | // canonicalPath follows symlinks to their ends 10 | val backup = File(orig.canonicalPath + ".backup") 11 | orig.renameTo(backup) 12 | val pw = orig.printWriter() 13 | for (i in data.indices) { 14 | pw.print(data[i]) 15 | if (i < data.lastIndex) pw.println() 16 | } 17 | pw.close() 18 | } 19 | 20 | fun main(args: Array) { 21 | saveWithBackup("original.txt", "fourth", "fifth", "sixth") 22 | } -------------------------------------------------------------------------------- /src/tasks/Make_directory_path.kt: -------------------------------------------------------------------------------- 1 | package `make_directory_path` 2 | 3 | // version 1.0.6 4 | 5 | import java.io.File 6 | 7 | fun main(args: Array) { 8 | // using built-in mkdirs() method 9 | val success = File("./path/to/dir").mkdirs() 10 | if (success) println("Directory path was created successfully") 11 | else println("Failed to create directory path") 12 | } -------------------------------------------------------------------------------- /src/tasks/Man_or_boy_test.kt: -------------------------------------------------------------------------------- 1 | package `man_or_boy_test` 2 | 3 | // version 1.1.3 4 | 5 | typealias Func = () -> Int 6 | 7 | fun a(k: Int, x1: Func, x2: Func, x3: Func, x4: Func, x5: Func): Int { 8 | var kk = k 9 | fun b(): Int = a(--kk, ::b, x1, x2, x3, x4) 10 | return if (kk <= 0) x4() + x5() else b() 11 | } 12 | 13 | fun main(args: Array) { 14 | println(" k a") 15 | for (k in 0..12) { 16 | println("${"%2d".format(k)}: ${a(k, { 1 }, { -1 }, { -1 }, { 1 }, { 0 })}") 17 | } 18 | } -------------------------------------------------------------------------------- /src/tasks/McNuggets_Problem.kt: -------------------------------------------------------------------------------- 1 | package `mcnuggets_problem` 2 | 3 | // Version 1.2.71 4 | 5 | fun mcnugget(limit: Int) { 6 | val sv = BooleanArray(limit + 1) // all false by default 7 | for (s in 0..limit step 6) 8 | for (n in s..limit step 9) 9 | for (t in n..limit step 20) sv[t] = true 10 | 11 | for (i in limit downTo 0) { 12 | if (!sv[i]) { 13 | println("Maximum non-McNuggets number is $i") 14 | return 15 | } 16 | } 17 | } 18 | 19 | fun main(args: Array) { 20 | mcnugget(100) 21 | } -------------------------------------------------------------------------------- /src/tasks/Menu.kt: -------------------------------------------------------------------------------- 1 | package `menu` 2 | 3 | // version 1.1.2 4 | 5 | fun menu(list: List): String { 6 | if (list.isEmpty()) return "" 7 | val n = list.size 8 | while (true) { 9 | println("\n M E N U\n") 10 | for (i in 0 until n) println("${i + 1}: ${list[i]}") 11 | print("\nEnter your choice 1 - $n : ") 12 | val index = readLine()!!.toIntOrNull() 13 | if (index == null || index !in 1..n) continue 14 | return list[index - 1] 15 | } 16 | } 17 | 18 | fun main(args: Array) { 19 | val list = listOf( 20 | "fee fie", 21 | "huff and puff", 22 | "mirror mirror", 23 | "tick tock" 24 | ) 25 | val choice = menu(list) 26 | println("\nYou chose : $choice") 27 | } -------------------------------------------------------------------------------- /src/tasks/Metaprogramming.kt: -------------------------------------------------------------------------------- 1 | package `metaprogramming` 2 | 3 | // version 1.0.6 4 | 5 | infix fun Double.pwr(exp: Double) = Math.pow(this, exp) 6 | 7 | fun main(args: Array) { 8 | val d = 2.0 pwr 8.0 9 | println(d) 10 | } -------------------------------------------------------------------------------- /src/tasks/Metered_concurrency.kt: -------------------------------------------------------------------------------- 1 | package `metered_concurrency` 2 | 3 | // version 1.1.51 4 | 5 | import java.util.concurrent.Semaphore 6 | import kotlin.concurrent.thread 7 | 8 | fun main(args: Array) { 9 | val numPermits = 4 10 | val numThreads = 9 11 | val semaphore = Semaphore(numPermits) 12 | for (i in 1..numThreads) { 13 | thread { 14 | val name = "Unit #$i" 15 | semaphore.acquire() 16 | println("$name has acquired the semaphore") 17 | Thread.sleep(2000) 18 | semaphore.release() 19 | println("$name has released the semaphore") 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /src/tasks/Metronome.kt: -------------------------------------------------------------------------------- 1 | package `metronome` 2 | 3 | // version 1.1.2 4 | 5 | fun metronome(bpm: Int, bpb: Int, maxBeats: Int = Int.MAX_VALUE) { 6 | val delay = 60_000L / bpm 7 | var beats = 0 8 | do { 9 | Thread.sleep(delay) 10 | if (beats % bpb == 0) print("\nTICK ") 11 | else print("tick ") 12 | beats++ 13 | } 14 | while (beats < maxBeats) 15 | println() 16 | } 17 | 18 | fun main(args: Array) = metronome(120, 4, 20) // limit to 20 beats -------------------------------------------------------------------------------- /src/tasks/Middle_three_digits.kt: -------------------------------------------------------------------------------- 1 | package `middle_three_digits` 2 | 3 | fun middleThree(x: Int): Int? { 4 | val s = Math.abs(x).toString() 5 | return when { 6 | s.length < 3 -> null // throw Exception("too short!") 7 | s.length % 2 == 0 -> null // throw Exception("even number of digits") 8 | else -> ((s.length / 2) - 1).let { s.substring(it, it + 3) }.toInt() 9 | } 10 | } 11 | 12 | fun main(args: Array) { 13 | println(middleThree(12345)) // 234 14 | println(middleThree(1234)) // null 15 | println(middleThree(1234567)) // 345 16 | println(middleThree(123))// 123 17 | println(middleThree(123555)) //null 18 | } 19 | -------------------------------------------------------------------------------- /src/tasks/Modular_exponentiation.kt: -------------------------------------------------------------------------------- 1 | package `modular_exponentiation` 2 | 3 | // version 1.0.6 4 | 5 | import java.math.BigInteger 6 | 7 | fun main(args: Array) { 8 | val a = BigInteger("2988348162058574136915891421498819466320163312926952423791023078876139") 9 | val b = BigInteger("2351399303373464486466122544523690094744975233415544072992656881240319") 10 | val m = BigInteger.TEN.pow(40) 11 | println(a.modPow(b, m)) 12 | } -------------------------------------------------------------------------------- /src/tasks/Modular_inverse.kt: -------------------------------------------------------------------------------- 1 | package `modular_inverse` 2 | 3 | // version 1.0.6 4 | 5 | import java.math.BigInteger 6 | 7 | fun main(args: Array) { 8 | val a = BigInteger.valueOf(42) 9 | val m = BigInteger.valueOf(2017) 10 | println(a.modInverse(m)) 11 | } -------------------------------------------------------------------------------- /src/tasks/Monads-List_monad.kt: -------------------------------------------------------------------------------- 1 | package `monads_list_monad` 2 | 3 | // version 1.2.10 4 | 5 | class MList private constructor(val value: List) { 6 | fun bind(f: (List) -> MList) = f(this.value) 7 | 8 | companion object { 9 | fun unit(lt: List) = MList(lt) 10 | } 11 | } 12 | 13 | fun doubler(li: List) = MList.unit(li.map { 2 * it } ) 14 | 15 | fun letters(li: List) = MList.unit(li.map { "${('@' + it)}".repeat(it) } ) 16 | 17 | fun main(args: Array) { 18 | val iv = MList.unit(listOf(2, 3, 4)) 19 | val fv = iv.bind(::doubler).bind(::letters) 20 | println(fv.value) 21 | } -------------------------------------------------------------------------------- /src/tasks/Monte_Carlo_methods.kt: -------------------------------------------------------------------------------- 1 | package `monte_carlo_methods` 2 | 3 | // version 1.1.0 4 | 5 | fun mcPi(n: Int): Double { 6 | var inside = 0 7 | (1..n).forEach { 8 | val x = Math.random() 9 | val y = Math.random() 10 | if (x * x + y * y <= 1.0) inside++ 11 | } 12 | return 4.0 * inside / n 13 | } 14 | 15 | fun main(args: Array) { 16 | println("Iterations -> Approx Pi -> Error%") 17 | println("---------- ---------- ------") 18 | var n = 1_000 19 | while (n <= 100_000_000) { 20 | val pi = mcPi(n) 21 | val err = Math.abs(Math.PI - pi) / Math.PI * 100.0 22 | println(String.format("%9d -> %10.8f -> %6.4f", n, pi, err)) 23 | n *= 10 24 | } 25 | } -------------------------------------------------------------------------------- /src/tasks/Mouse_position.kt: -------------------------------------------------------------------------------- 1 | package `mouse_position` 2 | 3 | // version 1.1.2 4 | 5 | import java.awt.MouseInfo 6 | 7 | fun main(args: Array) { 8 | (1..5).forEach { 9 | Thread.sleep(1000) 10 | val p = MouseInfo.getPointerInfo().location // gets screen coordinates 11 | println("${it}: x = ${"%-4d".format(p.x)} y = ${"%-4d".format(p.y)}") 12 | } 13 | } -------------------------------------------------------------------------------- /src/tasks/Multifactorial.kt: -------------------------------------------------------------------------------- 1 | package `multifactorial` 2 | 3 | fun multifactorial(n: Long, d: Int) : Long { 4 | val r = n % d 5 | return (1..n).filter { it % d == r } .reduce { i, p -> i * p } 6 | } 7 | 8 | fun main(args: Array) { 9 | val m = 5 10 | val r = 1..10L 11 | for (d in 1..m) { 12 | print("%${m}s:".format( "!".repeat(d))) 13 | r.forEach { print(" " + multifactorial(it, d)) } 14 | println() 15 | } 16 | } -------------------------------------------------------------------------------- /src/tasks/Multiple_distinct_objects.kt: -------------------------------------------------------------------------------- 1 | package `multiple_distinct_objects` 2 | 3 | // version 1.1.2 4 | 5 | class Foo { 6 | val id: Int 7 | 8 | init { 9 | id = ++numCreated // creates a distict id for each object 10 | } 11 | 12 | companion object { 13 | private var numCreated = 0 14 | } 15 | } 16 | 17 | fun main(args: Array) { 18 | val n = 3 // say 19 | 20 | /* correct approach - creates references to distinct objects */ 21 | val fooList = List(n) { Foo() } 22 | for (foo in fooList) println(foo.id) 23 | 24 | /* incorrect approach - creates references to same object */ 25 | val f = Foo() 26 | val fooList2 = List(n) { f } 27 | for (foo in fooList2) println(foo.id) 28 | } -------------------------------------------------------------------------------- /src/tasks/Multiplication_tables.kt: -------------------------------------------------------------------------------- 1 | package `multiplication_tables` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | print(" x|") 7 | for (i in 1..12) print("%4d".format(i)) 8 | println("\n---+${"-".repeat(48)}") 9 | for (i in 1..12) { 10 | print("%3d".format(i) +"|${" ".repeat(4 * i - 4)}") 11 | for (j in i..12) print("%4d".format(i * j)) 12 | println() 13 | } 14 | } -------------------------------------------------------------------------------- /src/tasks/Munchausen_numbers.kt: -------------------------------------------------------------------------------- 1 | package `munchausen_numbers` 2 | 3 | // version 1.0.6 4 | 5 | val powers = IntArray(10) 6 | 7 | fun isMunchausen(n: Int): Boolean { 8 | if (n < 0) return false 9 | var sum = 0L 10 | var nn = n 11 | while (nn > 0) { 12 | sum += powers[nn % 10] 13 | if (sum > n.toLong()) return false 14 | nn /= 10 15 | } 16 | return sum == n.toLong() 17 | } 18 | 19 | fun main(args: Array) { 20 | // cache n ^ n for n in 0..9, defining 0 ^ 0 = 0 for this purpose 21 | for (i in 1..9) powers[i] = Math.pow(i.toDouble(), i.toDouble()).toInt() 22 | 23 | // check numbers 0 to 500 million 24 | println("The Munchausen numbers between 0 and 500 million are:") 25 | for (i in 0..500000000) if (isMunchausen(i))print ("$i ") 26 | println() 27 | } -------------------------------------------------------------------------------- /src/tasks/Mutual_recursion.kt: -------------------------------------------------------------------------------- 1 | package `mutual_recursion` 2 | 3 | // version 1.0.6 4 | 5 | fun f(n: Int): Int = 6 | when { 7 | n == 0 -> 1 8 | else -> n - m(f(n - 1)) 9 | } 10 | 11 | fun m(n: Int): Int = 12 | when { 13 | n == 0 -> 0 14 | else -> n - f(m(n - 1)) 15 | } 16 | 17 | fun main(args: Array) { 18 | val n = 24 19 | print("n :") 20 | for (i in 0..n) print("%3d".format(i)) 21 | println() 22 | println("-".repeat(78)) 23 | print("F :") 24 | for (i in 0..24) print("%3d".format(f(i))) 25 | println() 26 | print("M :") 27 | for (i in 0..24) print("%3d".format(m(i))) 28 | println() 29 | } -------------------------------------------------------------------------------- /src/tasks/Named_parameters.kt: -------------------------------------------------------------------------------- 1 | package `named_parameters` 2 | 3 | // version 1.0.6 4 | 5 | fun someFunction(first: String, second: Int = 2, third: Double) { 6 | println("First = ${first.padEnd(10)}, Second = $second, Third = $third") 7 | } 8 | 9 | fun main(args: Array) { 10 | // using positional parameters 11 | someFunction("positional", 1, 2.0) 12 | 13 | // using named parameters 14 | someFunction(first = "named", second = 1, third = 2.0) 15 | 16 | // omitting 2nd parameter which is optional because it has a default value 17 | someFunction(first = "omitted", third = 2.0) 18 | 19 | // using first and third parameters in reverse 20 | someFunction(third = 2.0, first = "reversed") 21 | } -------------------------------------------------------------------------------- /src/tasks/Narcissist.kt: -------------------------------------------------------------------------------- 1 | package `narcissist` 2 | 3 | // version 1.1.0 (run on Windows 10) 4 | 5 | fun main(args: Array) { 6 | val text = java.io.File("narcissist.kt").readText() 7 | println("Enter the number of lines to be input followed by those lines:\n") 8 | val n = readLine()!!.toInt() 9 | val lines = Array(n) { readLine()!! } 10 | if (lines.joinToString("\r\n") == text) println("\naccept") else println("\nreject") 11 | } -------------------------------------------------------------------------------- /src/tasks/Nested_function.kt: -------------------------------------------------------------------------------- 1 | package `nested_function` 2 | 3 | // version 1.0.6 4 | 5 | fun makeList(sep: String): String { 6 | var count = 0 7 | fun makeItem(item: String): String { 8 | count++ 9 | return "$count$sep$item\n" 10 | } 11 | return makeItem("first") + makeItem("second") + makeItem("third") 12 | } 13 | 14 | fun main(args: Array) { 15 | print(makeList(". ")) 16 | } -------------------------------------------------------------------------------- /src/tasks/Non-decimal_radices-Input.kt: -------------------------------------------------------------------------------- 1 | package `non_decimal_radices_input` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args: Array) { 6 | val s = "100" 7 | val bases = intArrayOf(2, 8, 10, 16, 19, 36) 8 | for (base in bases) 9 | println("$s in base ${"%2d".format(base)} is ${s.toInt(base)}") 10 | } -------------------------------------------------------------------------------- /src/tasks/Non-decimal_radices-Output.kt: -------------------------------------------------------------------------------- 1 | package `non_decimal_radices_output` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args: Array) { 6 | val bases = intArrayOf(2, 8, 10, 16, 19, 36) 7 | for (base in bases) print("%6s".format(base)) 8 | println() 9 | println("-".repeat(6 * bases.size)) 10 | for (i in 0..35) { 11 | for (base in bases) print("%6s".format(i.toString(base))) 12 | println() 13 | } 14 | } -------------------------------------------------------------------------------- /src/tasks/Nth.kt: -------------------------------------------------------------------------------- 1 | package `nth` 2 | 3 | fun Int.ordinalAbbrev() = 4 | if (this % 100 / 10 == 1) "th" 5 | else when (this % 10) { 1 -> "st" 2 -> "nd" 3 -> "rd" else -> "th" } 6 | 7 | fun IntRange.ordinalAbbrev() = map { "$it" + it.ordinalAbbrev() }.joinToString(" ") 8 | 9 | fun main(args: Array) { 10 | listOf((0..25), (250..265), (1000..1025)).forEach { println(it.ordinalAbbrev()) } 11 | } -------------------------------------------------------------------------------- /src/tasks/Nth_root.kt: -------------------------------------------------------------------------------- 1 | package `nth_root` 2 | 3 | // version 1.0.6 4 | 5 | fun nthRoot(x: Double, n: Int): Double { 6 | if (n < 2) throw IllegalArgumentException("n must be more than 1") 7 | if (x <= 0.0) throw IllegalArgumentException("x must be positive") 8 | val np = n - 1 9 | fun iter(g: Double) = (np * g + x / Math.pow(g, np.toDouble())) / n 10 | var g1 = x 11 | var g2 = iter(g1) 12 | while (g1 != g2) { 13 | g1 = iter(g1) 14 | g2 = iter(iter(g2)) 15 | } 16 | return g1 17 | } 18 | 19 | fun main(args: Array) { 20 | val numbers = arrayOf(1728.0 to 3, 1024.0 to 10, 2.0 to 2) 21 | for (number in numbers) 22 | println("${number.first} ^ 1/${number.second}\t = ${nthRoot(number.first, number.second)}") 23 | } -------------------------------------------------------------------------------- /src/tasks/Null_object.kt: -------------------------------------------------------------------------------- 1 | package `null_object` 2 | 3 | // version 1.1.0 4 | 5 | fun main(args: Array) { 6 | val i: Int = 3 // non-nullable Int type - can't be assigned null 7 | println(i) 8 | val j: Int? = null // nullable Int type - can be assigned null 9 | println(j) 10 | println(null is Nothing?) // test that null is indeed of type Nothing? 11 | } -------------------------------------------------------------------------------- /src/tasks/Odd_word_problem.kt: -------------------------------------------------------------------------------- 1 | package `odd_word_problem` 2 | 3 | // version 1.1.3 4 | 5 | typealias Func = () -> Unit 6 | 7 | fun doChar(odd: Boolean, f: Func?): Boolean { 8 | val c = System.`in`.read() 9 | if (c == -1) return false // end of stream reached 10 | val ch = c.toChar() 11 | 12 | fun writeOut() { 13 | print(ch) 14 | if (f != null) f() 15 | } 16 | 17 | if (!odd) print(ch) 18 | if (ch.isLetter()) return doChar(odd, ::writeOut) 19 | if (odd) { 20 | if (f != null) f() 21 | print(ch) 22 | } 23 | return ch != '.' 24 | } 25 | 26 | fun main(args: Array) { 27 | repeat(2) { 28 | var b = true 29 | while (doChar(!b, null)) b = !b 30 | System.`in`.read() // remove '\n' from buffer 31 | println("\n") 32 | } 33 | } -------------------------------------------------------------------------------- /src/tasks/One_of_n_lines_in_a_file.kt: -------------------------------------------------------------------------------- 1 | package `one_of_n_lines_in_a_file` 2 | 3 | // version 1.1.51 4 | 5 | import java.util.Random 6 | 7 | val r = Random() 8 | 9 | fun oneOfN(n: Int): Int { 10 | var choice = 1 11 | for (i in 2..n) { 12 | if (r.nextDouble() < 1.0 / i) choice = i 13 | } 14 | return choice 15 | } 16 | 17 | fun main(args: Array) { 18 | val n = 10 19 | val freqs = IntArray(n) 20 | val reps = 1_000_000 21 | repeat(reps) { 22 | val num = oneOfN(n) 23 | freqs[num - 1]++ 24 | } 25 | for (i in 1..n) println("Line ${"%-2d".format(i)} = ${freqs[i - 1]}") 26 | } -------------------------------------------------------------------------------- /src/tasks/Ordered_words.kt: -------------------------------------------------------------------------------- 1 | package `ordered_words` 2 | 3 | import java.io.File 4 | 5 | fun main(args: Array) { 6 | val file = File("unixdict.txt") 7 | val result = mutableListOf() 8 | 9 | file.forEachLine { 10 | if (it.toCharArray().sorted().joinToString(separator = "") == it) { 11 | result += it 12 | } 13 | } 14 | 15 | result.sortByDescending { it.length } 16 | val max = result[0].length 17 | 18 | for (word in result) { 19 | if (word.length == max) { 20 | println(word) 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /src/tasks/Pangram_checker.kt: -------------------------------------------------------------------------------- 1 | package `pangram_checker` 2 | 3 | // version 1.0.6 4 | 5 | fun isPangram(s: String): Boolean { 6 | if (s.length < 26) return false 7 | val t = s.toLowerCase() 8 | for (c in 'a' .. 'z') 9 | if (c !in t) return false 10 | return true 11 | } 12 | 13 | fun main(args: Array) { 14 | val candidates = arrayOf( 15 | "The quick brown fox jumps over the lazy dog", 16 | "New job: fix Mr. Gluck's hazy TV, PDQ!", 17 | "A very bad quack might jinx zippy fowls", 18 | "A very mad quack might jinx zippy fowls" // no 'b' now! 19 | ) 20 | for (candidate in candidates) 21 | println("'$candidate' is ${if (isPangram(candidate)) "a" else "not a"} pangram") 22 | } -------------------------------------------------------------------------------- /src/tasks/Parametric_polymorphism.kt: -------------------------------------------------------------------------------- 1 | package `parametric_polymorphism` 2 | 3 | // version 1.0.6 4 | 5 | class BinaryTree(var value: T) { 6 | var left : BinaryTree? = null 7 | var right: BinaryTree? = null 8 | 9 | fun map(f: (T) -> U): BinaryTree { 10 | val tree = BinaryTree(f(value)) 11 | if (left != null) tree.left = left?.map(f) 12 | if (right != null) tree.right = right?.map(f) 13 | return tree 14 | } 15 | 16 | fun showTopThree() = "(${left?.value}, $value, ${right?.value})" 17 | } 18 | 19 | fun main(args: Array) { 20 | val b = BinaryTree(6) 21 | b.left = BinaryTree(5) 22 | b.right = BinaryTree(7) 23 | println(b.showTopThree()) 24 | val b2 = b.map { it * 10.0 } 25 | println(b2.showTopThree()) 26 | } -------------------------------------------------------------------------------- /src/tasks/Parse_command-line_arguments.kt: -------------------------------------------------------------------------------- 1 | package `parse_command_line_arguments` 2 | 3 | // version 1.0.6 (packaged as parse_cla.jar) 4 | 5 | fun main(args: Array) = println(args.asList()) -------------------------------------------------------------------------------- /src/tasks/Pascals_triangle-Puzzle.kt: -------------------------------------------------------------------------------- 1 | package `pascals_triangle_puzzle` 2 | 3 | // version 1.1.3 4 | 5 | data class Solution(val x: Int, val y: Int, val z: Int) 6 | 7 | fun Double.isIntegral(tolerance: Double = 0.0) = 8 | (this - Math.floor(this)) <= tolerance || (Math.ceil(this) - this) <= tolerance 9 | 10 | fun pascal(a: Int, b: Int, mid: Int, top: Int): Solution { 11 | val yd = (top - 4 * (a + b)) / 7.0 12 | if (!yd.isIntegral(0.0001)) return Solution(0, 0, 0) 13 | val y = yd.toInt() 14 | val x = mid - 2 * a - y 15 | return Solution(x, y, y - x) 16 | } 17 | 18 | fun main(args: Array) { 19 | val (x, y, z) = pascal(11, 4, 40, 151) 20 | if (x != 0) 21 | println("Solution is: x = $x, y = $y, z = $z") 22 | else 23 | println("There is no solutuon") 24 | } -------------------------------------------------------------------------------- /src/tasks/Pascals_triangle.kt: -------------------------------------------------------------------------------- 1 | package `pascals_triangle` 2 | 3 | fun pas(rows: Int) { 4 | for (i in 0..rows - 1) { 5 | for (j in 0..i) 6 | print(ncr(i, j).toString() + " ") 7 | println() 8 | } 9 | } 10 | 11 | fun ncr(n: Int, r: Int) = fact(n) / (fact(r) * fact(n - r)) 12 | 13 | fun fact(n: Int) : Long { 14 | var ans = 1.toLong() 15 | for (i in 2..n) 16 | ans *= i 17 | return ans 18 | } 19 | 20 | fun main(args: Array) = pas(args[0].toInt()) -------------------------------------------------------------------------------- /src/tasks/Permutations.kt: -------------------------------------------------------------------------------- 1 | package `permutations` 2 | 3 | // version 1.1.2 4 | 5 | fun permute(input: List): List> { 6 | if (input.size == 1) return listOf(input) 7 | val perms = mutableListOf>() 8 | val toInsert = input[0] 9 | for (perm in permute(input.drop(1))) { 10 | for (i in 0..perm.size) { 11 | val newPerm = perm.toMutableList() 12 | newPerm.add(i, toInsert) 13 | perms.add(newPerm) 14 | } 15 | } 16 | return perms 17 | } 18 | 19 | fun main(args: Array) { 20 | val input = listOf('a', 'b', 'c', 'd') 21 | val perms = permute(input) 22 | println("There are ${perms.size} permutations of $input, namely:\n") 23 | for (perm in perms) println(perm) 24 | } -------------------------------------------------------------------------------- /src/tasks/Phrase_reversals.kt: -------------------------------------------------------------------------------- 1 | package `phrase_reversals` 2 | 3 | // version 1.0.6 4 | 5 | fun reverseEachWord(s: String) = s.split(" ").map { it.reversed() }.joinToString(" ") 6 | 7 | fun main(args: Array) { 8 | val original = "rosetta code phrase reversal" 9 | val reversed = original.reversed() 10 | println("Original string => $original") 11 | println("Reversed string => $reversed") 12 | println("Reversed words => ${reverseEachWord(original)}") 13 | println("Reversed order => ${reverseEachWord(reversed)}") 14 | } -------------------------------------------------------------------------------- /src/tasks/Pragmatic_directives.kt: -------------------------------------------------------------------------------- 1 | package `pragmatic_directives` 2 | 3 | // version 1.0.6 4 | 5 | @Suppress("UNUSED_VARIABLE") 6 | 7 | fun main(args: Array) { 8 | val s = "To be suppressed" 9 | } -------------------------------------------------------------------------------- /src/tasks/Primality_by_trial_division.kt: -------------------------------------------------------------------------------- 1 | package `primality_by_trial_division` 2 | 3 | // version 1.1.2 4 | fun isPrime(n: Int): Boolean { 5 | if (n < 2) return false 6 | if (n % 2 == 0) return n == 2 7 | val limit = Math.sqrt(n.toDouble()).toInt() 8 | return (3..limit step 2).none { n % it == 0 } 9 | } 10 | 11 | fun main(args: Array) { 12 | // test by printing all primes below 100 say 13 | (2..99).filter { isPrime(it) }.forEach { print("$it ") } 14 | } -------------------------------------------------------------------------------- /src/tasks/Priority_queue.kt: -------------------------------------------------------------------------------- 1 | package `priority_queue` 2 | 3 | import java.util.PriorityQueue 4 | 5 | internal data class Task(val priority: Int, val name: String) : Comparable { 6 | override fun compareTo(other: Task) = when { 7 | priority < other.priority -> -1 8 | priority > other.priority -> 1 9 | else -> 0 10 | } 11 | } 12 | 13 | private infix fun String.priority(priority: Int) = Task(priority, this) 14 | 15 | fun main(args: Array) { 16 | val q = PriorityQueue(listOf("Clear drains" priority 3, 17 | "Feed cat" priority 4, 18 | "Make tea" priority 5, 19 | "Solve RC tasks" priority 1, 20 | "Tax return" priority 2)) 21 | while (q.any()) println(q.remove()) 22 | } -------------------------------------------------------------------------------- /src/tasks/Program_name.kt: -------------------------------------------------------------------------------- 1 | package `program_name` 2 | 3 | // version 1.0.6 4 | 5 | // 'progname.kt' packaged as 'progname.jar' 6 | 7 | fun main(args: Array) { 8 | println(System.getProperty("sun.java.command")) // may not exist on all JVMs 9 | println(System.getProperty("java.vm.name")) 10 | } -------------------------------------------------------------------------------- /src/tasks/Program_termination.kt: -------------------------------------------------------------------------------- 1 | package `program_termination` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | val problem = true 7 | if (problem) System.exit(1) // non-zero code passed to OS to indicate a problem 8 | println("Program terminating normally") // this line will not be executed 9 | } -------------------------------------------------------------------------------- /src/tasks/Queue-Usage.kt: -------------------------------------------------------------------------------- 1 | package `queue_usage` 2 | 3 | // version 1.1.2 4 | 5 | import java.util.* 6 | 7 | fun main(args: Array) { 8 | val q: Queue = ArrayDeque() 9 | (1..5).forEach { q.add(it) } 10 | println(q) 11 | println("Size of queue = ${q.size}") 12 | print("Removing: ") 13 | (1..3).forEach { print("${q.remove()} ") } 14 | println("\nRemaining in queue: $q") 15 | println("Head element is now ${q.element()}") 16 | q.clear() 17 | println("After clearing, queue is ${if(q.isEmpty()) "empty" else "not empty"}") 18 | try { 19 | q.remove() 20 | } 21 | catch (e: NoSuchElementException) { 22 | println("Can't remove elements from an empty queue") 23 | } 24 | } -------------------------------------------------------------------------------- /src/tasks/Quine.kt: -------------------------------------------------------------------------------- 1 | package `quine` 2 | 3 | // version 1.1.2 4 | 5 | const val F = """// version 1.1.2 6 | 7 | const val F = %c%c%c%s%c%c%c 8 | 9 | fun main(args: Array) { 10 | System.out.printf(F, 34, 34, 34, F, 34, 34, 34) 11 | } 12 | """ 13 | 14 | fun main(args: Array) { 15 | System.out.printf(F, 34, 34, 34, F, 34, 34, 34) 16 | } -------------------------------------------------------------------------------- /src/tasks/RIPEMD-160.kt: -------------------------------------------------------------------------------- 1 | package `ripemd_160` 2 | 3 | import org.bouncycastle.crypto.digests.RIPEMD160Digest 4 | import org.bouncycastle.util.encoders.Hex 5 | import kotlin.text.Charsets.US_ASCII 6 | 7 | fun RIPEMD160Digest.inOneGo(input : ByteArray) : ByteArray { 8 | val output = ByteArray(digestSize) 9 | 10 | update(input, 0, input.size) 11 | doFinal(output, 0) 12 | 13 | return output 14 | } 15 | 16 | fun main(args: Array) { 17 | val input = "Rosetta Code".toByteArray(US_ASCII) 18 | val output = RIPEMD160Digest().inOneGo(input) 19 | 20 | Hex.encode(output, System.out) 21 | System.out.flush() 22 | } -------------------------------------------------------------------------------- /src/tasks/RPG_Attributes_Generator.kt: -------------------------------------------------------------------------------- 1 | package `rpg_attributes_generator` 2 | 3 | // Version 1.2.51 4 | 5 | import java.util.Random 6 | 7 | fun main(args: Array) { 8 | val r = Random() 9 | while (true) { 10 | val values = IntArray(6) 11 | for (i in 0..5) { 12 | val numbers = IntArray(4) { 1 + r.nextInt(6) } 13 | numbers.sort() 14 | values[i] = numbers.drop(1).sum() 15 | } 16 | val vsum = values.sum() 17 | val vcount = values.count { it >= 15 } 18 | if (vsum < 75 || vcount < 2) continue 19 | println("The 6 random numbers generated are:") 20 | println(values.asList()) 21 | println("\nTheir sum is $vsum and $vcount of them are >= 15") 22 | break 23 | } 24 | } -------------------------------------------------------------------------------- /src/tasks/Random_number_generator_(device).kt: -------------------------------------------------------------------------------- 1 | package `random_number_generator_(device)` 2 | 3 | // version 1.1.2 4 | 5 | import java.security.SecureRandom 6 | 7 | fun main(args: Array) { 8 | val rng = SecureRandom() 9 | val rn1 = rng.nextInt() 10 | val rn2 = rng.nextInt() 11 | val newSeed = rn1.toLong() * rn2 12 | rng.setSeed(newSeed) // reseed using the previous 2 random numbers 13 | println(rng.nextInt()) // get random 32-bit number and print it 14 | } -------------------------------------------------------------------------------- /src/tasks/Random_numbers.kt: -------------------------------------------------------------------------------- 1 | package `random_numbers` 2 | 3 | // version 1.0.6 4 | 5 | import java.util.Random 6 | 7 | fun main(args: Array) { 8 | val r = Random() 9 | val da = DoubleArray(1000) 10 | for (i in 0 until 1000) da[i] = 1.0 + 0.5 * r.nextGaussian() 11 | // now check actual mean and SD 12 | val mean = da.average() 13 | val sd = Math.sqrt(da.map { (it - mean) * (it - mean) }.average()) 14 | println("Mean is $mean") 15 | println("S.D. is $sd") 16 | } -------------------------------------------------------------------------------- /src/tasks/Rate_counter.kt: -------------------------------------------------------------------------------- 1 | package `rate_counter` 2 | 3 | // version 1.1.3 4 | 5 | typealias Func = (T) -> T 6 | 7 | fun cube(n: Int) = n * n * n 8 | 9 | fun benchmark(n: Int, func: Func, arg: T): LongArray { 10 | val times = LongArray(n) 11 | for (i in 0 until n) { 12 | val m = System.nanoTime() 13 | func(arg) 14 | times[i] = System.nanoTime() - m 15 | } 16 | return times 17 | } 18 | 19 | fun main(args: Array) { 20 | println("\nTimings (nanoseconds) : ") 21 | for (time in benchmark(10, ::cube, 5)) println(time) 22 | } -------------------------------------------------------------------------------- /src/tasks/Read_a_file_character_by_character-UTF8.kt: -------------------------------------------------------------------------------- 1 | package `read_a_file_character_by_character_utf8` 2 | 3 | // version 1.1.2 4 | 5 | import java.io.File 6 | 7 | const val EOF = -1 8 | 9 | fun main(args: Array) { 10 | val reader = File("input.txt").reader() // uses UTF-8 by default 11 | reader.use { 12 | while (true) { 13 | val c = reader.read() 14 | if (c == EOF) break 15 | print(c.toChar()) // echo to console 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /src/tasks/Read_a_file_line_by_line.kt: -------------------------------------------------------------------------------- 1 | package `read_a_file_line_by_line` 2 | 3 | // version 1.1.2 4 | 5 | import java.io.File 6 | 7 | fun main(args: Array) { 8 | File("input.txt").forEachLine { println(it) } 9 | } -------------------------------------------------------------------------------- /src/tasks/Read_entire_file.kt: -------------------------------------------------------------------------------- 1 | package `read_entire_file` 2 | 3 | import java.io.File 4 | 5 | fun main(args: Array) { 6 | println(File("unixdict.txt").readText(charset = Charsets.UTF_8)) 7 | } -------------------------------------------------------------------------------- /src/tasks/Real_constants_and_functions.kt: -------------------------------------------------------------------------------- 1 | package `real_constants_and_functions` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | println(Math.E) // e 7 | println(Math.PI) // pi 8 | println(Math.sqrt(2.0)) // square root 9 | println(Math.log(Math.E)) // log to base e 10 | println(Math.log10(10.0)) // log to base 10 11 | println(Math.exp(1.0)) // exponential 12 | println(Math.abs(-1)) // absolute value 13 | println(Math.floor(-2.5)) // floor 14 | println(Math.ceil(-2.5)) // ceiling 15 | println(Math.pow(2.5, 3.5)) // power 16 | } -------------------------------------------------------------------------------- /src/tasks/Reflection-List_methods.kt: -------------------------------------------------------------------------------- 1 | package `reflection_list_methods` 2 | 3 | // Version 1.2.31 4 | 5 | import kotlin.reflect.full.functions 6 | 7 | open class MySuperClass { 8 | fun mySuperClassMethod(){} 9 | } 10 | 11 | open class MyClass : MySuperClass() { 12 | fun myPublicMethod(){} 13 | 14 | internal fun myInternalMethod(){} 15 | 16 | protected fun myProtectedMethod(){} 17 | 18 | private fun myPrivateMethod(){} 19 | } 20 | 21 | fun main(args: Array) { 22 | val c = MyClass::class 23 | println("List of methods declared in ${c.simpleName} and its superclasses:\n") 24 | val fs = c.functions 25 | for (f in fs) println("${f.name}, ${f.visibility}") 26 | } -------------------------------------------------------------------------------- /src/tasks/Regular_expressions.kt: -------------------------------------------------------------------------------- 1 | package `regular_expressions` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | val s1 = "I am the original string" 7 | val r1 = Regex("^.*string$") 8 | if (s1.matches(r1)) println("`$s1` matches `$r1`") 9 | val r2 = Regex("original") 10 | val s3 = "replacement" 11 | val s2 = s1.replace(r2, s3) 12 | if (s2 != s1) println("`$s2` replaces `$r2` with `$s3`") 13 | } -------------------------------------------------------------------------------- /src/tasks/Remove_duplicate_elements.kt: -------------------------------------------------------------------------------- 1 | package `remove_duplicate_elements` 2 | 3 | fun main(args: Array) { 4 | val data = listOf(1, 2, 3, "a", "b", "c", 2, 3, 4, "b", "c", "d") 5 | val set = data.distinct() 6 | 7 | println(data) 8 | println(set) 9 | } -------------------------------------------------------------------------------- /src/tasks/Rename_a_file.kt: -------------------------------------------------------------------------------- 1 | package `rename_a_file` 2 | 3 | // version 1.0.6 4 | 5 | /* testing on Windows 10 which needs administrative privileges 6 | to rename files in the root */ 7 | 8 | import java.io.File 9 | 10 | fun main(args: Array) { 11 | val oldPaths = arrayOf("input.txt", "docs", "c:\\input.txt", "c:\\docs") 12 | val newPaths = arrayOf("output.txt", "mydocs", "c:\\output.txt", "c:\\mydocs") 13 | var oldFile: File 14 | var newFile: File 15 | for (i in 0 until oldPaths.size) { 16 | oldFile = File(oldPaths[i]) 17 | newFile = File(newPaths[i]) 18 | if (oldFile.renameTo(newFile)) 19 | println("${oldPaths[i]} successfully renamed to ${newPaths[i]}") 20 | else 21 | println("${oldPaths[i]} could not be renamed") 22 | } 23 | } -------------------------------------------------------------------------------- /src/tasks/Repeat.kt: -------------------------------------------------------------------------------- 1 | package `repeat` 2 | 3 | // version 1.0.6 4 | 5 | fun repeat(n: Int, f: () -> Unit) { 6 | for (i in 1..n) { 7 | f() 8 | println(i) 9 | } 10 | } 11 | 12 | fun main(args: Array) { 13 | repeat(5) { print("Example ") } 14 | } -------------------------------------------------------------------------------- /src/tasks/Repeat_a_string-1.kt: -------------------------------------------------------------------------------- 1 | package `repeat_a_string_1` 2 | 3 | operator fun String.times(n: Int) = this.repeat(n) 4 | 5 | fun main(args: Array) = println("ha" * 5) -------------------------------------------------------------------------------- /src/tasks/Repeat_a_string.kt: -------------------------------------------------------------------------------- 1 | package `repeat_a_string` 2 | 3 | fun main(args: Array) { 4 | println("ha".repeat(5)) 5 | } -------------------------------------------------------------------------------- /src/tasks/Return_multiple_values.kt: -------------------------------------------------------------------------------- 1 | package `return_multiple_values` 2 | 3 | // version 1.0.6 4 | 5 | /* implicitly returns a Pair*/ 6 | fun minmax(ia: IntArray) = ia.min() to ia.max() 7 | 8 | fun main(args: Array) { 9 | val ia = intArrayOf(17, 88, 9, 33, 4, 987, -10, 2) 10 | val(min, max) = minmax(ia) // destructuring declaration 11 | println("The smallest number is $min") 12 | println("The largest number is $max") 13 | } -------------------------------------------------------------------------------- /src/tasks/Reverse_a_string.kt: -------------------------------------------------------------------------------- 1 | package `reverse_a_string` 2 | 3 | fun main(args: Array) { 4 | println("asdf".reversed()) 5 | } -------------------------------------------------------------------------------- /src/tasks/Roots_of_unity.kt: -------------------------------------------------------------------------------- 1 | package `roots_of_unity` 2 | 3 | import java.lang.Math.* 4 | 5 | data class Complex(val r: Double, val i: Double) { 6 | override fun toString() = when { 7 | i == 0.0 -> r.toString() 8 | r == 0.0 -> i.toString() + 'i' 9 | else -> "$r + ${i}i" 10 | } 11 | } 12 | 13 | fun unity_roots(n: Number) = (1..n.toInt() - 1).map { 14 | val a = it * 2 * PI / n.toDouble() 15 | var r = cos(a); if (abs(r) < 1e-6) r = 0.0 16 | var i = sin(a); if (abs(i) < 1e-6) i = 0.0 17 | Complex(r, i) 18 | } 19 | 20 | fun main(args: Array) { 21 | (1..4).forEach { println(listOf(1) + unity_roots(it)) } 22 | println(listOf(1) + unity_roots(5.0)) 23 | } -------------------------------------------------------------------------------- /src/tasks/Rot-13.kt: -------------------------------------------------------------------------------- 1 | package `rot_13` 2 | 3 | import java.io.* 4 | 5 | fun String.rot13() = map { 6 | when { 7 | it.isUpperCase() -> { val x = it + 13; if (x > 'Z') x - 26 else x } 8 | it.isLowerCase() -> { val x = it + 13; if (x > 'z') x - 26 else x } 9 | else -> it 10 | } }.toCharArray() 11 | 12 | fun InputStreamReader.println() = 13 | try { BufferedReader(this).forEachLine { println(it.rot13()) } } 14 | catch (e: IOException) { e.printStackTrace() } 15 | 16 | fun main(args: Array) { 17 | if (args.any()) 18 | args.forEach { FileReader(it).println() } 19 | else 20 | InputStreamReader(System.`in`).println() 21 | } -------------------------------------------------------------------------------- /src/tasks/Run-length_encoding.kt: -------------------------------------------------------------------------------- 1 | package `run_length_encoding` 2 | 3 | tailrec fun runLengthEncoding(text:String,prev:String=""):String { 4 | if (text.isEmpty()){ 5 | return prev 6 | } 7 | val initialChar = text.get(0) 8 | val count = text.takeWhile{ it==initialChar }.count() 9 | return runLengthEncoding(text.substring(count),prev + "$count$initialChar" ) 10 | } 11 | 12 | fun main(args: Array) { 13 | assert(runLengthEncoding("TTESSST") == "2T1E3S1T") 14 | assert(runLengthEncoding("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") 15 | == "12W1B12W3B24W1B14W") 16 | } -------------------------------------------------------------------------------- /src/tasks/SHA-1.kt: -------------------------------------------------------------------------------- 1 | package `sha_1` 2 | 3 | // version 1.0.6 4 | 5 | import java.security.MessageDigest 6 | 7 | fun main(args: Array) { 8 | val text = "Rosetta Code" 9 | val bytes = text.toByteArray() 10 | val md = MessageDigest.getInstance("SHA-1") 11 | val digest = md.digest(bytes) 12 | for (byte in digest) print("%02x".format(byte)) 13 | println() 14 | } -------------------------------------------------------------------------------- /src/tasks/SHA-256.kt: -------------------------------------------------------------------------------- 1 | package `sha_256` 2 | 3 | // version 1.0.6 4 | 5 | import java.security.MessageDigest 6 | 7 | fun main(args: Array) { 8 | val text = "Rosetta code" 9 | val bytes = text.toByteArray() 10 | val md = MessageDigest.getInstance("SHA-256") 11 | val digest = md.digest(bytes) 12 | for (byte in digest) print("%02x".format(byte)) 13 | println() 14 | } -------------------------------------------------------------------------------- /src/tasks/Safe_addition.kt: -------------------------------------------------------------------------------- 1 | package `safe_addition` 2 | 3 | // version 1.1.2 4 | 5 | fun stepDown(d: Double) = Math.nextAfter(d, Double.NEGATIVE_INFINITY) 6 | 7 | fun stepUp(d: Double) = Math.nextUp(d) 8 | 9 | fun safeAdd(a: Double, b: Double) = stepDown(a + b).rangeTo(stepUp(a + b)) 10 | 11 | fun main(args: Array) { 12 | val a = 1.2 13 | val b = 0.03 14 | println("($a + $b) is in the range ${safeAdd(a, b)}") 15 | } -------------------------------------------------------------------------------- /src/tasks/Sattolo_cycle.kt: -------------------------------------------------------------------------------- 1 | package `sattolo_cycle` 2 | 3 | // version 1.0.6 4 | 5 | fun sattolo(items: Array) { 6 | for (i in items.size - 1 downTo 1) { 7 | val j = (Math.random() * i).toInt() 8 | val t = items[i] 9 | items[i] = items[j] 10 | items[j] = t 11 | } 12 | } 13 | 14 | fun main(args: Array) { 15 | val items = arrayOf(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22) 16 | println(items.joinToString()) 17 | sattolo(items) 18 | println(items.joinToString()) 19 | } -------------------------------------------------------------------------------- /src/tasks/Scope_modifiers.kt: -------------------------------------------------------------------------------- 1 | package `scope_modifiers` 2 | 3 | // version 1.1.2 4 | 5 | class SomeClass { 6 | val id: Int 7 | 8 | companion object { 9 | private var lastId = 0 10 | val objectsCreated get() = lastId 11 | } 12 | 13 | init { 14 | id = ++lastId 15 | } 16 | } 17 | 18 | fun main(args: Array) { 19 | val sc1 = SomeClass() 20 | val sc2 = SomeClass() 21 | println(sc1.id) 22 | println(sc2.id) 23 | println(SomeClass.objectsCreated) 24 | } -------------------------------------------------------------------------------- /src/tasks/Search_a_list.kt: -------------------------------------------------------------------------------- 1 | package `search_a_list` 2 | 3 | // version 1.0.6 (search_list.kt) 4 | 5 | fun main(args: Array) { 6 | val haystack = listOf("Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Boz", "Zag") 7 | println(haystack) 8 | var needle = "Zag" 9 | var index = haystack.indexOf(needle) 10 | val index2 = haystack.lastIndexOf(needle) 11 | println("\n'$needle' first occurs at index $index of the list") 12 | println("'$needle' last occurs at index $index2 of the list\n") 13 | needle = "Donald" 14 | index = haystack.indexOf(needle) 15 | if (index == -1) throw Exception("$needle does not occur in the list") 16 | } -------------------------------------------------------------------------------- /src/tasks/Secure_temporary_file.kt: -------------------------------------------------------------------------------- 1 | package `secure_temporary_file` 2 | 3 | // version 1.1.2 4 | 5 | import java.io.File 6 | 7 | fun main(args: Array) { 8 | try { 9 | val tf = File.createTempFile("temp", ".tmp") 10 | println(tf.absolutePath) 11 | tf.delete() 12 | } 13 | catch (ex: Exception) { 14 | println(ex.message) 15 | } 16 | } -------------------------------------------------------------------------------- /src/tasks/Selective_File_Copy.kt: -------------------------------------------------------------------------------- 1 | package `selective_file_copy` 2 | 3 | // version 1.1.51 4 | 5 | import java.io.File 6 | 7 | fun process(line: String): String { 8 | with (line) { 9 | val a = substring(0, 5) 10 | val n = (substring(14, 15) + substring(10, 14)).toInt() 11 | return String.format("%s%5dXXXXX", a, n) 12 | } 13 | } 14 | 15 | fun main(args: Array) { 16 | val out = File("selective_output.txt") 17 | val pw = out.printWriter() 18 | File("selective_input.txt").forEachLine { pw.println(process(it)) } 19 | pw.close() 20 | // check it worked 21 | println(out.readText()) 22 | } -------------------------------------------------------------------------------- /src/tasks/Self-describing_numbers.kt: -------------------------------------------------------------------------------- 1 | package `self_describing_numbers` 2 | 3 | // version 1.0.6 4 | 5 | fun selfDescribing(n: Int): Boolean { 6 | if (n <= 0) return false 7 | val ns = n.toString() 8 | val count = IntArray(10) 9 | var nn = n 10 | while (nn > 0) { 11 | count[nn % 10] += 1 12 | nn /= 10 13 | } 14 | for (i in 0 until ns.length) 15 | if( ns[i] - '0' != count[i]) return false 16 | return true 17 | } 18 | 19 | fun main(args: Array) { 20 | println("The self-describing numbers less than 100 million are:") 21 | for (i in 0..99999999) if (selfDescribing(i)) print("$i ") 22 | println() 23 | } -------------------------------------------------------------------------------- /src/tasks/Semiprime.kt: -------------------------------------------------------------------------------- 1 | package `semiprime` 2 | 3 | // version 1.1.2 4 | 5 | fun isSemiPrime(n: Int): Boolean { 6 | var nf = 0 7 | var nn = n 8 | for (i in 2..nn) 9 | while (nn % i == 0) { 10 | if (nf == 2) return false 11 | nf++ 12 | nn /= i 13 | } 14 | return nf == 2 15 | } 16 | 17 | fun main(args: Array) { 18 | for (v in 1675..1680) 19 | println("$v ${if (isSemiPrime(v)) "is" else "isn't"} semi-prime") 20 | } -------------------------------------------------------------------------------- /src/tasks/Semordnilap.kt: -------------------------------------------------------------------------------- 1 | package `semordnilap` 2 | 3 | // version 1.2.0 4 | 5 | import java.io.File 6 | 7 | fun main(args: Array) { 8 | val words = File("unixdict.txt").readLines().toSet() 9 | val pairs = words.map { Pair(it, it.reversed()) } 10 | .filter { it.first < it.second && it.second in words } // avoid dupes+palindromes, find matches 11 | println("Found ${pairs.size} semordnilap pairs") 12 | println(pairs.take(5)) 13 | } -------------------------------------------------------------------------------- /src/tasks/Sequence_of_non-squares.kt: -------------------------------------------------------------------------------- 1 | package `sequence_of_non_squares` 2 | 3 | // version 1.1 4 | 5 | fun f(n: Int) = n + Math.floor(0.5 + Math.sqrt(n.toDouble())).toInt() 6 | 7 | fun main(args: Array) { 8 | println(" n f") 9 | val squares = mutableListOf() 10 | for (n in 1 until 1000000) { 11 | val v1 = f(n) 12 | val v2 = Math.sqrt(v1.toDouble()).toInt() 13 | if (v1 == v2 * v2) squares.add(n) 14 | if (n < 23) println("${"%2d".format(n)} : $v1") 15 | } 16 | println() 17 | if (squares.size == 0) println("There are no squares for n less than one million") 18 | else println("Squares are generated for the following values of n: $squares") 19 | } -------------------------------------------------------------------------------- /src/tasks/Sequence_of_primes_by_Trial_Division.kt: -------------------------------------------------------------------------------- 1 | package `sequence_of_primes_by_trial_division` 2 | 3 | // version 1.0.6 4 | 5 | fun isPrime(n: Int): Boolean { 6 | if (n < 2) return false 7 | if (n % 2 == 0) return n == 2 8 | if (n % 3 == 0) return n == 3 9 | var d : Int = 5 10 | while (d * d <= n) { 11 | if (n % d == 0) return false 12 | d += 2 13 | if (n % d == 0) return false 14 | d += 4 15 | } 16 | return true 17 | } 18 | 19 | fun main(args: Array) { 20 | // print all primes below 2000 say 21 | var count = 1 22 | print(" 2") 23 | for (i in 3..1999 step 2) 24 | if (isPrime(i)) { 25 | count++ 26 | print("%5d".format(i)) 27 | if (count % 15 == 0) println() 28 | } 29 | } -------------------------------------------------------------------------------- /src/tasks/Shoelace_formula_for_polygonal_area.kt: -------------------------------------------------------------------------------- 1 | package `shoelace_formula_for_polygonal_area` 2 | 3 | // version 1.1.3 4 | 5 | class Point(val x: Int, val y: Int) { 6 | override fun toString() = "($x, $y)" 7 | } 8 | 9 | fun shoelaceArea(v: List): Double { 10 | val n = v.size 11 | var a = 0.0 12 | for (i in 0 until n - 1) { 13 | a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y 14 | } 15 | return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0 16 | } 17 | 18 | fun main(args: Array) { 19 | val v = listOf( 20 | Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6) 21 | ) 22 | val area = shoelaceArea(v) 23 | println("Given a polygon with vertices at $v,") 24 | println("its area is $area") 25 | } -------------------------------------------------------------------------------- /src/tasks/Short-circuit_evaluation.kt: -------------------------------------------------------------------------------- 1 | package `short_circuit_evaluation` 2 | 3 | // version 1.1.2 4 | 5 | fun a(v: Boolean): Boolean { 6 | println("'a' called") 7 | return v 8 | } 9 | 10 | fun b(v: Boolean): Boolean { 11 | println("'b' called") 12 | return v 13 | } 14 | 15 | fun main(args: Array){ 16 | val pairs = arrayOf(Pair(true, true), Pair(true, false), Pair(false, true), Pair(false, false)) 17 | for (pair in pairs) { 18 | val x = a(pair.first) && b(pair.second) 19 | println("${pair.first} && ${pair.second} = $x") 20 | val y = a(pair.first) || b(pair.second) 21 | println("${pair.first} || ${pair.second} = $y") 22 | println() 23 | } 24 | } -------------------------------------------------------------------------------- /src/tasks/Show_Ascii_table.kt: -------------------------------------------------------------------------------- 1 | package `show_ascii_table` 2 | 3 | // Version 1.2.60 4 | 5 | fun main(args: Array) { 6 | for (i in 0..15) { 7 | for (j in 32 + i..127 step 16) { 8 | val k = when (j) { 9 | 32 -> "Spc" 10 | 127 -> "Del" 11 | else -> j.toChar().toString() 12 | } 13 | System.out.printf("%3d : %-3s ", j, k) 14 | } 15 | println() 16 | } 17 | } -------------------------------------------------------------------------------- /src/tasks/Show_the_epoch.kt: -------------------------------------------------------------------------------- 1 | package `show_the_epoch` 2 | 3 | // version 1.1.2 4 | 5 | import java.util.Date 6 | import java.util.TimeZone 7 | import java.text.DateFormat 8 | 9 | fun main( args: Array) { 10 | val epoch = Date(0) 11 | val format = DateFormat.getDateTimeInstance() 12 | format.timeZone = TimeZone.getTimeZone("UTC") 13 | println(format.format(epoch)) 14 | } -------------------------------------------------------------------------------- /src/tasks/Sierpinski_carpet.kt: -------------------------------------------------------------------------------- 1 | package `sierpinski_carpet` 2 | 3 | // version 1.1.2 4 | 5 | fun inCarpet(x: Int, y: Int): Boolean { 6 | var xx = x 7 | var yy = y 8 | while (xx != 0 && yy != 0) { 9 | if (xx % 3 == 1 && yy % 3 == 1) return false 10 | xx /= 3 11 | yy /= 3 12 | } 13 | return true 14 | } 15 | 16 | fun carpet(n: Int) { 17 | val power = Math.pow(3.0, n.toDouble()).toInt() 18 | for(i in 0 until power) { 19 | for(j in 0 until power) print(if (inCarpet(i, j)) "*" else " ") 20 | println() 21 | } 22 | } 23 | 24 | fun main(args: Array) = carpet(3) -------------------------------------------------------------------------------- /src/tasks/Sierpinski_triangle.kt: -------------------------------------------------------------------------------- 1 | package `sierpinski_triangle` 2 | 3 | // version 1.1.2 4 | 5 | const val ORDER = 4 6 | const val SIZE = 1 shl ORDER 7 | 8 | fun main(args: Array) { 9 | for (y in SIZE - 1 downTo 0) { 10 | for (i in 0 until y) print(" ") 11 | for (x in 0 until SIZE - y) print(if ((x and y) != 0) " " else "* ") 12 | println() 13 | } 14 | } -------------------------------------------------------------------------------- /src/tasks/Sieve_of_Eratosthenes-2.kt: -------------------------------------------------------------------------------- 1 | package `sieve_of_eratosthenes_2` 2 | 3 | fun primesOdds(rng: Int): Iterable { 4 | val topi = (rng - 3) / 2 //convert to nearest index 5 | val size = topi / 32 + 1 //word size to include index 6 | val sqrtndx = (Math.sqrt(rng.toDouble()).toInt() - 3) / 2 7 | val cmpsts = IntArray(size) 8 | fun is_p(i: Int) = cmpsts[i shr 5] and (1 shl (i and 0x1F)) == 0 9 | fun cull(i: Int) { cmpsts[i shr 5] = cmpsts[i shr 5] or (1 shl (i and 0x1F)) } 10 | fun cullp(p: Int) = (((p * p - 3) / 2 .. topi).step(p)).forEach { cull(it) } 11 | (0 .. sqrtndx).filter { is_p(it) }.forEach { cullp(it + it + 3) } 12 | fun i2p(i: Int) = if (i < 0) 2 else i + i + 3 13 | val orng = (-1 .. topi).filter { it < 0 || is_p(it) }.map { i2p(it) } 14 | return Iterable { -> orng.iterator() } 15 | } -------------------------------------------------------------------------------- /src/tasks/Simple_windowed_application-1.kt: -------------------------------------------------------------------------------- 1 | package `simple_windowed_application_1` 2 | 3 | import tornadofx.* 4 | 5 | class ClicksView: View("Clicks example") { 6 | var clicks = 0 7 | override val root = vbox(5) { 8 | var label1 = label("There have been no clicks yet") 9 | button("Click me!") { action { label1.text = "Clicked ${++clicks} times." } } 10 | } 11 | } 12 | 13 | class ClicksApp: App(ClicksView::class) 14 | 15 | fun main(args: Array) = launch(args) -------------------------------------------------------------------------------- /src/tasks/Simulate_input-Keyboard.kt: -------------------------------------------------------------------------------- 1 | package `simulate_input_keyboard` 2 | 3 | // version 1.1.2 4 | 5 | import java.awt.Robot 6 | import java.awt.event.KeyEvent 7 | 8 | fun sendChars(s: String, pressReturn: Boolean = true) { 9 | val r = Robot() 10 | for (c in s) { 11 | val ci = c.toUpperCase().toInt() 12 | r.keyPress(ci) 13 | r.keyRelease(ci) 14 | } 15 | if (pressReturn) { 16 | r.keyPress(KeyEvent.VK_ENTER) 17 | r.keyRelease(KeyEvent.VK_ENTER) 18 | } 19 | } 20 | 21 | fun main(args: Array) { 22 | sendChars("dir") // runs 'dir' command 23 | } -------------------------------------------------------------------------------- /src/tasks/Simulate_input-Mouse.kt: -------------------------------------------------------------------------------- 1 | package `simulate_input_mouse` 2 | 3 | // version 1.1.2 4 | 5 | import java.awt.Robot 6 | import java.awt.event.InputEvent 7 | 8 | fun sendClick(buttons: Int) { 9 | val r = Robot() 10 | r.mousePress(buttons) 11 | r.mouseRelease(buttons) 12 | } 13 | 14 | fun main(args: Array) { 15 | sendClick(InputEvent.BUTTON3_DOWN_MASK) // simulate a click of the mouse's right button 16 | } -------------------------------------------------------------------------------- /src/tasks/Sine_wave-1.kt: -------------------------------------------------------------------------------- 1 | package `sine_wave_1` 2 | 3 | // Version 1.2.41 4 | 5 | fun main(args:Array) { 6 | val synthType = "sine" 7 | val duration = "5" 8 | val frequency = "440" 9 | val pb = ProcessBuilder("play", "-n", "synth", duration, synthType, frequency) 10 | pb.directory(null) 11 | val proc = pb.start() 12 | proc.waitFor() 13 | } -------------------------------------------------------------------------------- /src/tasks/Singleton.kt: -------------------------------------------------------------------------------- 1 | package `singleton` 2 | 3 | // version 1.1.2 4 | 5 | object Singleton { 6 | fun speak() = println("I am a singleton") 7 | } 8 | 9 | fun main(args: Array) { 10 | Singleton.speak() 11 | } -------------------------------------------------------------------------------- /src/tasks/Singly-linked_list-Element_definition.kt: -------------------------------------------------------------------------------- 1 | package `singly_linked_list_element_definition` 2 | 3 | // version 1.1.2 4 | 5 | class Node(var data: T, var next: Node? = null) { 6 | override fun toString(): String { 7 | val sb = StringBuilder(this.data.toString()) 8 | var node = this.next 9 | while (node != null) { 10 | sb.append(" -> ", node.data.toString()) 11 | node = node.next 12 | } 13 | return sb.toString() 14 | } 15 | } 16 | 17 | fun main(args: Array) { 18 | val n = Node(1, Node(2, Node(3))) 19 | println(n) 20 | } -------------------------------------------------------------------------------- /src/tasks/Singly-linked_list-Traversal.kt: -------------------------------------------------------------------------------- 1 | package `singly_linked_list_traversal` 2 | 3 | fun main(args: Array) { 4 | val list = IntRange(1, 50).toList() 5 | 6 | // classic traversal: 7 | for (i in list) { print("%4d ".format(i)); if (i % 10 == 0) println() } 8 | 9 | // list iterator: 10 | list.asReversed().forEach { print("%4d ".format(it)); if (it % 10 == 1) println() } 11 | } -------------------------------------------------------------------------------- /src/tasks/Sleep.kt: -------------------------------------------------------------------------------- 1 | package `sleep` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | print("Enter number of milliseconds to sleep: ") 7 | val ms = readLine()!!.toLong() 8 | println("Sleeping...") 9 | Thread.sleep(ms) 10 | println("Awake!") 11 | } -------------------------------------------------------------------------------- /src/tasks/Sockets.kt: -------------------------------------------------------------------------------- 1 | package `sockets` 2 | 3 | // version 1.2.21 4 | 5 | import java.net.Socket 6 | 7 | fun main(args: Array) { 8 | val sock = Socket("localhost", 256) 9 | sock.use { 10 | it.outputStream.write("hello socket world".toByteArray()) 11 | } 12 | } -------------------------------------------------------------------------------- /src/tasks/Sort_an_array_of_composite_structures.kt: -------------------------------------------------------------------------------- 1 | package `sort_an_array_of_composite_structures` 2 | 3 | // version 1.1 4 | 5 | data class Employee(val name: String, var category: String) : Comparable { 6 | override fun compareTo(other: Employee) = this.name.compareTo(other.name) 7 | } 8 | 9 | fun main(args: Array) { 10 | val employees = arrayOf( 11 | Employee("David", "Manager"), 12 | Employee("Alice", "Sales"), 13 | Employee("Joanna", "Director"), 14 | Employee("Henry", "Admin"), 15 | Employee("Tim", "Sales"), 16 | Employee("Juan", "Admin") 17 | ) 18 | employees.sort() 19 | for ((name, category) in employees) println("${name.padEnd(6)} : $category") 20 | } -------------------------------------------------------------------------------- /src/tasks/Sort_an_integer_array.kt: -------------------------------------------------------------------------------- 1 | package `sort_an_integer_array` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | val ints = intArrayOf(6, 2, 7, 8, 3, 1, 10, 5, 4, 9) 7 | ints.sort() 8 | println(ints.joinToString(prefix = "[", postfix = "]")) 9 | } -------------------------------------------------------------------------------- /src/tasks/Sort_disjoint_sublist.kt: -------------------------------------------------------------------------------- 1 | package `sort_disjoint_sublist` 2 | 3 | // version 1.1.51 4 | 5 | /* in place sort */ 6 | fun IntArray.sortDisjoint(indices: Set) { 7 | val sortedSubset = this.filterIndexed { index, _ -> index in indices }.sorted() 8 | if (sortedSubset.size < indices.size) 9 | throw IllegalArgumentException("Argument set contains out of range indices") 10 | indices.sorted().forEachIndexed { index, value -> this[value] = sortedSubset[index] } 11 | } 12 | 13 | fun main(args: Array) { 14 | val values = intArrayOf(7, 6, 5, 4, 3, 2, 1, 0) 15 | val indices = setOf(6, 1, 7) 16 | println("Original array : ${values.asList()} sorted on indices $indices") 17 | values.sortDisjoint(indices) 18 | println("Sorted array : ${values.asList()}") 19 | } -------------------------------------------------------------------------------- /src/tasks/Sort_numbers_lexicographically.kt: -------------------------------------------------------------------------------- 1 | package `sort_numbers_lexicographically` 2 | 3 | // Version 1.2.51 4 | 5 | fun lexOrder(n: Int): List { 6 | var first = 1 7 | var last = n 8 | if (n < 1) { 9 | first = n 10 | last = 1 11 | } 12 | return (first..last).map { it.toString() }.sorted().map { it.toInt() } 13 | } 14 | 15 | fun main(args: Array) { 16 | println("In lexicographical order:\n") 17 | for (n in listOf(0, 5, 13, 21, -22)) { 18 | println("${"%3d".format(n)}: ${lexOrder(n)}") 19 | } 20 | } -------------------------------------------------------------------------------- /src/tasks/Sort_stability.kt: -------------------------------------------------------------------------------- 1 | package `sort_stability` 2 | 3 | // version 1.1.51 4 | 5 | fun main(args: Array) { 6 | val cities = listOf("UK London", "US New York", "US Birmingham", "UK Birmingham") 7 | println("Original : $cities") 8 | // sort by country 9 | println("By country : ${cities.sortedBy { it.take(2) } }") 10 | // sort by city 11 | println("By city : ${cities.sortedBy { it.drop(3) } }") 12 | } -------------------------------------------------------------------------------- /src/tasks/Sort_using_a_custom_comparator.kt: -------------------------------------------------------------------------------- 1 | package `sort_using_a_custom_comparator` 2 | 3 | import java.util.Arrays 4 | 5 | fun main(args: Array) { 6 | val strings = arrayOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted") 7 | 8 | fun printArray(message: String, array: Array) = with(array) { 9 | print("$message [") 10 | forEachIndexed { index, string -> 11 | print(if (index == lastIndex) string else "$string, ") 12 | } 13 | println("]") 14 | } 15 | 16 | printArray("Unsorted:", strings) 17 | 18 | Arrays.sort(strings) { first, second -> 19 | val lengthDifference = second.length - first.length 20 | if (lengthDifference == 0) first.compareTo(second, true) else lengthDifference 21 | } 22 | 23 | printArray("Sorted:", strings) 24 | } -------------------------------------------------------------------------------- /src/tasks/Sorting_algorithms-Bubble_sort.kt: -------------------------------------------------------------------------------- 1 | package `sorting_algorithms_bubble_sort` 2 | 3 | import java.util.Comparator 4 | 5 | fun bubbleSort(a: Array, c: Comparator) { 6 | var changed: Boolean 7 | do { 8 | changed = false 9 | for (i in 0..a.size - 2) { 10 | if (c.compare(a[i], a[i + 1]) > 0) { 11 | val tmp = a[i] 12 | a[i] = a[i + 1] 13 | a[i + 1] = tmp 14 | changed = true 15 | } 16 | } 17 | } while (changed) 18 | } -------------------------------------------------------------------------------- /src/tasks/Sorting_algorithms-Counting_sort.kt: -------------------------------------------------------------------------------- 1 | package `sorting_algorithms_counting_sort` 2 | 3 | // version 1.1.0 4 | 5 | fun countingSort(array: IntArray) { 6 | if (array.isEmpty()) return 7 | val min = array.min()!! 8 | val max = array.max()!! 9 | val count = IntArray(max - min + 1) // all elements zero by default 10 | for (number in array) count[number - min]++ 11 | var z = 0 12 | for (i in min..max) 13 | while (count[i - min] > 0) { 14 | array[z++] = i 15 | count[i - min]-- 16 | } 17 | } 18 | 19 | fun main(args: Array) { 20 | val array = intArrayOf(4, 65, 2, -31, 0, 99, 2, 83, 782, 1) 21 | println("Original : ${array.asList()}") 22 | countingSort(array) 23 | println("Sorted : ${array.asList()}") 24 | } -------------------------------------------------------------------------------- /src/tasks/Sorting_algorithms-Quicksort-1.kt: -------------------------------------------------------------------------------- 1 | package `sorting_algorithms_quicksort_1` 2 | 3 | fun > quicksort(list: List): List { 4 | if (list.isEmpty()) return emptyList() 5 | 6 | val head = list.first() 7 | val tail = list.takeLast(list.size - 1) 8 | 9 | val (less, high) = tail.partition { it < head } 10 | 11 | return less + head + high 12 | } 13 | 14 | fun main(args: Array) { 15 | val nums = listOf(9, 7, 9, 8, 1, 2, 3, 4, 1, 9, 8, 9, 2, 4, 2, 4, 6, 3) 16 | println(quicksort(nums)) 17 | } -------------------------------------------------------------------------------- /src/tasks/Sorting_algorithms-Quicksort.kt: -------------------------------------------------------------------------------- 1 | package `sorting_algorithms_quicksort` 2 | 3 | import java.util.* 4 | import java.util.Comparator 5 | 6 | fun quickSort(a: List, c: Comparator): ArrayList { 7 | if (a.isEmpty()) return ArrayList(a) 8 | 9 | val boxes = Array(3, { ArrayList() }) 10 | fun normalise(i: Int) = i / Math.max(1, Math.abs(i)) 11 | a.forEach { boxes[normalise(c.compare(it, a[0])) + 1].add(it) } 12 | arrayOf(0, 2).forEach { boxes[it] = quickSort(boxes[it], c) } 13 | return boxes.flatMapTo(ArrayList()) { it } 14 | } -------------------------------------------------------------------------------- /src/tasks/Sorting_algorithms-Sleep_sort.kt: -------------------------------------------------------------------------------- 1 | package `sorting_algorithms_sleep_sort` 2 | 3 | // version 1.1.51 4 | 5 | import kotlin.concurrent.thread 6 | 7 | fun sleepSort(list: List, interval: Long) { 8 | print("Sorted : ") 9 | for (i in list) { 10 | thread { 11 | Thread.sleep(i * interval) 12 | print("$i ") 13 | } 14 | } 15 | thread { // print a new line after displaying sorted list 16 | Thread.sleep ((1 + list.max()!!) * interval) 17 | println() 18 | } 19 | } 20 | 21 | fun main(args: Array) { 22 | val list = args.map { it.toInt() }.filter { it >= 0 } // ignore negative integers 23 | println("Unsorted: ${list.joinToString(" ")}") 24 | sleepSort(list, 50) 25 | } -------------------------------------------------------------------------------- /src/tasks/Sorting_algorithms-Stooge_sort.kt: -------------------------------------------------------------------------------- 1 | package `sorting_algorithms_stooge_sort` 2 | 3 | // version 1.1.0 4 | 5 | fun stoogeSort(a: IntArray, i: Int, j: Int) { 6 | if (a[j] < a[i]) { 7 | val temp = a[j] 8 | a[j] = a[i] 9 | a[i] = temp 10 | } 11 | if (j - i > 1) { 12 | val t = (j - i + 1) / 3 13 | stoogeSort(a, i, j - t) 14 | stoogeSort(a, i + t, j) 15 | stoogeSort(a, i, j - t) 16 | } 17 | } 18 | 19 | fun main(args: Array) { 20 | val a = intArrayOf(100, 2, 56, 200, -52, 3, 99, 33, 177, -199) 21 | println("Original : ${a.asList()}") 22 | stoogeSort(a, 0, a.size - 1) 23 | println("Sorted : ${a.asList()}") 24 | } -------------------------------------------------------------------------------- /src/tasks/Split_a_character_string_based_on_change_of_character.kt: -------------------------------------------------------------------------------- 1 | package `split_a_character_string_based_on_change_of_character` 2 | 3 | // version 1.0.6 4 | 5 | fun splitOnChange(s: String): String { 6 | if (s.length < 2) return s 7 | var t = s.take(1) 8 | for (i in 1 until s.length) 9 | if (t.last() == s[i]) t += s[i] 10 | else t += ", " + s[i] 11 | return t 12 | } 13 | 14 | fun main(args: Array) { 15 | val s = """gHHH5YY++///\""" 16 | println(splitOnChange(s)) 17 | } -------------------------------------------------------------------------------- /src/tasks/Square_but_not_cube.kt: -------------------------------------------------------------------------------- 1 | package `square_but_not_cube` 2 | 3 | // Version 1.2.60 4 | 5 | fun main(args: Array) { 6 | var n = 1 7 | var count = 0 8 | while (count < 30) { 9 | val sq = n * n 10 | val cr = Math.cbrt(sq.toDouble()).toInt() 11 | if (cr * cr * cr != sq) { 12 | count++ 13 | println(sq) 14 | } 15 | else { 16 | println("$sq is square and cube") 17 | } 18 | n++ 19 | } 20 | } -------------------------------------------------------------------------------- /src/tasks/Stack_traces.kt: -------------------------------------------------------------------------------- 1 | package `stack_traces` 2 | 3 | // version 1.1.2 (stacktrace.kt which compiles to StacktraceKt.class) 4 | 5 | fun myFunc() { 6 | println(Throwable().stackTrace.joinToString("\n")) 7 | } 8 | 9 | fun main(args:Array) { 10 | myFunc() 11 | println("\nContinuing ... ") 12 | } -------------------------------------------------------------------------------- /src/tasks/Stair-climbing_puzzle.kt: -------------------------------------------------------------------------------- 1 | package `stair_climbing_puzzle` 2 | 3 | // version 1.2.0 4 | 5 | import java.util.Random 6 | 7 | val rand = Random(6321L) // generates short repeatable sequence 8 | var position = 0 9 | 10 | fun step(): Boolean { 11 | val r = rand.nextBoolean() 12 | if (r) 13 | println("Climbed up to ${++position}") 14 | else 15 | println("Fell down to ${--position}") 16 | return r 17 | } 18 | 19 | fun stepUp() { 20 | while (!step()) stepUp() 21 | } 22 | 23 | fun main(args: Array) { 24 | stepUp() 25 | } -------------------------------------------------------------------------------- /src/tasks/String_append.kt: -------------------------------------------------------------------------------- 1 | package `string_append` 2 | 3 | fun main(args: Array) { 4 | var s = "a" 5 | s += "b" 6 | s += "c" 7 | println(s) 8 | println("a" + "b" + "c") 9 | val a = "a" 10 | val b = "b" 11 | val c = "c" 12 | println("$a$b$c") 13 | } -------------------------------------------------------------------------------- /src/tasks/String_case.kt: -------------------------------------------------------------------------------- 1 | package `string_case` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | val s = "alphaBETA" 7 | println(s.toUpperCase()) 8 | println(s.toLowerCase()) 9 | println(s.capitalize()) 10 | println(s.decapitalize()) 11 | } -------------------------------------------------------------------------------- /src/tasks/String_concatenation.kt: -------------------------------------------------------------------------------- 1 | package `string_concatenation` 2 | 3 | fun main(args: Array) { 4 | val s1 = "James" 5 | val s2 = "Bond" 6 | println(s1) 7 | println(s2) 8 | val s3 = s1 + " " + s2 9 | println(s3) 10 | } -------------------------------------------------------------------------------- /src/tasks/String_interpolation_(included).kt: -------------------------------------------------------------------------------- 1 | package `string_interpolation_(included)` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | val s = "little" 7 | // String interpolation using a simple variable 8 | println("Mary had a $s lamb") 9 | 10 | // String interpolation using an expression (need to wrap it in braces) 11 | println("Mary had a ${s.toUpperCase()} lamb") 12 | 13 | // However if a simple variable is immediately followed by a letter, digit or underscore 14 | // it must be treated as an expression 15 | println("Mary had a ${s}r lamb") // not $sr 16 | } -------------------------------------------------------------------------------- /src/tasks/String_length.kt: -------------------------------------------------------------------------------- 1 | package `string_length` 2 | 3 | // version 1.0.6 4 | fun main(args: Array) { 5 | val s = "José" 6 | println("The char length is ${s.length}") 7 | println("The byte length is ${Character.BYTES * s.length}") 8 | } -------------------------------------------------------------------------------- /src/tasks/String_matching.kt: -------------------------------------------------------------------------------- 1 | package `string_matching` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | val s1 = "abracadabra" 7 | val s2 = "abra" 8 | println("$s1 begins with $s2 : ${s1.startsWith(s2)}") 9 | println("$s1 ends with $s2 : ${s1.endsWith(s2)}") 10 | val b = s2 in s1 11 | print("$s1 contains $s2 : $b") 12 | if (b) println(" at locations ${s1.indexOf(s2) + 1} and ${s1.lastIndexOf(s2) + 1}") 13 | else println() 14 | } -------------------------------------------------------------------------------- /src/tasks/String_prepend.kt: -------------------------------------------------------------------------------- 1 | package `string_prepend` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | var s = "Obama" 7 | s = "Barack " + s 8 | println(s) 9 | 10 | // It's also possible to use this standard library function 11 | // though this is not what it's really intended for 12 | var t = "Trump" 13 | t = t.prependIndent("Donald ") 14 | println(t) 15 | } -------------------------------------------------------------------------------- /src/tasks/Strip_a_set_of_characters_from_a_string.kt: -------------------------------------------------------------------------------- 1 | package `strip_a_set_of_characters_from_a_string` 2 | 3 | // version 1.0.6 4 | 5 | fun stripChars(s: String, r: String) = s.replace(Regex("[$r]"), "") 6 | 7 | fun main(args: Array) { 8 | println(stripChars("She was a soul stripper. She took my heart!", "aei")) 9 | } -------------------------------------------------------------------------------- /src/tasks/Strip_comments_from_a_string.kt: -------------------------------------------------------------------------------- 1 | package `strip_comments_from_a_string` 2 | 3 | // version 1.0.6 4 | 5 | val r = Regex("""(/\*.*\*/|//.*$)""") 6 | 7 | fun stripComments(s: String) = s.replace(r, "").trim() 8 | 9 | fun main(args: Array) { 10 | val strings = arrayOf( 11 | "apples, pears // and bananas", 12 | " apples, pears /* and bananas */", 13 | "/* oranges */ apples // pears and bananas ", 14 | " \toranges /*apples/*, pears*/*/and bananas" 15 | ) 16 | for (string in strings) println(stripComments(string)) 17 | } -------------------------------------------------------------------------------- /src/tasks/Strip_whitespace_from_a_string-Top_and_tail.kt: -------------------------------------------------------------------------------- 1 | package `strip_whitespace_from_a_string_top_and_tail` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | val s = " \tRosetta Code \r\n" 7 | println("Untrimmed => $s") 8 | println("Left Trimmed => ${s.trimStart()}") 9 | println("Right Trimmed => ${s.trimEnd()}") 10 | println("Fully Trimmed => ${s.trim()}") 11 | } -------------------------------------------------------------------------------- /src/tasks/Substring-Top_and_tail.kt: -------------------------------------------------------------------------------- 1 | package `substring_top_and_tail` 2 | 3 | // version 1.0.6 4 | fun main(args: Array) { 5 | val s = "Rosetta" 6 | println(s.drop(1)) 7 | println(s.dropLast(1)) 8 | println(s.drop(1).dropLast(1)) 9 | } -------------------------------------------------------------------------------- /src/tasks/Substring.kt: -------------------------------------------------------------------------------- 1 | package `substring` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | val s = "0123456789" 7 | val n = 3 8 | val m = 4 9 | val c = '5' 10 | val z = "12" 11 | var i: Int 12 | println(s.substring(n, n + m)) 13 | println(s.substring(n)) 14 | println(s.dropLast(1)) 15 | i = s.indexOf(c) 16 | println(s.substring(i, i + m)) 17 | i = s.indexOf(z) 18 | println(s.substring(i, i + m)) 19 | } -------------------------------------------------------------------------------- /src/tasks/Sum_and_product_of_an_array.kt: -------------------------------------------------------------------------------- 1 | package `sum_and_product_of_an_array` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args: Array) { 6 | val a = intArrayOf(1, 5, 8, 11, 15) 7 | println("Array contains : ${a.contentToString()}") 8 | val sum = a.sum() 9 | println("Sum is $sum") 10 | val product = a.fold(1) { acc, i -> acc * i } 11 | println("Product is $product") 12 | } -------------------------------------------------------------------------------- /src/tasks/Sum_of_a_series.kt: -------------------------------------------------------------------------------- 1 | package `sum_of_a_series` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | val n = 1000 7 | val sum = (1..n).sumByDouble { 1.0 / (it * it) } 8 | println("Actual sum is $sum") 9 | println("zeta(2) is ${Math.PI * Math.PI / 6.0}") 10 | } -------------------------------------------------------------------------------- /src/tasks/Sum_of_squares.kt: -------------------------------------------------------------------------------- 1 | package `sum_of_squares` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | val vector = doubleArrayOf(3.1, 1.0, 4.0, 1.0, 5.0, 9.0) 7 | println(vector.map { it * it }.sum()) 8 | val vector2 = doubleArrayOf() // empty vector 9 | println(vector2.map { it * it }.sum()) 10 | } -------------------------------------------------------------------------------- /src/tasks/Symmetric_difference.kt: -------------------------------------------------------------------------------- 1 | package `symmetric_difference` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args: Array) { 6 | val a = setOf("John", "Bob", "Mary", "Serena") 7 | val b = setOf("Jim", "Mary", "John", "Bob") 8 | println("A = $a") 9 | println("B = $b") 10 | val c = a - b 11 | println("A \\ B = $c") 12 | val d = b - a 13 | println("B \\ A = $d") 14 | val e = c.union(d) 15 | println("A Δ B = $e") 16 | } -------------------------------------------------------------------------------- /src/tasks/System_time.kt: -------------------------------------------------------------------------------- 1 | package `system_time` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | println("%tc".format(System.currentTimeMillis())) 7 | } -------------------------------------------------------------------------------- /src/tasks/Take_notes_on_the_command_line.kt: -------------------------------------------------------------------------------- 1 | package `take_notes_on_the_command_line` 2 | 3 | // version 1.2.10 4 | 5 | import java.io.File 6 | import java.util.Date 7 | import java.text.SimpleDateFormat 8 | 9 | fun main(args: Array) { 10 | val f = File("NOTES.TXT") 11 | // create file if it doesn't exist already 12 | f.createNewFile() 13 | if (args.size == 0) { 14 | println(f.readText()) 15 | } 16 | else { 17 | val df = SimpleDateFormat("yyyy/MM/dd HH:mm:ss") 18 | val dt = df.format(Date()) 19 | val notes = "$dt\n\t${args.joinToString(" ")}\n" 20 | f.appendText(notes) 21 | } 22 | } -------------------------------------------------------------------------------- /src/tasks/Temperature_conversion.kt: -------------------------------------------------------------------------------- 1 | package `temperature_conversion` 2 | 3 | // version 1.1.2 4 | 5 | class Kelvin(val degrees: Double) { 6 | fun toCelsius() = degrees - 273.15 7 | 8 | fun toFahreneit() = (degrees - 273.15) * 1.8 + 32.0 9 | 10 | fun toRankine() = (degrees - 273.15) * 1.8 + 32.0 + 459.67 11 | } 12 | 13 | fun main(args: Array) { 14 | print("Enter the temperature in degrees Kelvin : ") 15 | val degrees = readLine()!!.toDouble() 16 | val k = Kelvin(degrees) 17 | val f = "% 1.2f" 18 | println() 19 | println("K ${f.format(k.degrees)}\n") 20 | println("C ${f.format(k.toCelsius())}\n") 21 | println("F ${f.format(k.toFahreneit())}\n") 22 | println("R ${f.format(k.toRankine())}") 23 | } -------------------------------------------------------------------------------- /src/tasks/Terminal_control-Clear_the_screen.kt: -------------------------------------------------------------------------------- 1 | package `terminal_control_clear_the_screen` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args: Array) { 6 | println("\u001Bc") // Esc + c 7 | } -------------------------------------------------------------------------------- /src/tasks/Terminal_control-Cursor_movement.kt: -------------------------------------------------------------------------------- 1 | package `terminal_control_cursor_movement` 2 | 3 | // version 1.1.2 4 | 5 | const val ESC = "\u001B" // escape code 6 | 7 | fun main(args: Array) { 8 | print("$ESC[2J") // clear terminal first 9 | print("$ESC[10;10H") // move cursor to (10, 10) say 10 | val aecs = arrayOf( 11 | "[1D", // left 12 | "[1C", // right 13 | "[1A", // up 14 | "[1B", // down 15 | "[9D", // line start 16 | "[H", // top left 17 | "[24;79H" // bottom right - assuming 80 x 24 terminal 18 | ) 19 | for (aec in aecs) { 20 | Thread.sleep(3000) // three second display between cursor movements 21 | print("$ESC$aec") 22 | } 23 | Thread.sleep(3000) 24 | println() 25 | } -------------------------------------------------------------------------------- /src/tasks/Terminal_control-Cursor_positioning.kt: -------------------------------------------------------------------------------- 1 | package `terminal_control_cursor_positioning` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args: Array) { 6 | print("\u001Bc") // clear screen first 7 | println("\u001B[6;3HHello") 8 | } -------------------------------------------------------------------------------- /src/tasks/Terminal_control-Dimensions.kt: -------------------------------------------------------------------------------- 1 | package `terminal_control_dimensions` 2 | 3 | // version 1.1.2 4 | 5 | /* 6 | I needed to execute the terminal command: 'export COLUMNS LINES' 7 | before running this program for it to work (returned 'null' sizes otherwise). 8 | */ 9 | 10 | fun main(args: Array) { 11 | val lines = System.getenv("LINES") 12 | val columns = System.getenv("COLUMNS") 13 | println("Lines = $lines") 14 | println("Columns = $columns") 15 | } -------------------------------------------------------------------------------- /src/tasks/Terminal_control-Display_an_extended_character.kt: -------------------------------------------------------------------------------- 1 | package `terminal_control_display_an_extended_character` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args:Array) = println("£") -------------------------------------------------------------------------------- /src/tasks/Terminal_control-Hiding_the_cursor.kt: -------------------------------------------------------------------------------- 1 | package `terminal_control_hiding_the_cursor` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args: Array) { 6 | print("\u001B[?25l") // hide cursor 7 | Thread.sleep(2000) // wait 2 seconds before redisplaying cursor 8 | print("\u001B[?25h") // display cursor 9 | Thread.sleep(2000) // wait 2 more seconds before exiting 10 | } -------------------------------------------------------------------------------- /src/tasks/Terminal_control-Inverse_video.kt: -------------------------------------------------------------------------------- 1 | package `terminal_control_inverse_video` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args: Array) { 6 | println("\u001B[7mInverse\u001B[m Normal") 7 | } -------------------------------------------------------------------------------- /src/tasks/Terminal_control-Preserve_screen.kt: -------------------------------------------------------------------------------- 1 | package `terminal_control_preserve_screen` 2 | 3 | // version 1.1.2 4 | 5 | const val ESC = "\u001B" 6 | 7 | fun main(args: Array) { 8 | print("$ESC[?1049h$ESC[H") 9 | println("Alternate screen buffer") 10 | for(i in 5 downTo 1) { 11 | print("\rGoing back in $i second${if (i != 1) "s" else ""}...") 12 | Thread.sleep(1000) 13 | } 14 | print("$ESC[?1049l") 15 | } -------------------------------------------------------------------------------- /src/tasks/Terminal_control-Ringing_the_terminal_bell.kt: -------------------------------------------------------------------------------- 1 | package `terminal_control_ringing_the_terminal_bell` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args: Array) { 6 | println("\u0007") 7 | } -------------------------------------------------------------------------------- /src/tasks/Terminal_control-Unicode_output.kt: -------------------------------------------------------------------------------- 1 | package `terminal_control_unicode_output` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args: Array) { 6 | val supportsUnicode = "UTF" in System.getenv("LANG").toUpperCase() 7 | if (supportsUnicode) 8 | println("This terminal supports unicode and U+25b3 is : \u25b3") 9 | else 10 | println("This terminal does not support unicode") 11 | } -------------------------------------------------------------------------------- /src/tasks/Test_a_function.kt: -------------------------------------------------------------------------------- 1 | package `test_a_function` 2 | 3 | // version 1.1.3 4 | 5 | fun isPalindrome(s: String) = (s == s.reversed()) 6 | 7 | fun main(args: Array) { 8 | val testCases = listOf("racecar", "alice", "eertree", "david") 9 | for (testCase in testCases) { 10 | try { 11 | assert(isPalindrome(testCase)) { "$testCase is not a palindrome" } 12 | } 13 | catch (ae: AssertionError) { 14 | println(ae.message) 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /src/tasks/The_Name_Game.kt: -------------------------------------------------------------------------------- 1 | package `the_name_game` 2 | 3 | // version 1.2.31 4 | 5 | fun printVerse(name: String) { 6 | val x = name.toLowerCase().capitalize() 7 | val y = if (x[0] in "AEIOU") x.toLowerCase() else x.substring(1) 8 | var b = "b$y" 9 | var f = "f$y" 10 | var m = "m$y" 11 | when (x[0]) { 12 | 'B' -> b = "$y" 13 | 'F' -> f = "$y" 14 | 'M' -> m = "$y" 15 | else -> {} // no adjustment needed 16 | } 17 | println("$x, $x, bo-$b") 18 | println("Banana-fana fo-$f") 19 | println("Fee-fi-mo-$m") 20 | println("$x!\n") 21 | } 22 | 23 | fun main(args: Array) { 24 | listOf("Gary", "Earl", "Billy", "Felix", "Mary", "Steve").forEach { printVerse(it) } 25 | } -------------------------------------------------------------------------------- /src/tasks/Thue-Morse.kt: -------------------------------------------------------------------------------- 1 | package `thue_morse` 2 | 3 | // version 1.1.2 4 | fun thueMorse(n: Int): String { 5 | val sb0 = StringBuilder("0") 6 | val sb1 = StringBuilder("1") 7 | (0 until n).forEach { 8 | val tmp = sb0.toString() 9 | sb0.append(sb1) 10 | sb1.append(tmp) 11 | } 12 | return sb0.toString() 13 | } 14 | 15 | fun main(args: Array) { 16 | for (i in 0..6) println("$i : ${thueMorse(i)}") 17 | } -------------------------------------------------------------------------------- /src/tasks/Tokenize_a_string.kt: -------------------------------------------------------------------------------- 1 | package `tokenize_a_string` 2 | 3 | fun main(args: Array) { 4 | val input = "Hello,How,Are,You,Today" 5 | println(input.split(',').joinToString(".")) 6 | } -------------------------------------------------------------------------------- /src/tasks/Topic_variable.kt: -------------------------------------------------------------------------------- 1 | package `topic_variable` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args: Array) { 6 | 3.let { 7 | println(it) 8 | println(it * it) 9 | println(Math.sqrt(it.toDouble())) 10 | } 11 | } -------------------------------------------------------------------------------- /src/tasks/Towers_of_Hanoi.kt: -------------------------------------------------------------------------------- 1 | package `towers_of_hanoi` 2 | 3 | // version 1.1.0 4 | 5 | class Hanoi(disks: Int) { 6 | private var moves = 0 7 | 8 | init { 9 | println("Towers of Hanoi with $disks disks:\n") 10 | move(disks, 'L', 'C', 'R') 11 | println("\nCompleted in $moves moves\n") 12 | } 13 | 14 | private fun move(n: Int, from: Char, to: Char, via: Char) { 15 | if (n > 0) { 16 | move(n - 1, from, via, to) 17 | moves++ 18 | println("Move disk $n from $from to $to") 19 | move(n - 1, via, to, from) 20 | } 21 | } 22 | } 23 | 24 | fun main(args: Array) { 25 | Hanoi(3) 26 | Hanoi(4) 27 | } -------------------------------------------------------------------------------- /src/tasks/Truncate_a_file.kt: -------------------------------------------------------------------------------- 1 | package `truncate_a_file` 2 | 3 | // version 1.1.2 4 | 5 | import java.io.FileOutputStream 6 | import java.nio.channels.FileChannel 7 | 8 | fun truncateFile(fileName: String, newSize: Long) { 9 | var fc: FileChannel? = null 10 | try { 11 | fc = FileOutputStream(fileName, true).channel 12 | if (newSize >= fc.size()) 13 | println("Requested file size isn't less than existing size") 14 | else 15 | fc.truncate(newSize) 16 | } 17 | catch (ex: Exception) { 18 | println(ex.message) 19 | } 20 | finally { 21 | fc!!.close() 22 | } 23 | } 24 | 25 | fun main(args: Array) { 26 | truncateFile("test.txt", 10) 27 | } -------------------------------------------------------------------------------- /src/tasks/Type_detection.kt: -------------------------------------------------------------------------------- 1 | package `type_detection` 2 | 3 | // version 1.0.6 4 | fun showType(a: Any) = when (a) { 5 | is Int -> println("'$a' is an integer") 6 | is Double -> println("'$a' is a double") 7 | is Char -> println("'$a' is a character") 8 | else -> println("'$a' is some other type") 9 | } 10 | 11 | fun main(args: Array) { 12 | showType(5) 13 | showType(7.5) 14 | showType('d') 15 | showType(true) 16 | } -------------------------------------------------------------------------------- /src/tasks/URL_decoding.kt: -------------------------------------------------------------------------------- 1 | package `url_decoding` 2 | 3 | // version 1.1.2 4 | 5 | import java.net.URLDecoder 6 | 7 | fun main(args: Array) { 8 | val encoded = arrayOf("http%3A%2F%2Ffoo%20bar%2F", "google.com/search?q=%60Abdu%27l-Bah%C3%A1") 9 | for (e in encoded) println(URLDecoder.decode(e, "UTF-8")) 10 | } -------------------------------------------------------------------------------- /src/tasks/URL_encoding.kt: -------------------------------------------------------------------------------- 1 | package `url_encoding` 2 | 3 | // version 1.1.2 4 | 5 | import java.net.URLEncoder 6 | 7 | fun main(args: Array) { 8 | val url = "http://foo bar/" 9 | println(URLEncoder.encode(url, "utf-8")) // note: encodes space to + not %20 10 | } -------------------------------------------------------------------------------- /src/tasks/Unbias_a_random_generator.kt: -------------------------------------------------------------------------------- 1 | package `unbias_a_random_generator` 2 | 3 | // version 1.1.2 4 | 5 | fun biased(n: Int) = Math.random() < 1.0 / n 6 | 7 | fun unbiased(n: Int): Boolean { 8 | var a: Boolean 9 | var b: Boolean 10 | do { 11 | a = biased(n) 12 | b = biased(n) 13 | } 14 | while (a == b) 15 | return a 16 | } 17 | 18 | fun main(args: Array) { 19 | val m = 50_000 20 | val f = "%d: %2.2f%% %2.2f%%" 21 | for (n in 3..6) { 22 | var c1 = 0 23 | var c2 = 0 24 | for (i in 0 until m) { 25 | if (biased(n)) c1++ 26 | if (unbiased(n)) c2++ 27 | } 28 | println(f.format(n, 100.0 * c1 / m, 100.0 * c2 / m)) 29 | } 30 | } -------------------------------------------------------------------------------- /src/tasks/Unicode_strings.kt: -------------------------------------------------------------------------------- 1 | package `unicode_strings` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args: Array) { 6 | val åäö = "as⃝df̅ ♥♦♣♠ 頰" 7 | println(åäö) 8 | } -------------------------------------------------------------------------------- /src/tasks/Unicode_variable_names.kt: -------------------------------------------------------------------------------- 1 | package `unicode_variable_names` 2 | 3 | fun main(args: Array) { 4 | var Δ = 1 5 | Δ++ 6 | print(Δ) 7 | } -------------------------------------------------------------------------------- /src/tasks/Unix-ls.kt: -------------------------------------------------------------------------------- 1 | package `unix_ls` 2 | 3 | // Version 1.2.41 4 | 5 | import java.io.File 6 | 7 | fun ls(directory: String) { 8 | val d = File(directory) 9 | if (!d.isDirectory) { 10 | println("$directory is not a directory") 11 | return 12 | } 13 | d.listFiles().map { it.name } 14 | .sortedBy { it.toLowerCase() } // case insensitive 15 | .forEach { println(it) } 16 | } 17 | 18 | fun main(args: Array) { 19 | ls(".") // list files in current directory, say 20 | } -------------------------------------------------------------------------------- /src/tasks/User_input-Graphical.kt: -------------------------------------------------------------------------------- 1 | package `user_input_graphical` 2 | 3 | // version 1.1 4 | 5 | import javax.swing.JOptionPane 6 | 7 | fun main(args: Array) { 8 | do { 9 | val number = JOptionPane.showInputDialog("Enter 75000").toInt() 10 | } while (number != 75000) 11 | } -------------------------------------------------------------------------------- /src/tasks/User_input-Text.kt: -------------------------------------------------------------------------------- 1 | package `user_input_text` 2 | 3 | // version 1.1 4 | 5 | fun main(args: Array) { 6 | print("Enter a string : ") 7 | val s = readLine()!! 8 | println(s) 9 | do { 10 | print("Enter 75000 : ") 11 | val number = readLine()!!.toInt() 12 | } while (number != 75000) 13 | } -------------------------------------------------------------------------------- /src/tasks/Variable_size-Get.kt: -------------------------------------------------------------------------------- 1 | package `variable_size_get` 2 | 3 | // version 1.1.2 4 | 5 | fun main(args: Array) { 6 | /* sizes for variables of the primitive types (except Boolean which is JVM dependent) */ 7 | println("A Byte variable occupies: ${java.lang.Byte.SIZE / 8} byte") 8 | println("A Short variable occupies: ${java.lang.Short.SIZE / 8} bytes") 9 | println("An Int variable occupies: ${java.lang.Integer.SIZE / 8} bytes") 10 | println("A Long variable occupies: ${java.lang.Long.SIZE / 8} bytes") 11 | println("A Float variable occupies: ${java.lang.Float.SIZE / 8} bytes") 12 | println("A Double variable occupies: ${java.lang.Double.SIZE / 8} bytes") 13 | println("A Char variable occupies: ${java.lang.Character.SIZE / 8} bytes") 14 | } -------------------------------------------------------------------------------- /src/tasks/Variable_size-Set.kt: -------------------------------------------------------------------------------- 1 | package `variable_size_set` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | /* ranges for variables of the primitive numeric types */ 7 | println("A Byte variable has a range of : ${Byte.MIN_VALUE} to ${Byte.MAX_VALUE}") 8 | println("A Short variable has a range of : ${Short.MIN_VALUE} to ${Short.MAX_VALUE}") 9 | println("An Int variable has a range of : ${Int.MIN_VALUE} to ${Int.MAX_VALUE}") 10 | println("A Long variable has a range of : ${Long.MIN_VALUE} to ${Long.MAX_VALUE}") 11 | println("A Float variable has a range of : ${Float.MIN_VALUE} to ${Float.MAX_VALUE}") 12 | println("A Double variable has a range of : ${Double.MIN_VALUE} to ${Double.MAX_VALUE}") 13 | } -------------------------------------------------------------------------------- /src/tasks/Variadic_function.kt: -------------------------------------------------------------------------------- 1 | package `variadic_function` 2 | 3 | // version 1.1 4 | 5 | fun variadic(vararg va: String) { 6 | for (v in va) println(v) 7 | } 8 | 9 | fun main(args: Array) { 10 | variadic("First", "Second", "Third") 11 | println("\nEnter four strings for the function to print:") 12 | val va = Array(4) { "" } 13 | for (i in 1..4) { 14 | print("String $i = ") 15 | va[i - 1] = readLine()!! 16 | } 17 | println() 18 | variadic(*va) 19 | } -------------------------------------------------------------------------------- /src/tasks/Video_display_modes.kt: -------------------------------------------------------------------------------- 1 | package `video_display_modes` 2 | 3 | // version 1.1.51 4 | 5 | import java.util.Scanner 6 | 7 | fun runSystemCommand(command: String) { 8 | val proc = Runtime.getRuntime().exec(command) 9 | Scanner(proc.inputStream).use { 10 | while (it.hasNextLine()) println(it.nextLine()) 11 | } 12 | proc.waitFor() 13 | println() 14 | } 15 | 16 | fun main(args: Array) { 17 | // query supported display modes 18 | runSystemCommand("xrandr -q") 19 | Thread.sleep(3000) 20 | 21 | // change display mode to 1024x768 say (no text output) 22 | runSystemCommand("xrandr -s 1024x768") 23 | Thread.sleep(3000) 24 | 25 | // change it back again to 1366x768 (or whatever is optimal for your system) 26 | runSystemCommand("xrandr -s 1366x768") 27 | } -------------------------------------------------------------------------------- /src/tasks/Walk_a_directory-Non-recursively.kt: -------------------------------------------------------------------------------- 1 | package `walk_a_directory_non_recursively` 2 | 3 | // version 1.1.2 4 | 5 | import java.io.File 6 | 7 | fun walkDirectory(dirPath: String, pattern: Regex): List { 8 | val d = File(dirPath) 9 | require(d.exists() && d.isDirectory()) 10 | return d.list().filter { it.matches(pattern) } 11 | } 12 | 13 | fun main(args: Array) { 14 | val r = Regex("""^a.*\.h$""") // get all C header files beginning with 'a' 15 | val files = walkDirectory("/usr/include", r) 16 | for (file in files) println(file) 17 | } -------------------------------------------------------------------------------- /src/tasks/Walk_a_directory-Recursively.kt: -------------------------------------------------------------------------------- 1 | package `walk_a_directory_recursively` 2 | 3 | // version 1.2.0 4 | 5 | import java.io.File 6 | 7 | fun walkDirectoryRecursively(dirPath: String, pattern: Regex): Sequence { 8 | val d = File(dirPath) 9 | require (d.exists() && d.isDirectory()) 10 | return d.walk().map { it.name }.filter { it.matches(pattern) }.sorted().distinct() } 11 | 12 | fun main(args: Array) { 13 | val r = Regex("""^v(a|f).*\.h$""") // get all C header files beginning with 'va' or 'vf' 14 | val files = walkDirectoryRecursively("/usr/include", r) 15 | for (file in files) println(file) 16 | } -------------------------------------------------------------------------------- /src/tasks/Web_scraping.kt: -------------------------------------------------------------------------------- 1 | package `web_scraping` 2 | 3 | // version 1.1.3 4 | 5 | import java.net.URL 6 | import java.io.InputStreamReader 7 | import java.util.Scanner 8 | 9 | fun main(args: Array) { 10 | val url = URL("http://tycho.usno.navy.mil/cgi-bin/timer.pl") 11 | val isr = InputStreamReader(url.openStream()) 12 | val sc = Scanner(isr) 13 | while (sc.hasNextLine()) { 14 | val line = sc.nextLine() 15 | if ("UTC" in line) { 16 | println(line.drop(4).take(17)) 17 | break 18 | } 19 | } 20 | sc.close() 21 | } -------------------------------------------------------------------------------- /src/tasks/Window_creation.kt: -------------------------------------------------------------------------------- 1 | package `window_creation` 2 | 3 | import javax.swing.JFrame 4 | 5 | fun main(args : Array) { 6 | JFrame("Title").apply { 7 | setSize(800, 600) 8 | defaultCloseOperation = JFrame.EXIT_ON_CLOSE 9 | isVisible = true 10 | } 11 | } -------------------------------------------------------------------------------- /src/tasks/Word_count.kt: -------------------------------------------------------------------------------- 1 | package `word_count` 2 | 3 | // version 1.1.3 4 | 5 | import java.io.File 6 | 7 | fun main(args: Array) { 8 | val text = File("135-0.txt").readText().toLowerCase() 9 | val r = Regex("""\p{javaLowerCase}+""") 10 | val matches = r.findAll(text) 11 | val wordGroups = matches.map { it.value } 12 | .groupBy { it } 13 | .map { Pair(it.key, it.value.size) } 14 | .sortedByDescending { it.second } 15 | .take(10) 16 | println("Rank Word Frequency") 17 | println("==== ==== =========") 18 | var rank = 1 19 | for ((word, freq) in wordGroups) 20 | System.out.printf("%2d %-4s %5d\n", rank++, word, freq) 21 | } -------------------------------------------------------------------------------- /src/tasks/Write_entire_file.kt: -------------------------------------------------------------------------------- 1 | package `write_entire_file` 2 | 3 | // version 1.1.2 4 | 5 | import java.io.File 6 | 7 | fun main(args: Array) { 8 | val text = "empty vessels make most noise" 9 | File("output.txt").writeText(text) 10 | } -------------------------------------------------------------------------------- /src/tasks/Write_float_arrays_to_a_text_file.kt: -------------------------------------------------------------------------------- 1 | package `write_float_arrays_to_a_text_file` 2 | 3 | // version 1.1.2 4 | 5 | import java.io.File 6 | 7 | fun main(args: Array) { 8 | val x = doubleArrayOf(1.0, 2.0, 3.0, 1e11) 9 | val y = doubleArrayOf(1.0, 1.4142135623730951, 1.7320508075688772, 316227.76601683791) 10 | val xp = 3 11 | val yp = 5 12 | val f = "%.${xp}g\t%.${yp}g\n" 13 | val writer = File("output.txt").writer() 14 | writer.use { 15 | for (i in 0 until x.size) { 16 | val s = f.format(x[i], y[i]) 17 | writer.write(s) 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /src/tasks/Write_to_Windows_event_log.kt: -------------------------------------------------------------------------------- 1 | package `write_to_windows_event_log` 2 | 3 | // version 1.1.4-3 4 | 5 | fun main(args: Array) { 6 | val command = "EventCreate" + 7 | " /t INFORMATION" + 8 | " /id 123" + 9 | " /l APPLICATION" + 10 | " /so Kotlin" + 11 | " /d \"Rosetta Code Example\"" 12 | 13 | Runtime.getRuntime().exec(command) 14 | } -------------------------------------------------------------------------------- /src/tasks/Y_combinator.kt: -------------------------------------------------------------------------------- 1 | package `y_combinator` 2 | 3 | // version 1.1.2 4 | 5 | typealias Func = (T) -> R 6 | 7 | class RecursiveFunc(val p: (RecursiveFunc) -> Func) 8 | 9 | fun y(f: (Func) -> Func): Func { 10 | val rec = RecursiveFunc { r -> f { r.p(r)(it) } } 11 | return rec.p(rec) 12 | } 13 | 14 | fun fac(f: Func) = { x: Int -> if (x <= 1) 1 else x * f(x - 1) } 15 | 16 | fun fib(f: Func) = { x: Int -> if (x <= 2) 1 else f(x - 1) + f(x - 2) } 17 | 18 | fun main(args: Array) { 19 | print("Factorial(1..10) : ") 20 | for (i in 1..10) print("${y(::fac)(i)} ") 21 | print("\nFibonacci(1..10) : ") 22 | for (i in 1..10) print("${y(::fib)(i)} ") 23 | println() 24 | } -------------------------------------------------------------------------------- /src/tasks/Zero_to_the_zero_power.kt: -------------------------------------------------------------------------------- 1 | package `zero_to_the_zero_power` 2 | 3 | // version 1.0.6 4 | 5 | fun main(args: Array) { 6 | println("0 ^ 0 = ${Math.pow(0.0, 0.0)}") 7 | } -------------------------------------------------------------------------------- /src/tasks/_100_doors.kt: -------------------------------------------------------------------------------- 1 | package `_100_doors` 2 | 3 | fun oneHundredDoors(): List { 4 | val doors = BooleanArray(100, { false }) 5 | for (i in 0..99) { 6 | for (j in i..99 step (i + 1)) { 7 | doors[j] = !doors[j] 8 | } 9 | } 10 | return doors 11 | .mapIndexed { i, b -> i to b } 12 | .filter { it.second } 13 | .map { it.first + 1 } 14 | } -------------------------------------------------------------------------------- /src/tasks/_99_Bottles_of_Beer.kt: -------------------------------------------------------------------------------- 1 | package `_99_bottles_of_beer` 2 | 3 | fun main(args: Array) { 4 | for (i in 99.downTo(1)) { 5 | println("$i bottles of beer on the wall") 6 | println("$i bottles of beer") 7 | println("Take one down, pass it around") 8 | } 9 | println("No more bottles of beer on the wall!") 10 | } -------------------------------------------------------------------------------- /test/scripts/implementation/pages/TaskPageSpec.kt: -------------------------------------------------------------------------------- 1 | package scripts.implementation.pages 2 | 3 | import io.kotlintest.matchers.shouldBe 4 | import io.kotlintest.specs.StringSpec 5 | 6 | val kotlinSectionId = 77 // Note that this id might change over time. 7 | 8 | class TaskPageSpec: StringSpec() { 9 | init { 10 | "extract edit page urls from task page" { 11 | val html = "array-concatenation-page.txt".readFileText() 12 | val url = TaskPage(html).extractKotlinEditPageUrl() 13 | url shouldBe EditPageUrl("http://rosettacode.org//mw/index.php?title=Array_concatenation&action=edit§ion=$kotlinSectionId") 14 | } 15 | } 16 | } --------------------------------------------------------------------------------