task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #REXX | REXX | /*REXX (using PC/REXX) to display a message in a window (which is bordered). */
if fcnPkg('rxWindow') ¬== 1 then do
say 'RXWINDOW function package not loaded.'
exit 13
end
if pcVideo()==3 then normal= 7
... |
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #Ring | Ring |
Load "guilib.ring"
New qApp {
new qWidget() {
setwindowtitle("Hello World")
show()
}
exec()
}
|
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #Prolog | Prolog | to_gray(N, G) :-
N0 is N >> 1,
G is N xor N0.
from_gray(G, N) :-
( G > 0
-> S is G >> 1,
from_gray(S, N0),
N is G xor N0
; N is G ). |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #PureBasic | PureBasic | Procedure.i gray_encode(n)
ProcedureReturn n ! (n >> 1)
EndProcedure
Procedure.i gray_decode(g)
Protected bit = 1 << (8 * SizeOf(Integer) - 2)
Protected b = g & bit, p = b >> 1
While bit > 1
bit >> 1
b | (p ! (g & bit))
p = (b & bit) >> 1
Wend
ProcedureReturn b
EndProcedure
If OpenConsole... |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #CMake | CMake | function(swap var1 var2)
set(_SWAP_TEMPORARY "${${var1}}")
set(${var1} "${${var2}}" PARENT_SCOPE)
set(${var2} "${_SWAP_TEMPORARY}" PARENT_SCOPE)
endfunction(swap) |
http://rosettacode.org/wiki/Greatest_element_of_a_list | Greatest element of a list | Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| #Dart | Dart | /*This is a function which returns the greatest element in a list of numbers */
num findGreatestElement(List<num> list){
num greatestElement = list[0];
for (num element in list){
if (element>greatestElement) {
greatestElement = element;
}
}
return greatestElement;
}
/* and this is a shorter vers... |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #Clojure | Clojure | (defn gcd
"(gcd a b) computes the greatest common divisor of a and b."
[a b]
(if (zero? b)
a
(recur b (mod a b)))) |
http://rosettacode.org/wiki/Hailstone_sequence | Hailstone sequence | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conje... | #Dc | Dc | 27
[[--: ]nzpq]sq
[d 2/ p]se
[d 3*1+ p]so
[d2% 0=e d1=q d2% 1=o d1=q lxx]dsxx |
http://rosettacode.org/wiki/Hamming_numbers | Hamming numbers | Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In ... | #Nim | Nim | import bigints
proc min(a: varargs[BigInt]): BigInt =
result = a[0]
for i in 1..a.high:
if a[i] < result: result = a[i]
proc hamming(limit: int): BigInt =
var
h = newSeq[BigInt](limit)
x2 = initBigInt(2)
x3 = initBigInt(3)
x5 = initBigInt(5)
i, j, k = 0
for i in 0..h.high: h[i] = ini... |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #Python | Python | import random
t,g=random.randint(1,10),0
g=int(input("Guess a number that's between 1 and 10: "))
while t!=g:g=int(input("Guess again! "))
print("That's right!") |
http://rosettacode.org/wiki/Greatest_subsequential_sum | Greatest subsequential sum | Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be th... | #Ring | Ring |
# Project : Greatest subsequential sum
aList1 = [0, 1, 2, -3, 3, -1, 0, -4, 0, -1, -4, 2]
see "[0, 1, 2, -3, 3, -1, 0, -4, 0, -1, -4, 2] -> " + sum(aList1) + nl
aList2 = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]
see "[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1] -> " + sum(aList2) + nl
aList3 = [-1, -2, -3, -4, -5]
see "... |
http://rosettacode.org/wiki/Greatest_subsequential_sum | Greatest subsequential sum | Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be th... | #Ruby | Ruby | def subarray_sum(arr)
max, slice = 0, []
arr.each_index do |i|
(i...arr.length).each do |j|
sum = arr[i..j].inject(0, :+)
max, slice = sum, arr[i..j] if sum > max
end
end
[max, slice]
end |
http://rosettacode.org/wiki/Guess_the_number/With_feedback | Guess the number/With feedback | Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to... | #LiveCode | LiveCode | command guessTheNumber lowN highN
local tNumber, tguess, tmin, tmax
if lowN is empty or lowN < 1 then
put 1 into tmin
else
put lowN into tmin
end if
if highN is empty then
put 10 into tmax
else
put highN into tmax
end if
put random(tmax - tmin + 1) + tmin... |
http://rosettacode.org/wiki/Happy_numbers | Happy numbers | From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not inclu... | #MAD | MAD | NORMAL MODE IS INTEGER
BOOLEAN CYCLE
DIMENSION CYCLE(200)
VECTOR VALUES OUTFMT = $I2*$
SEEN = 0
I = 0
NEXNUM THROUGH ZERO, FOR K=0, 1, K.G.200
ZERO CYCLE(K) = 0B
I = I + 1
SUMSQR = I
CHKLP N = SUMSQR
... |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #Io | Io | "Hello world!" println |
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #Robotic | Robotic | require 'gtk2'
window = Gtk::Window.new
window.title = 'Goodbye, World'
window.signal_connect(:delete-event) { Gtk.main_quit }
window.show_all
Gtk.main |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #Python | Python | def gray_encode(n):
return n ^ n >> 1
def gray_decode(n):
m = n >> 1
while m:
n ^= m
m >>= 1
return n
if __name__ == '__main__':
print("DEC, BIN => GRAY => DEC")
for i in range(32):
gray = gray_encode(i)
dec = gray_decode(gray)
print(f" {i:>2d}, {... |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #Quackery | Quackery | [ dup 1 >> ^ ] is encodegray ( n --> n )
[ dup
[ dip [ 1 >> ]
over ^
over 0 = until ]
nip ] is decodegray ( n --> n )
[ [] unrot times
[ 2 /mod char 0 +
rot join swap ]
drop echo$ ] is echobin ( n n --> )
say "number encoded ... |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #COBOL | COBOL |
PROGRAM-ID. SWAP-DEMO.
AUTHOR. Bill Gunshannon.
INSTALLATION. Home.
DATE-WRITTEN. 16 December 2021.
************************************************************
** Program Abstract:
** A simple program to demonstrate the SWAP subprogram.
**
*********... |
http://rosettacode.org/wiki/Greatest_element_of_a_list | Greatest element of a list | Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| #dc | dc | [sm llx] sg
[lm p q] sq
[d lm <u s_ z 0 =q llx] sl
[d sm] su
["Put list of numbers on the stack starting here, then execute g"] s_
3.14159265358979 sp
_275.0 _111.19 0.0 _1234568.0 lp lp _1 *
lgx |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #CLU | CLU | gcd = proc (a, b: int) returns (int)
while b~=0 do
a, b := b, a//b
end
return(a)
end gcd
start_up = proc()
po: stream := stream$primary_input()
as: array[int] := array[int]$[18, 1071, 3528]
bs: array[int] := array[int]$[12, 1029, 3780]
for i: int in array[int]$indexes(as) do
... |
http://rosettacode.org/wiki/Hailstone_sequence | Hailstone sequence | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conje... | #DCL | DCL | $ n = f$integer( p1 )
$ i = 1
$ loop:
$ if p2 .nes. "QUIET" then $ s'i = n
$ if n .eq. 1 then $ goto done
$ i = i + 1
$ if .not. n
$ then
$ n = n / 2
$ else
$ if n .gt. 715827882 then $ exit ! avoid overflowing
$ n = 3 * n + 1
$ endif
$ goto loop
$ done:
$ if p2 .nes. "QUIET"
$ then
$ penultimate_i = i ... |
http://rosettacode.org/wiki/Hamming_numbers | Hamming numbers | Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In ... | #OCaml | OCaml | module ISet = Set.Make(struct type t = int let compare=compare end)
let pq = ref (ISet.singleton 1)
let next () =
let m = ISet.min_elt !pq in
pq := ISet.(remove m !pq |> add (2*m) |> add (3*m) |> add (5*m));
m
let () =
print_string "The first 20 are: ";
for i = 1 to 20
do
Printf.printf "%d " ... |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #QB64_2 | QB64 | START:
CLS
RANDOMIZE TIMER
num = INT(RND * 10) + 1
DO
INPUT "Enter a number between 1 and 10: ", n
IF n = num THEN EXIT DO
PRINT "Nope."
LOOP UNTIL n = num
INPUT "Well guessed! Go again"; a$
IF LEFT$(LCASE$(a$), 1) = "y" THEN GOTO START |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #QB64_3 | QB64 |
'Task
'Plus features: 1) AI gives suggestions about your guess
' 2) AI controls wrong input by user (numbers outer 1 and 10).
' 3) player can choose to replay the game
Randomize Timer
Dim As Integer Done, Guess, Number
Done = 1
Guess = 0
While Done
Cls
Number = Rnd * 10 + 1
Do While Number <> Gu... |
http://rosettacode.org/wiki/Greatest_subsequential_sum | Greatest subsequential sum | Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be th... | #Run_BASIC | Run BASIC | seq$ = "-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1"
max = -999
for i = 1 to 11
sum = 0
for j = i to 11
sum = sum + val(word$(seq$,j,","))
If sum > max then
max = sum
i1 = i
j1 = j
end if
next j
next i
print "Sum:";
for i = i1 to j1
print word$(seq$,i,",");",";
next i
p... |
http://rosettacode.org/wiki/Greatest_subsequential_sum | Greatest subsequential sum | Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be th... | #Rust | Rust | fn main() {
let nums = [1,2,39,34,20, -20, -16, 35, 0];
let mut max = 0;
let mut boundaries = 0..0;
for length in 0..nums.len() {
for start in 0..nums.len()-length {
let sum = (&nums[start..start+length]).iter()
.fold(0, |sum, elem| sum+elem);
if sum >... |
http://rosettacode.org/wiki/Guess_the_number/With_feedback | Guess the number/With feedback | Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to... | #Locomotive_Basic | Locomotive Basic | 10 CLS:RANDOMIZE TIME
20 PRINT "Please specify lower and upper limits":guess=0
30 INPUT " (must be positive integers) :", first, last
40 IF first<1 OR last<1 THEN 20
50 num=INT(RND*(last-first+1)+first)
60 WHILE num<>guess
70 INPUT "Your guess? ", guess
80 IF guess<num THEN PRINT "too small!"
90 IF guess>num THEN PRIN... |
http://rosettacode.org/wiki/Happy_numbers | Happy numbers | From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not inclu... | #Maple | Maple | SumSqDigits := proc( n :: posint )
local s := 0;
local m := n;
while m <> 0 do
s := s + irem( m, 10, 'm' )^2
end do;
s
end proc: |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #Ioke | Ioke | "Hello world!" println |
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #Ruby | Ruby | require 'gtk2'
window = Gtk::Window.new
window.title = 'Goodbye, World'
window.signal_connect(:delete-event) { Gtk.main_quit }
window.show_all
Gtk.main |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #R | R |
GrayEncode <- function(binary) {
gray <- substr(binary,1,1)
repeat {
if (substr(binary,1,1) != substr(binary,2,2)) gray <- paste(gray,"1",sep="")
else gray <- paste(gray,"0",sep="")
binary <- substr(binary,2,nchar(binary))
if (nchar(binary) <=1) {
break
}
}
return (gray)
}
GrayDecode <- function(gray) {
... |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #ColdFusion | ColdFusion | <cfset temp = a />
<cfset a = b />
<cfset b = temp /> |
http://rosettacode.org/wiki/Greatest_element_of_a_list | Greatest element of a list | Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| #DCL | DCL | $ list = "45,65,81,12,0,13,-56,123,-123,888,12,0"
$ max = f$integer( f$element( 0, ",", list ))
$ i = 1
$ loop:
$ element = f$element( i, ",", list )
$ if element .eqs. "," then $ goto done
$ element = f$integer( element )
$ if element .gt. max then $ max = element
$ i = i + 1
$ goto loop
$ done:
$ show symbol ma... |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. GCD.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 A PIC 9(10) VALUE ZEROES.
01 B PIC 9(10) VALUE ZEROES.
01 TEMP PIC 9(10) VALUE ZEROES.
PROCEDURE DIVISION.
Begin.
DISPLAY "Enter firs... |
http://rosettacode.org/wiki/Hailstone_sequence | Hailstone sequence | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conje... | #Delphi | Delphi | program ShowHailstoneSequence;
{$APPTYPE CONSOLE}
uses SysUtils, Generics.Collections;
procedure GetHailstoneSequence(aStartingNumber: Integer; aHailstoneList: TList<Integer>);
var
n: Integer;
begin
aHailstoneList.Clear;
aHailstoneList.Add(aStartingNumber);
n := aStartingNumber;
while n <> 1 do
begi... |
http://rosettacode.org/wiki/Hamming_numbers | Hamming numbers | Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In ... | #Oz | Oz | declare
fun lazy {HammingFun}
1|{FoldL1 [{MultHamming 2} {MultHamming 3} {MultHamming 5}] LMerge}
end
Hamming = {HammingFun}
fun {MultHamming N}
{LMap Hamming fun {$ X} N*X end}
end
fun lazy {LMap Xs F}
case Xs
of nil then nil
[] X|Xr then {F X}|{LMap Xr F}
end
end
... |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #Quackery | Quackery | randomise
10 random 1+ number$
say 'I chose a number between 1 and 10.' cr
[ $ 'Your guess? ' input
over = if
done
again ]
drop say 'Well guessed!' |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #R | R | f <- function() {
print("Guess a number between 1 and 10 until you get it right.")
n <- sample(10, 1)
while (as.numeric(readline()) != n) {
print("Try again.")
}
print("You got it!")
} |
http://rosettacode.org/wiki/Greatest_subsequential_sum | Greatest subsequential sum | Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be th... | #Scala | Scala | def maxSubseq(l: List[Int]) = l.scanRight(Nil : List[Int]) {
case (el, acc) if acc.sum + el < 0 => Nil
case (el, acc) => el :: acc
} max Ordering.by((_: List[Int]).sum)
def biggestMaxSubseq(l: List[Int]) = l.scanRight(Nil : List[Int]) {
case (el, acc) if acc.sum + el < 0 => Nil
case (el, a... |
http://rosettacode.org/wiki/Guess_the_number/With_feedback | Guess the number/With feedback | Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to... | #Logo | Logo | to guess [:max 100]
local "number
make "number random :max
local "guesses
make "guesses 0
local "guess
forever [
(type [Guess my number! \(range 1 -\ ] :max "\):\ )
make "guess first readlist
ifelse (or (not numberp :guess) (lessp :guess 1) (greaterp :guess :max)) [
print sentence [Guess... |
http://rosettacode.org/wiki/Happy_numbers | Happy numbers | From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not inclu... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | AddSumSquare[input_]:=Append[input,Total[IntegerDigits[Last[input]]^2]]
NestUntilRepeat[a_,f_]:=NestWhile[f,{a},!MemberQ[Most[Last[{##}]],Last[Last[{##}]]]&,All]
HappyQ[a_]:=Last[NestUntilRepeat[a,AddSumSquare]]==1 |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #IS-BASIC | IS-BASIC | PRINT "Hello world!" |
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #Run_BASIC | Run BASIC | ' do it with javascript
html "<script>alert('Goodbye, World!');</script>" |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #Racket | Racket |
#lang racket
(define (gray-encode n) (bitwise-xor n (arithmetic-shift n -1)))
(define (gray-decode n)
(letrec ([loop (lambda(g bits)
(if (> bits 0)
(loop (bitwise-xor g bits) (arithmetic-shift bits -1))
g))])
(loop 0 n)))
(define (to-bin n) (f... |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #Raku | Raku | sub gray_encode ( Int $n --> Int ) {
return $n +^ ( $n +> 1 );
}
sub gray_decode ( Int $n is copy --> Int ) {
my $mask = 1 +< (32-2);
$n +^= $mask +> 1 if $n +& $mask while $mask +>= 1;
return $n;
}
for ^32 -> $n {
my $g = gray_encode($n);
my $d = gray_decode($g);
printf "%2d: %5b => %5b... |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #Common_Lisp | Common Lisp | (rotatef a b)
(psetq a b b a) |
http://rosettacode.org/wiki/Greatest_element_of_a_list | Greatest element of a list | Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| #Delphi | Delphi |
program GElemLIst;
{$IFNDEF FPC}
{$Apptype Console}
{$ENDIF}
uses
math;
const
MaxCnt = 10000;
var
IntArr : array of integer;
fltArr : array of double;
i: integer;
begin
setlength(fltArr,MaxCnt); //filled with 0
setlength(IntArr,MaxCnt); //filled with 0.0
randomize;
i := random(MaxCnt); //ch... |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #Cobra | Cobra |
class Rosetta
def gcd(u as number, v as number) as number
u, v = u.abs, v.abs
while v > 0
u, v = v, u % v
return u
def main
print "gcd of [12] and [8] is [.gcd(12, 8)]"
print "gcd of [12] and [-8] is [.gcd(12, -8)]"
print "gcd of [96] and [27] is [.gcd(27, 96)]"
print "gcd of [51] and [34] is [.g... |
http://rosettacode.org/wiki/Hailstone_sequence | Hailstone sequence | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conje... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | local hailstone:
swap [ over ]
while < 1 dup:
if % over 2:
#odd
++ * 3
else:
#even
/ swap 2
swap push-through rot dup
drop
if = (name) :(main):
local :h27 hailstone 27
!. = 112 len h27
!. = 27 h27! 0
!. = 82 h27! 1
!. = 41 h27! 2
!. = 124 h27! 3
!. = 8 h27! 108
!. = 4 h27! 109
!. = 2 h27... |
http://rosettacode.org/wiki/Hamming_numbers | Hamming numbers | Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In ... | #PARI.2FGP | PARI/GP | Hupto(n)={
my(v=vector(n),x2=2,x3=3,x5=5,i=1,j=1,k=1,t);
v[1]=1;
for(m=2,n,
v[m]=t=min(x2,min(x3,x5));
if(x2 == t, x2 = v[i++] << 1);
if(x3 == t, x3 = 3 * v[j++]);
if(x5 == t, x5 = 5 * v[k++]);
);
v
};
H(n)=Hupto(n)[n];
Hupto(20)
H(1691)
H(10^6) |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #Racket | Racket | #lang racket
(define (guess-number)
(define number (add1 (random 10)))
(let loop ()
(define guess (read))
(if (equal? guess number)
(display "Well guessed!\n")
(loop)))) |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #Raku | Raku | my $number = (1..10).pick;
repeat {} until prompt("Guess a number: ") == $number;
say "Guessed right!"; |
http://rosettacode.org/wiki/Greatest_subsequential_sum | Greatest subsequential sum | Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be th... | #Scheme | Scheme | (define (maxsubseq in)
(let loop
((_sum 0) (_seq (list)) (maxsum 0) (maxseq (list)) (l in))
(if (null? l)
(cons maxsum (reverse maxseq))
(let* ((x (car l)) (sum (+ _sum x)) (seq (cons x _seq)))
(if (> sum 0)
(if (> sum maxsum)
(loop sum seq sum s... |
http://rosettacode.org/wiki/Guess_the_number/With_feedback | Guess the number/With feedback | Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to... | #Lua | Lua | math.randomseed(os.time())
me_win=false
my_number=math.random(1,10)
while me_win==false do
print "Guess my number from 1 to 10:"
your_number = io.stdin:read'*l'
if type(tonumber(your_number))=="number" then
your_number=tonumber(your_number)
if your_number>10 or your_number<1 then
print "Your number was not be... |
http://rosettacode.org/wiki/Happy_numbers | Happy numbers | From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not inclu... | #MATLAB | MATLAB | function findHappyNumbers
nHappy = 0;
k = 1;
while nHappy < 8
if isHappyNumber(k, [])
fprintf('%d ', k)
nHappy = nHappy+1;
end
k = k+1;
end
fprintf('\n')
end
function hap = isHappyNumber(k, prev)
if k == 1
hap = true;
elseif ismember(... |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #Isabelle | Isabelle | theory Scratch
imports Main
begin
value ‹''Hello world!''›
end |
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #Rust | Rust | // cargo-deps: gtk
extern crate gtk;
use gtk::traits::*;
use gtk::{Window, WindowType, WindowPosition};
use gtk::signal::Inhibit;
fn main() {
gtk::init().unwrap();
let window = Window::new(WindowType::Toplevel).unwrap();
window.set_title("Goodbye, World!");
window.set_border_width(10);
window.s... |
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #Scala | Scala | swing.Dialog.showMessage(message = "Goodbye, World!") |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #REXX | REXX | /*REXX program converts decimal number ───► binary ───► gray code ───► binary.*/
parse arg N . /*get the optional argument from the CL*/
if N=='' | N=="," then N=31 /*Not specified? Then use the default.*/
L=max(1,length(strip(x2b(d2x(N)),'L',0))) /*find the max binary length of N... |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #Computer.2Fzero_Assembly | Computer/zero Assembly | LDA 29
STA 31
LDA 30
STA 29
LDA 31
STA 30
STP
---
org 29
byte $0F
byte $E0
byte $00 |
http://rosettacode.org/wiki/Greatest_element_of_a_list | Greatest element of a list | Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| #Dyalect | Dyalect | func max(xs) {
var y
for x in xs {
if y == nil || x > y {
y = x
}
}
y
}
var xs = [1..10]
max(xs) |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #CoffeeScript | CoffeeScript |
gcd = (x, y) ->
if y == 0 then x else gcd y, x % y
|
http://rosettacode.org/wiki/Hailstone_sequence | Hailstone sequence | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conje... | #EchoLisp | EchoLisp |
(lib 'hash)
(lib 'sequences)
(lib 'compile)
(define (hailstone n)
(when (> n 1)
(if (even? n) (/ n 2) (1+ (* n 3)))))
(define H (make-hash))
;; (iterator/f seed f) returns seed, (f seed) (f(f seed)) ...
(define (hlength seed)
(define collatz (iterator/f hailstone seed))
(or
(hash-ref H seed) ;; known ?... |
http://rosettacode.org/wiki/Hamming_numbers | Hamming numbers | Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In ... | #Pascal | Pascal |
program HammNumb;
{$IFDEF FPC}
{$MODE DELPHI}
{$OPTIMIZATION ON}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
{
type
NativeUInt = longWord;
}
var
pot : array[0..2] of NativeUInt;
function NextHammNumb(n:NativeUInt):NativeUInt;
var
q,p,nr : NativeUInt;
begin
repeat
nr := n+1;
n := nr;
p := 0;
... |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #RapidQ | RapidQ |
RANDOMIZE
number = rnd(10) + 1
Print "I selected a number between 1 and 10, try to find it:" + chr$(10)
while Guess <> Number
input "Your guess: "; Guess
wend
print "You guessed right, well done !"
input "Press enter to quit";a$
|
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #Rascal | Rascal | import vis::Render;
import vis::Figure;
import util::Math;
public void Guess(){
random = arbInt(10);
entered = "";
guess = false;
figure = box(vcat([
text("Try to guess the number from 0 to 9."),
textfield("Put your guess here", void(str s){guess = (toInt(s)==random); entered = s; }, fillColor("white")),
... |
http://rosettacode.org/wiki/Greatest_subsequential_sum | Greatest subsequential sum | Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be th... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const func array integer: maxSubseq (in array integer: sequence) is func
result
var array integer: maxSequence is 0 times 0;
local
var integer: number is 0;
var integer: index is 0;
var integer: currentSum is 0;
var integer: currentStart is 1;
var integer: maxSum ... |
http://rosettacode.org/wiki/Greatest_subsequential_sum | Greatest subsequential sum | Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be th... | #Sidef | Sidef | func maxsubseq(*a) {
var (start, end, sum, maxsum) = (-1, -1, 0, 0);
a.each_kv { |i, x|
sum += x;
if (maxsum < sum) {
maxsum = sum;
end = i;
}
elsif (sum < 0) {
sum = 0;
start = i;
}
};
a.ft(start+1, end);
}
say ma... |
http://rosettacode.org/wiki/Guess_the_number/With_feedback | Guess the number/With feedback | Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to... | #M2000_Interpreter | M2000 Interpreter |
Module GuessNumber {
Read Min, Max
chosen = Random(Min, Max)
print "guess a whole number between ";Min;" and ";Max
do {
\\ we use guess so Input get integer value
\\ if we press enter without a number we get error
do {
... |
http://rosettacode.org/wiki/Happy_numbers | Happy numbers | From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not inclu... | #MAXScript | MAXScript |
fn isHappyNumber n =
(
local pastNumbers = #()
while n != 1 do
(
n = n as string
local newNumber = 0
for i = 1 to n.count do
(
local digit = n[i] as integer
newNumber += pow digit 2
)
n = newNumber
if (finditem pastNumbers n) != 0 do return false
append pastNumbers newNumber
)
n == 1
)
pri... |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #IWBASIC | IWBASIC |
OPENCONSOLE
PRINT"Hello world!"
'This line could be left out.
PRINT:PRINT:PRINT"Press any key to end."
'Keep the console from closing right away so the text can be read.
DO:UNTIL INKEY$<>""
CLOSECONSOLE
END
|
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #Scheme | Scheme |
#!r6rs
;; PS-TK example: display frame + label
(import (rnrs)
(lib pstk main) ; change this to refer to your PS/Tk installation
)
(define tk (tk-start))
(tk/wm 'title tk "PS-Tk Example: Label")
(let ((label (tk 'create-widget 'label 'text: "Goodbye, world")))
(tk/place label 'height: 20 'wi... |
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #Scilab | Scilab | messagebox("Goodbye, World!") |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #Ring | Ring |
# Project : Gray code
pos = 5
see "0 : 00000 => 00000 => 00000" + nl
for n = 1 to 31
res1 = tobase(n, 2, pos)
res2 = tobase(grayencode(n), 2, pos)
res3 = tobase(graydecode(n), 2, pos)
see "" + n + " : " + res1 + " => " + res2 + " => " + res3 + nl
next
func grayencode(n)
return n ^ (n ... |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #Ruby | Ruby | class Integer
# Converts a normal integer to a Gray code.
def to_gray
raise Math::DomainError, "integer is negative" if self < 0
self ^ (self >> 1)
end
# Converts a Gray code to a normal integer.
def from_gray
raise Math::DomainError, "integer is negative" if self < 0
recurse = proc do |i|
... |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #Crystal | Crystal | a, b = b, a |
http://rosettacode.org/wiki/Greatest_element_of_a_list | Greatest element of a list | Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | max lst:
lst! 0
for item in copy lst:
if > item dup:
item drop
!. max [ 10 300 999 9 ] |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #Common_Lisp | Common Lisp | CL-USER> (gcd 2345 5432)
7 |
http://rosettacode.org/wiki/Hailstone_sequence | Hailstone sequence | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conje... | #EDSAC_order_code | EDSAC order code |
[Hailstone (or Collatz) task for Rosetta Code.
EDSAC program, Initial Orders 2.]
[This program shows how subroutines can be called via the
phi, H, N, ..., V parameters, so that the code doesn't have
to be changed if the subroutines are moved about in store.
See Wilkes, Wheeler and Gill, 1951 edition, page... |
http://rosettacode.org/wiki/Hamming_numbers | Hamming numbers | Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In ... | #Perl | Perl | use strict;
use warnings;
use List::Util 'min';
# If you want the large output, uncomment either the one line
# marked (1) or the two lines marked (2)
#use Math::GMP qw/:constant/; # (1) uncomment this to use Math::GMP
#use Math::GMPz; # (2) uncomment this plus later line for Math::GMPz
s... |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #Red | Red |
Red []
#include %environment/console/CLI/input.red
random/seed now
print "I have thought of a number between 1 and 10. Try to guess it."
number: random 10
while [(to integer! input) <> number][
print "Your guess was wrong. Try again."
]
print "Well guessed!"
|
http://rosettacode.org/wiki/Greatest_subsequential_sum | Greatest subsequential sum | Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be th... | #SQL | SQL |
/*
This is a code implementation for finding one or more contiguous subsequences in a general sequence with the maximum sum of its elements.
p_list -- List of elements of the general sequence of integers separated by a delimiter.
p_delimiter -- proper delimiter
*/
WITH
FUNCTION greatest_subsequential_sum(p_... |
http://rosettacode.org/wiki/Guess_the_number/With_feedback | Guess the number/With feedback | Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to... | #Maple | Maple | GuessANumber := proc(low, high)
local number, input;
randomize():
printf( "Guess a number between %d and %d:\n:> ", low, high );
number := rand(low..high)();
do
input := parse(readline());
if input > number then
printf("Too high, try again!\n:> ");
elif input < nu... |
http://rosettacode.org/wiki/Happy_numbers | Happy numbers | From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not inclu... | #Mercury | Mercury | :- module happy.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int, list, set_tree234.
main(!IO) :-
print_line(get_n_happy_numbers(8, 1), !IO).
:- func get_n_happy_numbers(int, int) = list(int).
get_n_happy_numbers(NumToFind, N) =
( if NumT... |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #J | J | 'Hello world!'
Hello world! |
http://rosettacode.org/wiki/Hello_world/Graphical | Hello world/Graphical |
Task
Display the string Goodbye, World! on a GUI object (alert box, plain window, text area, etc.).
Related task
Hello world/Text
| #Scratch | Scratch | pos -100 70
print "Goodbye, World!" |
http://rosettacode.org/wiki/Gray_code | Gray code | Gray code
Karnaugh maps
Create functions to encode a number to and decode a number from Gray code.
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
There are many possible Gray codes. The follow... | #Rust | Rust | fn gray_encode(integer: u64) -> u64 {
(integer >> 1) ^ integer
}
fn gray_decode(integer: u64) -> u64 {
match integer {
0 => 0,
_ => integer ^ gray_decode(integer >> 1)
}
}
fn main() {
for i in 0..32 {
println!("{:2} {:0>5b} {:0>5b} {:2}", i, i, gray_encode(i),
gra... |
http://rosettacode.org/wiki/Generic_swap | Generic swap | Task
Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types.
If your solution language is statically typed please describe the way your language provides genericity.
If variables are typed in t... | #D | D | import std.algorithm: swap; // from Phobos standard library
// The D solution uses templates and it's similar to the C++ one:
void mySwap(T)(ref T left, ref T right) {
auto temp = left;
left = right;
right = temp;
}
void main() {
import std.stdio;
int[] a = [10, 20];
writeln(a);
// T... |
http://rosettacode.org/wiki/Greatest_element_of_a_list | Greatest element of a list | Task
Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.
| #Draco | Draco | /* Find the greatest element in an array of ints */
proc nonrec max([*] int a) int:
int INT_MIN = ~((~0) >> 1);
int nmax, i;
nmax := INT_MIN;
for i from 0 upto dim(a,1)-1 do
if a[i] > nmax then nmax := a[i] fi
od;
nmax
corp
/* Test on an array */
proc nonrec main() void:
type arr ... |
http://rosettacode.org/wiki/Greatest_common_divisor | Greatest common divisor | Greatest common divisor
You are encouraged to solve this task according to the task description, using any language you may know.
Task
Find the greatest common divisor (GCD) of two integers.
Greatest common divisor is also known as greatest common factor (gcf) and greatest common measure.
Related tas... | #Component_Pascal | Component Pascal |
MODULE Operations;
IMPORT StdLog,Args,Strings;
PROCEDURE Gcd(a,b: LONGINT):LONGINT;
VAR
r: LONGINT;
BEGIN
LOOP
r := a MOD b;
IF r = 0 THEN RETURN b END;
a := b;b := r
END
END Gcd;
PROCEDURE DoGcd*;
VAR
x,y,done: INTEGER;
p: Args.Params;
BEGIN
Args.Get(p);
IF p.argc >= 2 THEN
Strings.StringToInt(p.... |
http://rosettacode.org/wiki/Hailstone_sequence | Hailstone sequence | The Hailstone sequence of numbers can be generated from a starting positive integer, n by:
If n is 1 then the sequence ends.
If n is even then the next n of the sequence = n/2
If n is odd then the next n of the sequence = (3 * n) + 1
The (unproven) Collatz conje... | #Egel | Egel |
import "prelude.eg"
namespace Hailstone (
using System
using List
def even = [ N -> (N%2) == 0 ]
def hailstone =
[ 1 -> {1}
| N -> if even N then cons N (hailstone (N/2))
else cons N (hailstone (N * 3 + 1)) ]
def hailpair =
[ N -> (N, length (hailst... |
http://rosettacode.org/wiki/Hamming_numbers | Hamming numbers | Hamming numbers are numbers of the form
H = 2i × 3j × 5k
where
i, j, k ≥ 0
Hamming numbers are also known as ugly numbers and also 5-smooth numbers (numbers whose prime divisors are less or equal to 5).
Task
Generate the sequence of Hamming numbers, in increasing order. In ... | #Phix | Phix | with javascript_semantics
function hamming(integer N)
sequence h = repeat(1,N)
atom x2 = 2, x3 = 3, x5 = 5, hn
integer i = 1, j = 1, k = 1
for n=2 to N do
hn = min(x2,min(x3,x5))
h[n] = hn
if hn==x2 then i += 1 x2 = 2*h[i] end if
if hn==x3 then j += 1 x3 = 3*h[j] end if
if h... |
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #Retro | Retro | : checkGuess ( gn-gf || f )
over = [ drop 0 ] [ "Sorry, try again!\n" puts -1 ] if ;
: think ( -n )
random abs 10 mod 1+ ;
: guess ( - )
"I'm thinking of a number between 1 and 10.\n" puts
"Try to guess it!\n" puts
think [ getToken toNumber checkGuess ] while
"You got it!\n" puts ;
|
http://rosettacode.org/wiki/Guess_the_number | Guess the number | Task
Write a program where the program chooses a number between 1 and 10.
A player is then prompted to enter a guess. If the player guesses wrong, then the prompt appears again until the guess is correct.
When the player has made a successful guess the computer will issue a "Well guessed!" message, a... | #REXX | REXX | #!/usr/bin/rexx
/*REXX program to play: Guess the number */
number = random(1,10)
say "I have thought of a number. Try to guess it!"
guess=0 /* We don't want a valid guess, before we start */
do while guess \= number
pull guess
if guess \= number then
say "Sorry, the guess was wrong. Try again!"
... |
http://rosettacode.org/wiki/Greatest_subsequential_sum | Greatest subsequential sum | Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be th... | #Standard_ML | Standard ML | val maxsubseq = let
fun loop (_, _, maxsum, maxseq) [] = (maxsum, rev maxseq)
| loop (sum, seq, maxsum, maxseq) (x::xs) = let
val sum = sum + x
val seq = x :: seq
in
if sum < 0 then
loop (0, [], maxsum, maxseq) xs
else if sum > maxsum then
loop (sum, seq, ... |
http://rosettacode.org/wiki/Greatest_subsequential_sum | Greatest subsequential sum | Task
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
An empty subsequence is considered to have the sum of 0; thus if all elements are negative, the result must be th... | #Swift | Swift | func maxSubseq(sequence: [Int]) -> (Int, Int, Int) {
var maxSum = 0, thisSum = 0, i = 0
var start = 0, end = -1
for (j, seq) in sequence.enumerated() {
thisSum += seq
if thisSum < 0 {
i = j + 1
thisSum = 0
} else if (thisSum > maxSum) {
maxSum = th... |
http://rosettacode.org/wiki/Guess_the_number/With_feedback | Guess the number/With feedback | Task
Write a game (computer program) that follows the following rules:
The computer chooses a number between given set limits.
The player is asked for repeated guesses until the the target number is guessed correctly
At each guess, the computer responds with whether the guess is:
higher than the target,
equal to... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | guessnumber[min_, max_] :=
Module[{number = RandomInteger[{min, max}], guess},
While[guess =!= number,
guess = Input[
If[guess > number, "Too high.Guess again.",
"Too low.Guess again.",
"Guess a number between " <> ToString@min <> " and " <>
ToString@max <> "."]]];
CreateDialog[{"... |
http://rosettacode.org/wiki/Happy_numbers | Happy numbers | From Wikipedia, the free encyclopedia:
A happy number is defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not inclu... | #MiniScript | MiniScript | isHappy = function(x)
while true
if x == 89 then return false
sum = 0
while x > 0
sum = sum + (x % 10)^2
x = floor(x / 10)
end while
if sum == 1 then return true
x = sum
end while
end function
found = []
i = 1
while found.len < 8
if i... |
http://rosettacode.org/wiki/Hello_world/Text | Hello world/Text | Hello world/Text is part of Short Circuit's Console Program Basics selection.
Task
Display the string Hello world! on a text console.
Related tasks
Hello world/Graphical
Hello world/Line Printer
Hello world/Newbie
Hello world/Newline omission
Hello world/Standard error
Hello world/Web server
| #Jack | Jack | class Main {
function void main () {
do Output.printString("Hello world!");
do Output.println();
return;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.