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/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #TI-89_BASIC | TI-89 BASIC | Define doors(fast) = Func
Local doors,i,j
seq(false,x,1,100) ? doors
If fast Then
For i,1,10,1
true ? doors[i^2]
EndFor
Else
For i,1,100,1
For j,i,100,i
not doors[j] ? doors[j]
EndFor
EndFor
EndIf
Return doors
EndFunc |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #TorqueScript | TorqueScript | for(%steps = 1; %a <= 100; %a++)
for(%current = %steps; %current <= 100; %current += %steps)
%door[%current] = !%door[%current];
for(%a = 1; %a <= 100; %a++)
echo("Door #" @ %a @ " is" SPC %door[%current] ? "Open" : "Closed" @ "."); |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Transact-SQL | Transact-SQL |
WITH OneToTen (N)
AS ( SELECT N
FROM ( VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9)
) V(N)
)
, InitDoors (Num, IsOpen)
AS ( SELECT 1
+ 1 * Units.N
+ 10 * Tens.N AS Num
, CONVERT(Bit, 0) AS IsOpen
FROM OneToTen AS Units
CROSS JOIN OneToTen AS Tens
) -- This part could be easier with a tally table or equivalent table-valued function
, States (NbStep, Num, IsOpen)
AS ( SELECT 0 AS NbStep
, Num
, IsOpen
FROM InitDoors AS InitState
UNION ALL
SELECT 1 + NbStep
, Num
, CASE Num % (1 + NbStep)
WHEN 0 THEN ~IsOpen
ELSE IsOpen
END
FROM States
WHERE NbStep < 100
)
SELECT Num AS DoorNumber
, Concat( 'Door number ', Num, ' is '
, CASE IsOpen
WHEN 1 THEN ' open'
ELSE ' closed'
END ) AS RESULT -- Concat needs SQL Server 2012
FROM States
WHERE NbStep = 100
ORDER BY Num
; -- Fortunately, maximum recursion is 100 in SQL Server.
-- For more doors, the MAXRECURSION hint should be used.
-- More doors would also need an InitDoors with more rows.
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Transd | Transd | #lang transd
MainModule: {
doors: Vector<Bool>(100),
_start: (λ
(for i in Seq(100) do
(for k in Seq(i 100 (+ i 1)) do
(set-el doors k (not (get doors k)))
))
(for i in Seq(100) do
(if (get doors i) (textout (+ i 1) " "))
))
}
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #True_BASIC | True BASIC |
! Optimized solution with True BASIC
OPTION NOLET
x = 1
y = 3
z = 0
PRINT STR$(x) & " Open"
DO UNTIL z >= 100
z = x + y
PRINT STR$(z) & " Open"
x = z
y = y + 2
LOOP
END
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #TSE_SAL | TSE SAL |
// library: math: get: task: door: open: close100 <description></description> <version control></version control> <version>1.0.0.0.11</version> <version control></version control> (filenamemacro=getmaocl.s) [<Program>] [<Research>] [kn, ri, mo, 31-12-2012 22:03:16]
PROC PROCMathGetTaskDoorOpenClose( INTEGER doorMaxI, INTEGER passMaxI )
// e.g. PROC Main()
// e.g. PROCMathGetTaskDoorOpenClose( 100, 100 )
// e.g. END
// e.g.
// e.g. <F12> Main()
//
// ===
//
// The output will be:
//
// door 1 is open
// door 4 is open
// door 9 is open
// door 16 is open
// door 25 is open
// door 36 is open
// door 49 is open
// door 64 is open
// door 81 is open
// door 100 is open
// all other doors are closed
//
// ===
//
INTEGER passMinI = 1
INTEGER passI = 0
//
INTEGER doorminI = 1
INTEGER doorI = 0
//
STRING s[255] = ""
//
INTEGER bufferI = 0
//
PushPosition()
bufferI = CreateTempBuffer()
PopPosition()
//
FOR doorI = doorMinI TO doorMaxI
//
SetGlobalInt( Format( "doorsI", doorI ), 0 )
//
ENDFOR
//
FOR passI = passMinI TO passMaxI
//
doorI = passI - passI
//
REPEAT
//
doorI = doorI + passI
//
SetGlobalInt( Format( "doorsI", doorI ), NOT( GetGlobalInt( Format( "doorsI", doorI ) ) ) )
//
UNTIL ( doorI >= doorMaxI )
//
ENDFOR
//
FOR doorI = doorMinI TO doorMaxI
//
IF ( GetGlobalInt( Format( "doorsI", doorI ) ) > 0 )
//
s = "open"
//
AddLine( Format( "door", " ", doorI, " ", "is", " ", s ), bufferI )
//
ELSE
//
s = "closed"
//
ENDIF
//
ENDFOR
//
AddLine( "all other doors are closed", bufferI )
//
GotoBufferId( bufferI )
//
END
PROC Main()
PROCMathGetTaskDoorOpenClose( 100, 100 )
END
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
DICT doors create
COMPILE
LOOP door=1,100
LOOP pass=1,100
SET go=MOD (door,pass)
DICT doors lookup door,num,cnt,status
IF (num==0) THEN
SET status="open"
DICT doors add door,num,cnt,status
ELSE
IF (go==0) THEN
IF (status=="closed") THEN
SET status="open"
ELSE
SET status="closed"
ENDIF
DICT doors update door,num,cnt,status
ENDIF
ENDIF
ENDLOOP
ENDLOOP
ENDCOMPILE
DICT doors unload door,num,cnt,status
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Tiny_BASIC | Tiny BASIC | PRINT "Open doors are:"
LET I = 1
10 IF I = 100 THEN END
rem funcion SQR
LET B = I*I
rem funcion MODULO
LET A = I - (I / B) * B
IF A < 11 THEN PRINT B
LET I = I + 1
GOTO 10 |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #TypeScript | TypeScript |
interface Door {
id: number;
open: boolean;
}
function doors(): Door[] {
var Doors: Door[] = [];
for (let i = 1; i <= 100; i++) {
Doors.push({id: i, open: false});
}
for (let secuence of Doors) {
for (let door of Doors) {
if (door.id % secuence.id == 0) {
door.open = !door.open;
}
}
}
return Doors.filter(a => a.open);
}
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #TXR | TXR | (defun hyaku-mai-tobira ()
(let ((doors (vector 100)))
(each ((i (range 0 99)))
(each ((j (range i 99 (+ i 1))))
(flip [doors j])))
doors))
(each ((counter (range 1))
(door (hyaku-mai-tobira)))
(put-line `door @counter is @(if door "open" "closed")`)) |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #uBasic.2F4tH | uBasic/4tH | FOR p = 1 TO 100
FOR d = p TO 100 STEP p
@(d) = @(d) = 0
NEXT d
NEXT p
FOR d= 1 TO 100
IF @(d) PRINT "Door ";d;" is open"
NEXT d |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Uniface | Uniface |
entry LP_DO_IT
variables
string V_DOORS
boolean V_DOOR_STATE
string V_DOOR_STATE_S
numeric V_IDX
numeric V_TOTAL_DOORS
string V_DOOR_STATE_LIST
numeric V_LOOP_COUNT
endvariables
V_TOTAL_DOORS = 100
putitem V_DOORS, V_TOTAL_DOORS, 0
V_DOORS = $replace (V_DOORS, 1, "·;", "·;0", -1)
putitem/id V_DOOR_STATE_LIST, "1", "Open"
putitem/id V_DOOR_STATE_LIST, "0", "Close"
V_LOOP_COUNT = 1
while (V_LOOP_COUNT <= V_TOTAL_DOORS)
V_IDX = 0
V_IDX = V_IDX + V_LOOP_COUNT
getitem V_DOOR_STATE, V_DOORS, V_IDX
while (V_IDX <= V_TOTAL_DOORS)
V_DOOR_STATE = !V_DOOR_STATE
getitem/id V_DOOR_STATE_S, V_DOOR_STATE_LIST, $number(V_DOOR_STATE)
putitem V_DOORS, V_IDX, V_DOOR_STATE
V_IDX = V_IDX + V_LOOP_COUNT
getitem V_DOOR_STATE, V_DOORS, V_IDX
endwhile
V_LOOP_COUNT = V_LOOP_COUNT + 1
endwhile
V_IDX = 1
getitem V_DOOR_STATE, V_DOORS, V_IDX
while (V_IDX <= V_TOTAL_DOORS)
getitem/id V_DOOR_STATE_S, V_DOOR_STATE_LIST, $number(V_DOOR_STATE)
if (V_DOOR_STATE)
putmess "Door %%V_IDX%%% is finally %%V_DOOR_STATE_S%%%"
endif
V_IDX = V_IDX + 1
getitem V_DOOR_STATE, V_DOORS, V_IDX
endwhile
end ; LP_DO_IT
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Unison | Unison | hundredDoors : [Boolean]
hundredDoors =
toggleEachNth : Nat -> [Boolean] -> [Boolean]
toggleEachNth n doors =
go counter = cases
[] -> []
(d +: ds) -> if counter == n
then (not d) +: go 1 ds
else d +: go (counter+1) ds
go 1 doors
foldr toggleEachNth (replicate 100 'false) (range 1 101)
results = filterMap (cases (open, ix) -> if open then Some (ix+1) else None)
(indexed hundredDoors) |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #UNIX_Shell | UNIX Shell | #! /bin/bash
declare -a doors
for((i=1; i <= 100; i++)); do
doors[$i]=0
done
for((i=1; i <= 100; i++)); do
for((j=i; j <= 100; j += i)); do
echo $i $j
doors[$j]=$(( doors[j] ^ 1 ))
done
done
for((i=1; i <= 100; i++)); do
if [[ ${doors[$i]} -eq 0 ]]; then
op="closed"
else
op="open"
fi
echo $i $op
done |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Ursa | Ursa |
#
# 100 doors
#
decl int i j
decl boolean<> doors
# append 101 boolean values to doors stream
for (set i 0) (or (< i 100) (= i 100)) (inc i)
append false doors
end for
# loop through, opening and closing doors
for (set i 1) (or (< i 100) (= i 100)) (inc i)
for (set j i) (or (< j 100) (= j 100)) (inc j)
if (= (mod j i) 0)
set doors<j> (not doors<j>)
end if
end for
end for
# loop through and output which doors are open
for (set i 1) (or (< i 100) (= i 100)) (inc i)
out "Door " i ": " console
if doors<i>
out "open" endl console
else
out "closed" endl console
end if
end if
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Ursala | Ursala | #import std
#import nat
doors = 0!* iota 100
pass("n","d") = remainder\"n"?l(~&r,not ~&r)* num "d"
#cast %nL
main = ~&rFlS num pass=>doors nrange(100,1) |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #UTFool | UTFool |
···
http://rosettacode.org/wiki/100_doors
···
■ HundredDoors
§ static
▶ main
• args⦂ String[]
open⦂ boolean: true
closed⦂ boolean: false
doors⦂ boolean[1+100] · all initially closed
🔁 pass from 1 to 100
∀ visited ∈ pass‥100 by pass
· toggle the visited doors
if the doors[visited] are closed
let the doors[visited] be open
else
let the doors[visited] be closed
for each door #n in doors⦂ boolean
if the door is open
System.out.println "Door #⸨n⸩ is open."
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Vala | Vala | int main() {
bool doors_open[101];
for(int i = 1; i < doors_open.length; i++) {
for(int j = 1; i*j < doors_open.length; j++) {
doors_open[i*j] = !doors_open[i*j];
}
stdout.printf("%d: %s\n", i, (doors_open[i] ? "open" : "closed"));
}
return 0;
} |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #VAX_Assembly | VAX Assembly |
00000064 0000 1 n = 100
0000 0000 2 .entry doors, ^m<>
26'AF 9F 0002 3 pushab b^arr ; offset signed byte
50 64 8F 9A 0005 4 movzbl #n, r0
50 DD 0009 5 pushl r0 ; (sp) -> .ascid arr
000B 6 10$:
51 50 D0 000B 7 movl r0, r1 ; step = start index
000E 8 20$:
25'AF41 01 8C 000E 9 xorb2 #^a"0" \^a"1", b^arr-1[r1] ; \ xor toggle "1"<->"0"
FFF5 51 50 6E F1 0013 10 acbl (sp), r0, r1, 20$ ; limit, step, index
EF 50 F5 0019 11 sobgtr r0, 10$ ; n..1
001C 12
5E DD 001C 13 pushl sp ; descriptor by reference
00000000'GF 01 FB 001E 14 calls #1, g^lib$put_output ; show result
04 0025 15 ret
0026 16
30'30'30'30'30'30'30'30'30'30'30'30' 0026 17 arr: .byte ^a"0"[n]
30'30'30'30'30'30'30'30'30'30'30'30' 0032
30'30'30'30'30'30'30'30'30'30'30'30' 003E
30'30'30'30'30'30'30'30'30'30'30'30' 004A
30'30'30'30'30'30'30'30'30'30'30'30' 0056
30'30'30'30'30'30'30'30'30'30'30'30' 0062
30'30'30'30'30'30'30'30'30'30'30'30' 006E
30'30'30'30'30'30'30'30'30'30'30'30' 007A
30'30'30'30' 0086
008A 18 .end doors
$ run doors
1001000010000001000000001000000000010000000000001000000000000001000000000000000010000000000000000001
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #VBA | VBA |
Sub Rosetta_100Doors()
Dim Door(100) As Boolean, i As Integer, j As Integer
For i = 1 To 100 Step 1
For j = i To 100 Step i
Door(j) = Not Door(j)
Next j
If Door(i) = True Then
Debug.Print "Door " & i & " is Open"
Else
Debug.Print "Door " & i & " is Closed"
End If
Next i
End Sub
<!-- /lang -->
*** USE THIS ONE, SEE COMMENTED LINES, DONT KNOW WHY EVERYBODY FOLLOWED OTHERS ANSWERS AND CODED THE PROBLEM DIFFERENTLY ***
*** ALWAYS USE AND TEST A READABLE, EASY TO COMPREHEND CODING BEFORE 'OPTIMIZING' YOUR CODE AND TEST THE 'OPTIMIZED' CODE AGAINST THE 'READABLE' ONE.
Panikkos Savvides.
Sub Rosetta_100Doors2()
Dim Door(100) As Boolean, i As Integer, j As Integer
Dim strAns As String
' There are 100 doors in a row that are all initially closed.
' You make 100 passes by the doors.
For j = 1 To 100
' The first time through, visit every door and toggle the door
' (if the door is closed, open it; if it is open, close it).
For i = 1 To 100 Step 1
Door(i) = Not Door(i)
Next i
' The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
For i = 2 To 100 Step 2
Door(i) = Not Door(i)
Next i
' The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
For i = 3 To 100 Step 3
Door(i) = Not Door(i)
Next i
Next j
For j = 1 To 100
If Door(j) = True Then
strAns = j & strAns & ", "
End If
Next j
If Right(strAns, 2) = ", " Then strAns = Left(strAns, Len(strAns) - 2)
If Len(strAns) = 0 Then strAns = "0"
Debug.Print "Doors [" & strAns & "] are open, the rest are closed."
' Doors [0] are open, the rest are closed., AKA ZERO DOORS OPEN
End Sub
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #VBScript | VBScript | Dim doorIsOpen(100), pass, currentDoor, text
For currentDoor = 0 To 99
doorIsOpen(currentDoor) = False
Next
For pass = 0 To 99
For currentDoor = pass To 99 Step pass + 1
doorIsOpen(currentDoor) = Not doorIsOpen(currentDoor)
Next
Next
For currentDoor = 0 To 99
text = "Door #" & currentDoor + 1 & " is "
If doorIsOpen(currentDoor) Then
text = text & "open."
Else
text = text & "closed."
End If
WScript.Echo(text)
Next |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Vedit_macro_language | Vedit macro language | Buf_Switch(Buf_Free)
Ins_Char('-', COUNT, 100) // All doors closed
for (#1 = 1; #1 <= 100; #1++) {
for (#2 = #1; #2 <= 100; #2 += #1) {
Goto_Col(#2)
Ins_Char((Cur_Char^0x62), OVERWRITE) // Toggle between '-' and 'O'
}
} |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Verilog | Verilog |
module main;
integer i;
initial begin
$display("Las siguientes puertas están abiertas:");
for (i=1; i<=10; i=i+1) if (i%i*i<11) $display(i*i);
$finish ;
end
endmodule
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #VHDL | VHDL | library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
entity DOORS is
port (CLK: in std_logic; OUTPUT: out std_logic_vector(1 to 100));
end DOORS;
architecture Behavioral of DOORS is
begin
process (CLK)
variable TEMP: std_logic_vector(1 to 100);
begin
--setup closed doors
TEMP := (others => '0');
--looping through
for i in 1 to TEMP'length loop
for j in i to TEMP'length loop
if (j mod i) = 0 then
TEMP(j) := not TEMP(j);
end if;
end loop;
end loop;
--assign output
OUTPUT <= TEMP;
end process;
end Behavioral;
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Visual_Basic | Visual Basic |
Public Sub Doors100()
' the state of a door is represented by the data type boolean (false = door closed, true = door opened)
Dim doorstate(1 To 100) As Boolean ' the doorstate()-array is initialized by VB with value 'false'
Dim i As Long, j As Long
For i = 1 To 100
For j = i To 100 Step i
doorstate(j) = Not doorstate(j)
Next j
Next i
Debug.Print "The following doors are open:"
For i = 1 To 100
' print number if door is openend
If doorstate(i) Then Debug.Print CStr(i)
Next i
End Sub
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Main()
Dim doors(100) As Boolean 'Door 1 is at index 0
For pass = 1 To 100
For door = pass - 1 To 99 Step pass
doors(door) = Not doors(door)
Next
Next
For door = 0 To 99
Console.WriteLine("Door # " & (door + 1) & " is " & If(doors(door), "Open", "Closed"))
Next
Console.ReadLine()
End Sub
End Module |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Vlang | Vlang | const number_doors = 101
fn main() {
mut closed_doors := []bool{len: number_doors, init: true}
for pass in 0..number_doors {
for door := 0; door < number_doors; door += pass + 1 {
closed_doors[door] = !closed_doors[door]
}
}
for pass in 1..number_doors {
if !closed_doors[pass] {
println('Door #$pass Open')
}
}
} |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #VTL-2 | VTL-2 | 10 D=1
20 :D)=0
30 D=D+1
40 #=100>D*20
50 P=1
60 D=P
70 :D)=:D)=0
80 D=D+P
90 #=100>D*70
100 P=P+1
110 #=100>P*60
120 D=1
130 #=:D)*170
140 D=D+1
150 #=100>D*130
160 #=999
170 ?="DOOR ";
180 ?=D
190 ?=" IS OPEN"
200 #=! |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Wart | Wart | def (doors n)
let door (table)
for step 1 (step <= n) ++step
for j 0 (j < n) (j <- j+step)
zap! not door.j
for j 0 (j < n) ++j
when door.j
pr j
pr " " |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #WDTE | WDTE | let a => import 'arrays';
let s => import 'stream';
let io => import 'io';
let toggle doors m =>
a.stream doors
-> s.enumerate
-> s.map (@ s n => [+ (a.at n 0) 1; a.at n 1])
-> s.map (@ s n => switch n {
(@ s n => == (% (a.at n 0) m) 0) => ! (a.at n 1);
true => a.at n 1;
})
-> s.collect
;
s.range 100
-> s.map false
-> s.collect : doors
-> s.range 1 100
-> s.reduce doors toggle
-> a.stream
-> s.map (@ s n => switch 0 {
n => 'Open';
true => 'Closed';
} -- io.writeln io.stdout)
-> s.drain
; |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Wortel | Wortel | ; unoptimized
+^[
@var doors []
@for i rangei [1 100]
@for j rangei [i 100 i]
:!@not `j doors
@for i rangei [1 100]
@if `i doors
!console.log "door {i} is open"
]
; optimized, map square over 1 to 10
!*^@sq @to 10 |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Wrapl | Wrapl | MOD Doors;
IMP Agg.Table;
IMP Std.String;
IMP IO.Terminal USE Out;
VAR door <- {}; EVERY door[1:to(100), "closed"];
DEF toggle(num) door[num] <- door[num] = "open" => "closed" // "open";
EVERY WITH pass <- 1:to(100), num <- pass:to(100, pass) DO toggle(num);
Out:write('Doors {door @ String.T}.');
END Doors. |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Wren | Wren | var doors = [true] * 100
for (i in 1..100) {
var j = i
while (j < 100) {
doors[j] = !doors[j]
j = j + i + 1
}
}
for (i in 0...100) {
if (doors[i]) System.write("%(i + 1) ")
}
System.print() |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #X86_Assembly | X86 Assembly |
.NOLIST
; The task can be completed in 48 and "half" steps:
; On the first pass ALL doors are opened.
; On the second pass every EVEN door is closed.
; So, instead of all closed, the doors can initially be:
; Every odd door open, every even door closed and start at pass 3.
; On 51st and all the next passes, only one door is visited per pass:
; On 51st pass door 51, on 52nd pass door 52 etc.
; So, after pass 50, we can make "half a pass" starting with door 51
; and toggling every door up to and including 100.
; The code uses only volatile registers, so, no string (STOS etc) instructions.
TITLE 100 Doors
PAGE , 132
.686
.MODEL FLAT
OPTION CASEMAP:NONE
.SFCOND
.LIST
; =============================================================================
.DATA?
Doors BYTE 100 DUP ( ? )
; =============================================================================
.CODE
Pass_Doors PROC
MOV EDX, OFFSET Doors ; Initialize all doors.
MOV ECX, SIZEOF Doors / SIZEOF DWORD
MOV EAX, 01010101h ; This does first and second pass.
Close_Doors: MOV [ EDX ], EAX
ADD EDX, SIZEOF DWORD
LOOP Close_Doors
MOV ECX, 2 ; Pass and step.
Pass_Loop: MOV EDX, OFFSET Doors
ASSUME EDX:PTR BYTE
Doors_Loop: XOR [ EDX ], 1 ; Toggle this door.
ADD EDX, ECX ; Advance.
CMP EDX, OFFSET Doors[ SIZEOF Doors ]
JB Doors_Loop
INC ECX
CMP ECX, SIZEOF Doors
JB Pass_Loop
XOR Doors[ SIZEOF Doors -1 ], 1 ; This is pass 100.
RET
Pass_Doors ENDP
; =============================================================================
END
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #XBasic | XBasic | PROGRAM "100doors"
VERSION "0.0001"
IMPORT "xma"
IMPORT "xst"
DECLARE FUNCTION Entry()
FUNCTION Entry()
maxpuertas = 100
cont = 0
DIM puertas[100]
FOR p = 1 TO maxpuertas
IF INT(SQRT(p)) = SQRT(p) THEN puertas[p] = 1
NEXT p
PRINT "The doors are open: ";
FOR p = 1 TO maxpuertas
IF puertas[p] = 1 THEN
PRINT p; " ";
INC cont
END IF
NEXT p
PRINT CHR$(10); "Are "; STR$(cont); " open doors."
END FUNCTION
END PROGRAM |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Xojo | Xojo |
// True=Open; False=Closed
Dim doors(100) As Boolean // Booleans default to false
For j As Integer = 1 To 100
For i As Integer = 1 to 100
If i Mod j = 0 Then doors(i) = Not doors(i)
Next
Next
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
int Door(100); \You have 100 doors in a row
define Open, Closed;
int D, Pass, Step;
[for D:= 0 to 100-1 do \that are all initially closed
Door(D):= Closed;
Step:= 1; \The first time through, you visit every door
for Pass:= 1 to 100 do \You make 100 passes by the doors
[D:= Step-1;
repeat \if the door is closed, you open it; if it is open, you close it
if Door(D)=Closed then Door(D):= Open else Door(D):= Closed;
D:= D+Step;
until D>=100;
Step:= Step+1; \The second time you only visit every 2nd door
]; \The third time, every 3rd door
\until you only visit the 100th door
\What state are the doors in after the last pass?
Text(0, "Open: "); \Which are open?
for D:= 0 to 100-1 do
if Door(D)=Open then [IntOut(0, D+1); ChOut(0,^ )];
CrLf(0);
Text(0, "Closed: "); \Which are closed?
for D:= 0 to 100-1 do
if Door(D)=Closed then [IntOut(0, D+1); ChOut(0,^ )];
CrLf(0);
\Optimized: The only doors that remain open are those that are perfect squares
Text(0, "Open: ");
D:= 1;
repeat IntOut(0, D*D); ChOut(0,^ );
D:= D+1;
until D*D>100;
CrLf(0);
] |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #XSLT_1.0 | XSLT 1.0 | <hallway>
<door number="1">closed</door>
<door number="2">closed</door>
<door number="3">closed</door>
<door number="4">closed</door>
... etc ...
<door number="100">closed</door>
<hallway> |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #XSLT_2.0 | XSLT 2.0 | <xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
<xsl:template match="/">
<hallway>
<xsl:for-each select="1 to 100">
<xsl:variable name="door-num" select="position()" />
<door number="{$door-num}">
<xsl:value-of select="('closed','open')[
number( sum( for $pass in 1 to 100 return
number(($door-num mod $pass) = 0)) mod 2 = 1) + 1]" />
</door>
</xsl:for-each>
</hallway>
</xsl:template>
</xsl:stylesheet> |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Yabasic | Yabasic | n = 100 // doors
ppa = 1 // next open door
p2 = 1
for i = 1 to n
print "Door ", i, " is ";
if i < p2 then
print "closed."
else
ppa = ppa + 1
p2 = ppa^2
print "OPEN."
end if
next |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Yorick | Yorick | doors = array(0, 100);
for(i = 1; i <= 100; i++)
for(j = i; j <= 100; j += i)
doors(j) ~= 1;
print, where(doors); |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Zig | Zig | pub fn main() !void {
const stdout = @import("std").io.getStdOut().writer();
var doors = [_]bool{false} ** 101;
var pass: u8 = 1;
var door: u8 = undefined;
while (pass <= 100) : (pass += 1) {
door = pass;
while (door <= 100) : (door += pass)
doors[door] = !doors[door];
}
for (doors) |open, num|
if (open)
try stdout.print("Door {d} is open.\n", .{num});
} |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #zkl | zkl | doors:=List.createLong(100,False); // list of 100 Falses
foreach n,m in (100,[n..99,n+1]){ doors[m]=(not doors[m]); } //foreach{ foreach{} }
doors.filterNs().apply('+(1)).println(); |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 REM 100 doors open/closed?
20 DIM d(100)
25 LET o=0
30 FOR a=1 TO 100
40 FOR b=a TO 100 STEP a
50 LET d(b)=NOT d(b)
55 LET o=o+(d(b)=1)-(d(b)=0)
60 NEXT b
70 NEXT a
80 PRINT o;" open doors"
|
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #11l | 11l | V costs = [‘W’ = [‘A’ = 16, ‘B’ = 16, ‘C’ = 13, ‘D’ = 22, ‘E’ = 17],
‘X’ = [‘A’ = 14, ‘B’ = 14, ‘C’ = 13, ‘D’ = 19, ‘E’ = 15],
‘Y’ = [‘A’ = 19, ‘B’ = 19, ‘C’ = 20, ‘D’ = 23, ‘E’ = 50],
‘Z’ = [‘A’ = 50, ‘B’ = 12, ‘C’ = 50, ‘D’ = 15, ‘E’ = 11]]
V demand = [‘A’ = 30, ‘B’ = 20, ‘C’ = 70, ‘D’ = 30, ‘E’ = 60]
V cols = sorted(demand.keys())
V supply = [‘W’ = 50, ‘X’ = 60, ‘Y’ = 50, ‘Z’ = 50]
V res = Dict(costs.keys().map(k -> (k, DefaultDict[Char, Int]())))
[Char = [Char]] g
L(x) supply.keys()
g[x] = sorted(costs[x].keys(), key' g -> :costs[@x][g])
L(x) demand.keys()
g[x] = sorted(costs.keys(), key' g -> :costs[g][@x])
L !g.empty
[Char = Int] d
L(x) demand.keys()
d[x] = I g[x].len > 1 {(costs[g[x][1]][x] - costs[g[x][0]][x])} E costs[g[x][0]][x]
[Char = Int] s
L(x) supply.keys()
s[x] = I g[x].len > 1 {(costs[x][g[x][1]] - costs[x][g[x][0]])} E costs[x][g[x][0]]
V f = max(d.keys(), key' n -> @d[n])
V t = max(s.keys(), key' n -> @s[n])
(t, f) = I d[f] > s[t] {(f, g[f][0])} E (g[t][0], t)
V v = min(supply[f], demand[t])
res[f][t] += v
demand[t] -= v
I demand[t] == 0
L(k, n) supply
I n != 0
g[k].remove(t)
g.pop(t)
demand.pop(t)
supply[f] -= v
I supply[f] == 0
L(k, n) demand
I n != 0
g[k].remove(f)
g.pop(f)
supply.pop(f)
L(n) cols
print("\t "n, end' ‘ ’)
print()
V cost = 0
L(g) sorted(costs.keys())
print(g" \t", end' ‘ ’)
L(n) cols
V y = res[g][n]
I y != 0
print(y, end' ‘ ’)
cost += y * costs[g][n]
print("\t", end' ‘ ’)
print()
print("\n\nTotal Cost = "cost) |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #C | C | #include <stdio.h>
#include <limits.h>
#define TRUE 1
#define FALSE 0
#define N_ROWS 4
#define N_COLS 5
typedef int bool;
int supply[N_ROWS] = { 50, 60, 50, 50 };
int demand[N_COLS] = { 30, 20, 70, 30, 60 };
int costs[N_ROWS][N_COLS] = {
{ 16, 16, 13, 22, 17 },
{ 14, 14, 13, 19, 15 },
{ 19, 19, 20, 23, 50 },
{ 50, 12, 50, 15, 11 }
};
bool row_done[N_ROWS] = { FALSE };
bool col_done[N_COLS] = { FALSE };
void diff(int j, int len, bool is_row, int res[3]) {
int i, c, min1 = INT_MAX, min2 = min1, min_p = -1;
for (i = 0; i < len; ++i) {
if((is_row) ? col_done[i] : row_done[i]) continue;
c = (is_row) ? costs[j][i] : costs[i][j];
if (c < min1) {
min2 = min1;
min1 = c;
min_p = i;
}
else if (c < min2) min2 = c;
}
res[0] = min2 - min1; res[1] = min1; res[2] = min_p;
}
void max_penalty(int len1, int len2, bool is_row, int res[4]) {
int i, pc = -1, pm = -1, mc = -1, md = INT_MIN;
int res2[3];
for (i = 0; i < len1; ++i) {
if((is_row) ? row_done[i] : col_done[i]) continue;
diff(i, len2, is_row, res2);
if (res2[0] > md) {
md = res2[0]; /* max diff */
pm = i; /* pos of max diff */
mc = res2[1]; /* min cost */
pc = res2[2]; /* pos of min cost */
}
}
if (is_row) {
res[0] = pm; res[1] = pc;
}
else {
res[0] = pc; res[1] = pm;
}
res[2] = mc; res[3] = md;
}
void next_cell(int res[4]) {
int i, res1[4], res2[4];
max_penalty(N_ROWS, N_COLS, TRUE, res1);
max_penalty(N_COLS, N_ROWS, FALSE, res2);
if (res1[3] == res2[3]) {
if (res1[2] < res2[2])
for (i = 0; i < 4; ++i) res[i] = res1[i];
else
for (i = 0; i < 4; ++i) res[i] = res2[i];
return;
}
if (res1[3] > res2[3])
for (i = 0; i < 4; ++i) res[i] = res2[i];
else
for (i = 0; i < 4; ++i) res[i] = res1[i];
}
int main() {
int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4];
int results[N_ROWS][N_COLS] = { 0 };
for (i = 0; i < N_ROWS; ++i) supply_left += supply[i];
while (supply_left > 0) {
next_cell(cell);
r = cell[0];
c = cell[1];
q = (demand[c] <= supply[r]) ? demand[c] : supply[r];
demand[c] -= q;
if (!demand[c]) col_done[c] = TRUE;
supply[r] -= q;
if (!supply[r]) row_done[r] = TRUE;
results[r][c] = q;
supply_left -= q;
total_cost += q * costs[r][c];
}
printf(" A B C D E\n");
for (i = 0; i < N_ROWS; ++i) {
printf("%c", 'W' + i);
for (j = 0; j < N_COLS; ++j) printf(" %2d", results[i][j]);
printf("\n");
}
printf("\nTotal cost = %d\n", total_cost);
return 0;
} |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #C.2B.2B | C++ | #include <iostream>
#include <numeric>
#include <vector>
template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << ']';
}
std::vector<int> demand = { 30, 20, 70, 30, 60 };
std::vector<int> supply = { 50, 60, 50, 50 };
std::vector<std::vector<int>> costs = {
{16, 16, 13, 22, 17},
{14, 14, 13, 19, 15},
{19, 19, 20, 23, 50},
{50, 12, 50, 15, 11}
};
int nRows = supply.size();
int nCols = demand.size();
std::vector<bool> rowDone(nRows, false);
std::vector<bool> colDone(nCols, false);
std::vector<std::vector<int>> result(nRows, std::vector<int>(nCols, 0));
std::vector<int> diff(int j, int len, bool isRow) {
int min1 = INT_MAX;
int min2 = INT_MAX;
int minP = -1;
for (int i = 0; i < len; i++) {
if (isRow ? colDone[i] : rowDone[i]) {
continue;
}
int c = isRow
? costs[j][i]
: costs[i][j];
if (c < min1) {
min2 = min1;
min1 = c;
minP = i;
} else if (c < min2) {
min2 = c;
}
}
return { min2 - min1, min1, minP };
}
std::vector<int> maxPenalty(int len1, int len2, bool isRow) {
int md = INT_MIN;
int pc = -1;
int pm = -1;
int mc = -1;
for (int i = 0; i < len1; i++) {
if (isRow ? rowDone[i] : colDone[i]) {
continue;
}
std::vector<int> res = diff(i, len2, isRow);
if (res[0] > md) {
md = res[0]; // max diff
pm = i; // pos of max diff
mc = res[1]; // min cost
pc = res[2]; // pos of min cost
}
}
return isRow
? std::vector<int> { pm, pc, mc, md }
: std::vector<int>{ pc, pm, mc, md };
}
std::vector<int> nextCell() {
auto res1 = maxPenalty(nRows, nCols, true);
auto res2 = maxPenalty(nCols, nRows, false);
if (res1[3] == res2[3]) {
return res1[2] < res2[2]
? res1
: res2;
}
return res1[3] > res2[3]
? res2
: res1;
}
int main() {
int supplyLeft = std::accumulate(supply.cbegin(), supply.cend(), 0, [](int a, int b) { return a + b; });
int totalCost = 0;
while (supplyLeft > 0) {
auto cell = nextCell();
int r = cell[0];
int c = cell[1];
int quantity = std::min(demand[c], supply[r]);
demand[c] -= quantity;
if (demand[c] == 0) {
colDone[c] = true;
}
supply[r] -= quantity;
if (supply[r] == 0) {
rowDone[r] = true;
}
result[r][c] = quantity;
supplyLeft -= quantity;
totalCost += quantity * costs[r][c];
}
for (auto &a : result) {
std::cout << a << '\n';
}
std::cout << "Total cost: " << totalCost;
return 0;
} |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #11l | 11l | L(filename) fs:list_dir(‘/foo/bar’)
I filename.ends_with(‘.mp3’)
print(filename) |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #D | D | void main() {
import std.stdio, std.string, std.algorithm, std.range;
enum K { A, B, C, D, E, X, Y, Z, W }
immutable int[K][K] costs = cast() //**
[K.W: [K.A: 16, K.B: 16, K.C: 13, K.D: 22, K.E: 17],
K.X: [K.A: 14, K.B: 14, K.C: 13, K.D: 19, K.E: 15],
K.Y: [K.A: 19, K.B: 19, K.C: 20, K.D: 23, K.E: 50],
K.Z: [K.A: 50, K.B: 12, K.C: 50, K.D: 15, K.E: 11]];
int[K] demand, supply;
with (K)
demand = [A: 30, B: 20, C: 70, D: 30, E: 60],
supply = [W: 50, X: 60, Y: 50, Z: 50];
auto cols = demand.keys.sort().release;
auto res = costs.byKey.zip((int[K]).init.repeat).assocArray;
K[][K] g;
foreach (immutable x; supply.byKey)
g[x] = costs[x].keys.schwartzSort!(k => cast()costs[x][k]) //**
.release;
foreach (immutable x; demand.byKey)
g[x] = costs.keys.schwartzSort!(k=> cast()costs[k][x]).release;
while (g.length) {
int[K] d, s;
foreach (immutable x; demand.byKey)
d[x] = g[x].length > 1 ?
costs[g[x][1]][x] - costs[g[x][0]][x] :
costs[g[x][0]][x];
foreach (immutable x; supply.byKey)
s[x] = g[x].length > 1 ?
costs[x][g[x][1]] - costs[x][g[x][0]] :
costs[x][g[x][0]];
auto f = d.keys.minPos!((a,b) => d[a] > d[b])[0];
auto t = s.keys.minPos!((a,b) => s[a] > s[b])[0];
if (d[f] > s[t]) {
t = f;
f = g[f][0];
} else {
f = t;
t = g[t][0];
}
immutable v = min(supply[f], demand[t]);
res[f][t] += v;
demand[t] -= v;
if (demand[t] == 0) {
foreach (immutable k, immutable n; supply)
if (n != 0)
g[k] = g[k].remove!(c => c == t);
g.remove(t);
demand.remove(t);
}
supply[f] -= v;
if (supply[f] == 0) {
foreach (immutable k, immutable n; demand)
if (n != 0)
g[k] = g[k].remove!(c => c == f);
g.remove(f);
supply.remove(f);
}
}
writefln("%-(\t%s%)", cols);
auto cost = 0;
foreach (immutable c; costs.keys.sort().release) {
write(c, '\t');
foreach (immutable n; cols) {
if (n in res[c]) {
immutable y = res[c][n];
if (y != 0) {
y.write;
cost += y * costs[c][n];
}
}
'\t'.write;
}
writeln;
}
writeln("\nTotal Cost = ", cost);
} |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #68000_Assembly | 68000 Assembly | ;
; Non-recursive directory walk for Motorola 68000 under AmigaOs 2.04+ by Thorham
;
execBase equ 4
;
; from exec includes
;
_LVOOpenLibrary equ -552
_LVOCloseLibrary equ -414
_LVOAllocVec equ -684
_LVOFreeVec equ -690
MEMF_ANY equ 0
;
; from dos includes
;
_LVOVPrintf equ -954
_LVOExamine equ -102
_LVOExNext equ -108
_LVOLock equ -84
_LVOUnLock equ -90
_LVOParsePatternNoCase equ -966
_LVOMatchPatternNoCase equ -972
ACCESS_READ equ -2
rsset 0
fib_DiskKey rs.l 1
fib_DirEntryType rs.l 1
fib_FileName rs.b 108
fib_Protection rs.l 1
fib_EntryType rs.l 1
fib_Size rs.l 1
fib_NumBlocks rs.l 1
fib_DateStamp rs.b 12
fib_Comment rs.b 80
fib_OwnerUID rs.w 1
fib_OwnerGID rs.w 1
fib_Reserved rs.b 32
fib_SIZEOF rs.b 0
;
; main
;
start
move.l execBase,a6
; open dos.library
lea dosName,a1
moveq #37,d0
jsr _LVOOpenLibrary(a6)
move.l d0,dosBase
beq exit
; allocate memory for file info block
move.l #fib_SIZEOF,d0
move.l #MEMF_ANY,d1
jsr _LVOAllocVec(a6)
move.l d0,fib
beq exit
; get directory lock
move.l dosBase,a6
move.l #pathString,d1
move.l #ACCESS_READ,d2
jsr _LVOLock(a6)
move.l d0,lock
beq exit
; examine directory for ExNext
move.l lock,d1
move.l fib,d2
jsr _LVOExamine(a6)
tst.w d0
beq exit
; parse pattern string
move.l #patternString,d1
move.l #patternParsed,d2
move.l #sizeof_patternString*2+2,d3
jsr _LVOParsePatternNoCase(a6)
tst.l d0
blt exit
; get some pointers for use in the loop
lea printfArgs,a2
move.l fib,a3
lea fib_FileName(a3),a3
.loop
; get next directory entry
move.l lock,d1
move.l fib,d2
jsr _LVOExNext(a6)
tst.w d0
beq exit
; match pattern
move.l #patternParsed,d1
move.l a3,d2
jsr _LVOMatchPatternNoCase(a6)
; if match then print file name
tst.l d0
beq .nomatch
move.l a3,(a2)
move.l #formatString,d1
move.l #printfArgs,d2
jsr _LVOVPrintf(a6)
.nomatch
bra .loop
; cleanup and exit
exit
move.l dosBase,a6
move.l lock,d1
jsr _LVOUnLock(a6)
move.l execBase,a6
move.l fib,a1
tst.l a1
beq .l1
jsr _LVOFreeVec(a6)
.l1
move.l dosBase,a1
jsr _LVOCloseLibrary(a6)
rts
section data,data_p
;
; variables
;
dosBase
dc.l 0
lock
dc.l 0
fib
dc.l 0
printfArgs
dc.l 0
;
; strings
;
dosName
dc.b "dos.library",0
pathString
dc.b "ram:",0
formatString
dc.b "%s",10,0
patternString
dc.b "#?",0
patternString_end
sizeof_patternString=patternString_end-patternString
patternParsed
dcb.b sizeof_patternString*2+2 |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #Go | Go | package main
import (
"fmt"
"math"
)
var supply = []int{50, 60, 50, 50}
var demand = []int{30, 20, 70, 30, 60}
var costs = make([][]int, 4)
var nRows = len(supply)
var nCols = len(demand)
var rowDone = make([]bool, nRows)
var colDone = make([]bool, nCols)
var results = make([][]int, nRows)
func init() {
costs[0] = []int{16, 16, 13, 22, 17}
costs[1] = []int{14, 14, 13, 19, 15}
costs[2] = []int{19, 19, 20, 23, 50}
costs[3] = []int{50, 12, 50, 15, 11}
for i := 0; i < len(results); i++ {
results[i] = make([]int, nCols)
}
}
func nextCell() []int {
res1 := maxPenalty(nRows, nCols, true)
res2 := maxPenalty(nCols, nRows, false)
switch {
case res1[3] == res2[3]:
if res1[2] < res2[2] {
return res1
} else {
return res2
}
case res1[3] > res2[3]:
return res2
default:
return res1
}
}
func diff(j, l int, isRow bool) []int {
min1 := math.MaxInt32
min2 := min1
minP := -1
for i := 0; i < l; i++ {
var done bool
if isRow {
done = colDone[i]
} else {
done = rowDone[i]
}
if done {
continue
}
var c int
if isRow {
c = costs[j][i]
} else {
c = costs[i][j]
}
if c < min1 {
min2, min1, minP = min1, c, i
} else if c < min2 {
min2 = c
}
}
return []int{min2 - min1, min1, minP}
}
func maxPenalty(len1, len2 int, isRow bool) []int {
md := math.MinInt32
pc, pm, mc := -1, -1, -1
for i := 0; i < len1; i++ {
var done bool
if isRow {
done = rowDone[i]
} else {
done = colDone[i]
}
if done {
continue
}
res := diff(i, len2, isRow)
if res[0] > md {
md = res[0] // max diff
pm = i // pos of max diff
mc = res[1] // min cost
pc = res[2] // pos of min cost
}
}
if isRow {
return []int{pm, pc, mc, md}
}
return []int{pc, pm, mc, md}
}
func main() {
supplyLeft := 0
for i := 0; i < len(supply); i++ {
supplyLeft += supply[i]
}
totalCost := 0
for supplyLeft > 0 {
cell := nextCell()
r, c := cell[0], cell[1]
q := demand[c]
if q > supply[r] {
q = supply[r]
}
demand[c] -= q
if demand[c] == 0 {
colDone[c] = true
}
supply[r] -= q
if supply[r] == 0 {
rowDone[r] = true
}
results[r][c] = q
supplyLeft -= q
totalCost += q * costs[r][c]
}
fmt.Println(" A B C D E")
for i, result := range results {
fmt.Printf("%c", 'W' + i)
for _, item := range result {
fmt.Printf(" %2d", item)
}
fmt.Println()
}
fmt.Println("\nTotal cost =", totalCost)
} |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #8080_Assembly | 8080 Assembly | exit: equ 0 ; CP/M syscall to exit
puts: equ 9 ; CP/M syscall to print a string
sfirst: equ 17 ; 'Find First' CP/M syscall
snext: equ 18 ; 'Find Next' CP/M syscall
FCB: equ 5Ch ; Location of FCB for file given on command line
org 100h
lxi d,FCB ; CP/M parses the command line for us automatically
mvi c,sfirst; and prepares an FCB which we can pass to SFIRST
call 5 ; immediately.
lxi d,emsg ; If SFIRST returns an error, there is no file,
mvi c,puts ; so we should print an error message.
loop: inr a ; A=FF = error
jz 5
dcr a ; If we _do_ have a file, the directory entry
rrc ; is located at DTA (80h) + A * 32. 0<=A<=3.
rrc ; Rotate right twice, moving low bits into high bits,
stc ; then finally rotate a 1 bit into the top bit.
rar ; The effect is 000000AB -> 1AB00000.
inr a ; Finally the filename is at offset 1 in the dirent.
mvi h,0 ; Set HL = pointer to the filename
mov l,a
lxi d,fname ; The filename is stored as 'FILENAMEEXT', but let's
mvi b,8 ; be nice and print 'FILENAME.EXT\r\n'.
call memcpy ; Copy filename (wihtout extension) into placeholder
inx d ; Skip the '.' in the placeholder
mvi b,3 ; Then copy the extension
call memcpy
lxi d,fname ; Then print the formatted filename
mvi c,puts
call 5
lxi d,FCB ; Find the next file matching the pattern in the FCB
mvi c,snext ; The result is the same as for SFIRST, so we can
call 5 ; loop back here, except FF means no more files.
mvi c,exit ; Arrange for the error routine to instead exit cleanly
jmp loop
memcpy: mov a,m ; Copy B bytes from HL to DE
stax d
inx h
inx d
dcr b
jnz memcpy
ret
emsg: db 'Not Found$'
fname: db 'XXXXXXXX.XXX',13,10,'$' ; Filename placeholder |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #8th | 8th |
"*.c" f:glob \ puts an array of strings with the file names on the top of the stack
|
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #J | J | vam=:1 :0
:
exceeding=. 0 <. -&(+/)
D=. x,y exceeding x NB. x: demands
S=. y,x exceeding y NB. y: sources
C=. (m,.0),0 NB. m: costs
B=. 1+>./,C NB. bigger than biggest cost
mincost=. <./@-.&0 NB. smallest non-zero cost
penalty=. |@(B * 2 -/@{. /:~ -. 0:)"1 - mincost"1
R=. C*0
while. 0 < +/D,S do.
pS=. penalty C
pD=. penalty |:C
if. pS >&(>./) pD do.
row=. (i. >./) pS
col=. (i. mincost) row { C
else.
col=. (i. >./) pD
row=. (i. mincost) col {"1 C
end.
n=. (row{S) <. col{D
S=. (n-~row{S) row} S
D=. (n-~col{D) col} D
C=. C * S *&*/ D
R=. n (<row,col)} R
end.
_1 _1 }. R
) |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #Action.21 | Action! | PROC GetFileName(CHAR ARRAY line,fname)
BYTE i,len
len=0
i=3
FOR i=3 TO 10
DO
IF line(i)=32 THEN EXIT FI
len==+1
fname(len)=line(i)
OD
len==+1
fname(len)='.
FOR i=11 TO 13
DO
IF line(i)=32 THEN EXIT FI
len==+1
fname(len)=line(i)
OD
fname(0)=len
RETURN
PROC Dir(CHAR ARRAY filter)
CHAR ARRAY line(255),fname(255)
BYTE dev=[1]
PrintE(filter)
Close(dev)
Open(dev,filter,6)
DO
InputSD(dev,line)
IF line(0)=0 OR line(0)>0 AND line(1)#32 THEN
EXIT
FI
GetFileName(line,fname)
Put(32) PrintE(fname)
OD
Close(dev)
PutE()
RETURN
PROC Main()
Dir("D:*.*")
Dir("H1:X*.*")
Dir("H1:?????.ACT")
Dir("H1:??F*.*")
RETURN |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #Ada | Ada | with Ada.Directories; use Ada.Directories;
with Ada.Text_IO; use Ada.Text_IO;
procedure Walk_Directory
(Directory : in String := ".";
Pattern : in String := "") -- empty pattern = all file names/subdirectory names
is
Search : Search_Type;
Dir_Ent : Directory_Entry_Type;
begin
Start_Search (Search, Directory, Pattern);
while More_Entries (Search) loop
Get_Next_Entry (Search, Dir_Ent);
Put_Line (Simple_Name (Dir_Ent));
end loop;
End_Search (Search);
end Walk_Directory; |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #Java | Java | import java.util.Arrays;
import static java.util.Arrays.stream;
import java.util.concurrent.*;
public class VogelsApproximationMethod {
final static int[] demand = {30, 20, 70, 30, 60};
final static int[] supply = {50, 60, 50, 50};
final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15},
{19, 19, 20, 23, 50}, {50, 12, 50, 15, 11}};
final static int nRows = supply.length;
final static int nCols = demand.length;
static boolean[] rowDone = new boolean[nRows];
static boolean[] colDone = new boolean[nCols];
static int[][] result = new int[nRows][nCols];
static ExecutorService es = Executors.newFixedThreadPool(2);
public static void main(String[] args) throws Exception {
int supplyLeft = stream(supply).sum();
int totalCost = 0;
while (supplyLeft > 0) {
int[] cell = nextCell();
int r = cell[0];
int c = cell[1];
int quantity = Math.min(demand[c], supply[r]);
demand[c] -= quantity;
if (demand[c] == 0)
colDone[c] = true;
supply[r] -= quantity;
if (supply[r] == 0)
rowDone[r] = true;
result[r][c] = quantity;
supplyLeft -= quantity;
totalCost += quantity * costs[r][c];
}
stream(result).forEach(a -> System.out.println(Arrays.toString(a)));
System.out.println("Total cost: " + totalCost);
es.shutdown();
}
static int[] nextCell() throws Exception {
Future<int[]> f1 = es.submit(() -> maxPenalty(nRows, nCols, true));
Future<int[]> f2 = es.submit(() -> maxPenalty(nCols, nRows, false));
int[] res1 = f1.get();
int[] res2 = f2.get();
if (res1[3] == res2[3])
return res1[2] < res2[2] ? res1 : res2;
return (res1[3] > res2[3]) ? res2 : res1;
}
static int[] diff(int j, int len, boolean isRow) {
int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
int minP = -1;
for (int i = 0; i < len; i++) {
if (isRow ? colDone[i] : rowDone[i])
continue;
int c = isRow ? costs[j][i] : costs[i][j];
if (c < min1) {
min2 = min1;
min1 = c;
minP = i;
} else if (c < min2)
min2 = c;
}
return new int[]{min2 - min1, min1, minP};
}
static int[] maxPenalty(int len1, int len2, boolean isRow) {
int md = Integer.MIN_VALUE;
int pc = -1, pm = -1, mc = -1;
for (int i = 0; i < len1; i++) {
if (isRow ? rowDone[i] : colDone[i])
continue;
int[] res = diff(i, len2, isRow);
if (res[0] > md) {
md = res[0]; // max diff
pm = i; // pos of max diff
mc = res[1]; // min cost
pc = res[2]; // pos of min cost
}
}
return isRow ? new int[]{pm, pc, mc, md} : new int[]{pc, pm, mc, md};
}
} |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #ALGOL_68 | ALGOL 68 | INT match=0, no match=1, out of memory error=2, other error=3;
[]STRING directory = get directory(".");
FOR file index TO UPB directory DO
STRING file = directory[file index];
IF grep in string("[Ss]ort*.[.]a68$", file, NIL, NIL) = match THEN
print((file, new line))
FI
OD |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #AppleScript | AppleScript | tell application "Finder" to return name of every item in (startup disk)
--> EXAMPLE RESULT: {"Applications", "Developer", "Library", "System", "Users"} |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #Julia | Julia |
immutable TProblem{T<:Integer,U<:String}
sd::Array{Array{T,1},1}
toc::Array{T,2}
labels::Array{Array{U,1},1}
tsort::Array{Array{T,2}, 1}
end
function TProblem{T<:Integer,U<:String}(s::Array{T,1},
d::Array{T,1},
toc::Array{T,2},
slab::Array{U,1},
dlab::Array{U,1})
scnt = length(s)
dcnt = length(d)
size(toc) = (scnt,dcnt) || error("Supply, Demand, TOC Size Mismatch")
length(slab) == scnt || error("Supply Label Size Labels")
length(dlab) == dcnt || error("Demand Label Size Labels")
0 <= minimum(s) || error("Negative Supply Value")
0 <= minimum(d) || error("Negative Demand Value")
sd = Array{T,1}[]
push!(sd, s)
push!(sd, d)
labels = Array{U,1}[]
push!(labels, slab)
push!(labels, dlab)
tsort = Array{T,2}[]
push!(tsort, mapslices(sortperm, toc, 2))
push!(tsort, mapslices(sortperm, toc, 1))
TProblem(sd, toc, labels, tsort)
end
isbalanced(tp::TProblem) = sum(tp.sd[1]) == sum(tp.sd[2])
type Resource{T<:Integer}
dim::T
i::T
quant::T
l::T
m::T
p::T
q::T
end
function Resource{T<:Integer}(dim::T, i::T, quant::T)
zed = zero(T)
Resource(dim, i, quant, zed, zed, zed, zed)
end
isavailable(r::Resource) = 0 < r.quant
Base.isless(a::Resource, b::Resource) = a.p < b.p || (a.p == b.p && b.q < a.q)
|
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #Arturo | Arturo | ; list all files at current path
print list "."
; get all files at given path
; and select only the ones we want
; just select the files with .md extension
select list "some/path"
=> [".md" = extract.extension]
; just select the files that contain "test"
select list "some/path"
=> [in? "test"] |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #AutoHotkey | AutoHotkey | Loop, %A_WinDir%\*.ini
out .= A_LoopFileName "`n"
MsgBox,% out |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #Kotlin | Kotlin | // version 1.1.3
val supply = intArrayOf(50, 60, 50, 50)
val demand = intArrayOf(30, 20, 70, 30, 60)
val costs = arrayOf(
intArrayOf(16, 16, 13, 22, 17),
intArrayOf(14, 14, 13, 19, 15),
intArrayOf(19, 19, 20, 23, 50),
intArrayOf(50, 12, 50, 15, 11)
)
val nRows = supply.size
val nCols = demand.size
val rowDone = BooleanArray(nRows)
val colDone = BooleanArray(nCols)
val results = Array(nRows) { IntArray(nCols) }
fun nextCell(): IntArray {
val res1 = maxPenalty(nRows, nCols, true)
val res2 = maxPenalty(nCols, nRows, false)
if (res1[3] == res2[3])
return if (res1[2] < res2[2]) res1 else res2
return if (res1[3] > res2[3]) res2 else res1
}
fun diff(j: Int, len: Int, isRow: Boolean): IntArray {
var min1 = Int.MAX_VALUE
var min2 = min1
var minP = -1
for (i in 0 until len) {
val done = if (isRow) colDone[i] else rowDone[i]
if (done) continue
val c = if (isRow) costs[j][i] else costs[i][j]
if (c < min1) {
min2 = min1
min1 = c
minP = i
}
else if (c < min2) min2 = c
}
return intArrayOf(min2 - min1, min1, minP)
}
fun maxPenalty(len1: Int, len2: Int, isRow: Boolean): IntArray {
var md = Int.MIN_VALUE
var pc = -1
var pm = -1
var mc = -1
for (i in 0 until len1) {
val done = if (isRow) rowDone[i] else colDone[i]
if (done) continue
val res = diff(i, len2, isRow)
if (res[0] > md) {
md = res[0] // max diff
pm = i // pos of max diff
mc = res[1] // min cost
pc = res[2] // pos of min cost
}
}
return if (isRow) intArrayOf(pm, pc, mc, md) else
intArrayOf(pc, pm, mc, md)
}
fun main(args: Array<String>) {
var supplyLeft = supply.sum()
var totalCost = 0
while (supplyLeft > 0) {
val cell = nextCell()
val r = cell[0]
val c = cell[1]
val q = minOf(demand[c], supply[r])
demand[c] -= q
if (demand[c] == 0) colDone[c] = true
supply[r] -= q
if (supply[r] == 0) rowDone[r] = true
results[r][c] = q
supplyLeft -= q
totalCost += q * costs[r][c]
}
println(" A B C D E")
for ((i, result) in results.withIndex()) {
print(('W'.toInt() + i).toChar())
for (item in result) print(" %2d".format(item))
println()
}
println("\nTotal Cost = $totalCost")
} |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #BaCon | BaCon | PRINT WALK$(".", 1, ".+", FALSE, NL$) |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #BASIC | BASIC | DECLARE SUB show (pattern AS STRING)
show "*.*"
SUB show (pattern AS STRING)
DIM f AS STRING
f = DIR$(pattern)
DO WHILE LEN(f)
PRINT f
f = DIR$
LOOP
END SUB |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #Lua | Lua | function initArray(n,v)
local tbl = {}
for i=1,n do
table.insert(tbl,v)
end
return tbl
end
function initArray2(m,n,v)
local tbl = {}
for i=1,m do
table.insert(tbl,initArray(n,v))
end
return tbl
end
supply = {50, 60, 50, 50}
demand = {30, 20, 70, 30, 60}
costs = {
{16, 16, 13, 22, 17},
{14, 14, 13, 19, 15},
{19, 19, 20, 23, 50},
{50, 12, 50, 15, 11}
}
nRows = table.getn(supply)
nCols = table.getn(demand)
rowDone = initArray(nRows, false)
colDone = initArray(nCols, false)
results = initArray2(nRows, nCols, 0)
function diff(j,le,isRow)
local min1 = 100000000
local min2 = min1
local minP = -1
for i=1,le do
local done = false
if isRow then
done = colDone[i]
else
done = rowDone[i]
end
if not done then
local c = 0
if isRow then
c = costs[j][i]
else
c = costs[i][j]
end
if c < min1 then
min2 = min1
min1 = c
minP = i
elseif c < min2 then
min2 = c
end
end
end
return {min2 - min1, min1, minP}
end
function maxPenalty(len1,len2,isRow)
local md = -100000000
local pc = -1
local pm = -1
local mc = -1
for i=1,len1 do
local done = false
if isRow then
done = rowDone[i]
else
done = colDone[i]
end
if not done then
local res = diff(i, len2, isRow)
if res[1] > md then
md = res[1] -- max diff
pm = i -- pos of max diff
mc = res[2] -- min cost
pc = res[3] -- pos of min cost
end
end
end
if isRow then
return {pm, pc, mc, md}
else
return {pc, pm, mc, md}
end
end
function nextCell()
local res1 = maxPenalty(nRows, nCols, true)
local res2 = maxPenalty(nCols, nRows, false)
if res1[4] == res2[4] then
if res1[3] < res2[3] then
return res1
else
return res2
end
else
if res1[4] > res2[4] then
return res2
else
return res1
end
end
end
function main()
local supplyLeft = 0
for i,v in pairs(supply) do
supplyLeft = supplyLeft + v
end
local totalCost = 0
while supplyLeft > 0 do
local cell = nextCell()
local r = cell[1]
local c = cell[2]
local q = math.min(demand[c], supply[r])
demand[c] = demand[c] - q
if demand[c] == 0 then
colDone[c] = true
end
supply[r] = supply[r] - q
if supply[r] == 0 then
rowDone[r] = true
end
results[r][c] = q
supplyLeft = supplyLeft - q
totalCost = totalCost + q * costs[r][c]
end
print(" A B C D E")
local labels = {'W','X','Y','Z'}
for i,r in pairs(results) do
io.write(labels[i])
for j,c in pairs(r) do
io.write(string.format(" %2d", c))
end
print()
end
print("Total Cost = " .. totalCost)
end
main() |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #BASIC256 | BASIC256 | call show ("c:\")
end
subroutine show (pattern$)
f$ = dir(pattern$)
while length(f$)
print f$
f$ = dir
end while
end subroutine |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #Batch_File | Batch File | dir /b "%windir%\system32\*.exe" |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #Nim | Nim | import math, sequtils, strutils
var
supply = [50, 60, 50, 50]
demand = [30, 20, 70, 30, 60]
let
costs = [[16, 16, 13, 22, 17],
[14, 14, 13, 19, 15],
[19, 19, 20, 23, 50],
[50, 12, 50, 15, 11]]
nRows = supply.len
nCols = demand.len
var
rowDone = newSeq[bool](nRows)
colDone = newSeq[bool](nCols)
results = newSeqWith(nRows, newSeq[int](nCols))
proc diff(j, len: int; isRow: bool): array[3, int] =
var min1, min2 = int.high
var minP = -1
for i in 0..<len:
let done = if isRow: colDone[i] else: rowDone[i]
if done: continue
let c = if isRow: costs[j][i] else: costs[i][j]
if c < min1:
min2 = min1
min1 = c
minP = i
elif c < min2:
min2 = c
result = [min2 - min1, min1, minP]
proc maxPenalty(len1, len2: int; isRow: bool): array[4, int] =
var md = int.low
var pc, pm, mc = -1
for i in 0..<len1:
let done = if isRow: rowDone[i] else: colDone[i]
if done: continue
let res = diff(i, len2, isRow)
if res[0] > md:
md = res[0] # max diff
pm = i # pos of max diff
mc = res[1] # min cost
pc = res[2] # pos of min cost
result = if isRow: [pm, pc, mc, md] else: [pc, pm, mc, md]
proc nextCell(): array[4, int] =
let res1 = maxPenalty(nRows, nCols, true)
let res2 = maxPenalty(nCols, nRows, false)
if res1[3] == res2[3]:
return if res1[2] < res2[2]: res1 else: res2
result = if res1[3] > res2[3]: res2 else: res1
when isMainModule:
var supplyLeft = sum(supply)
var totalCost = 0
while supplyLeft > 0:
let cell = nextCell()
let r = cell[0]
let c = cell[1]
let q = min(demand[c], supply[r])
dec demand[c], q
if demand[c] == 0: colDone[c] = true
dec supply[r], q
if supply[r] == 0: rowDone[r] = true
results[r][c] = q
dec supplyLeft, q
inc totalCost, q * costs[r][c]
echo " A B C D E"
for i, result in results:
stdout.write chr(i + ord('W'))
for item in result:
stdout.write " ", ($item).align(2)
echo()
echo "\nTotal cost = ", totalCost |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #BBC_BASIC | BBC BASIC | directory$ = "C:\Windows\"
pattern$ = "*.ini"
PROClistdir(directory$ + pattern$)
END
DEF PROClistdir(afsp$)
LOCAL dir%, sh%, res%
DIM dir% LOCAL 317
SYS "FindFirstFile", afsp$, dir% TO sh%
IF sh% <> -1 THEN
REPEAT
PRINT $$(dir%+44)
SYS "FindNextFile", sh%, dir% TO res%
UNTIL res% = 0
SYS "FindClose", sh%
ENDIF
ENDPROC |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #C | C | #include <sys/types.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>
enum {
WALK_OK = 0,
WALK_BADPATTERN,
WALK_BADOPEN,
};
int walker(const char *dir, const char *pattern)
{
struct dirent *entry;
regex_t reg;
DIR *d;
if (regcomp(®, pattern, REG_EXTENDED | REG_NOSUB))
return WALK_BADPATTERN;
if (!(d = opendir(dir)))
return WALK_BADOPEN;
while (entry = readdir(d))
if (!regexec(®, entry->d_name, 0, NULL, 0))
puts(entry->d_name);
closedir(d);
regfree(®);
return WALK_OK;
}
int main()
{
walker(".", ".\\.c$");
return 0;
} |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #Perl | Perl | #!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Vogel%27s_approximation_method
use warnings;
use List::AllUtils qw( max_by nsort_by min );
my $data = <<END;
A=30 B=20 C=70 D=30 E=60
W=50 X=60 Y=50 Z=50
AW=16 BW=16 CW=13 DW=22 EW=17
AX=14 BX=14 CX=13 DX=19 EX=15
AY=19 BY=19 CY=20 DY=23 EY=50
AZ=50 BZ=12 CZ=50 DZ=15 EZ=11
END
my $table = sprintf +('%4s' x 6 . "\n") x 5,
map {my $t = $_; map "$_$t", '', 'A' .. 'E' } '' , 'W' .. 'Z';
my ($cost, %assign) = (0);
while( $data =~ /\b\w=\d/ )
{
my @penalty;
for ( $data =~ /\b(\w)=\d/g )
{
my @all = map /(\d+)/, nsort_by { /\d+/ && $& }
grep { my ($t, $c) = /(.)(.)=/; $data =~ /\b$c=\d/ and $data =~ /\b$t=\d/ }
$data =~ /$_\w=\d+|\w$_=\d+/g;
push @penalty, [ $_, ($all[1] // 0) - $all[0] ];
}
my $rc = (max_by { $_->[1] } nsort_by
{ my $x = $_->[0]; $data =~ /(?:$x\w|\w$x)=(\d+)/ && $1 } @penalty)->[0];
my @lowest = nsort_by { /\d+/ && $& }
grep { my ($t, $c) = /(.)(.)=/; $data =~ /\b$c=\d/ and $data =~ /\b$t=\d/ }
$data =~ /$rc\w=\d+|\w$rc=\d+/g;
my ($t, $c) = $lowest[0] =~ /(.)(.)/;
my $allocate = min $data =~ /\b[$t$c]=(\d+)/g;
$table =~ s/$t$c/ sprintf "%2d", $allocate/e;
$cost += $data =~ /$t$c=(\d+)/ && $1 * $allocate;
$data =~ s/\b$_=\K\d+/ $& - $allocate || '' /e for $t, $c;
}
print "cost $cost\n\n", $table =~ s/[A-Z]{2}/--/gr; |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #C.23 | C# | using System;
using System.IO;
namespace DirectoryWalk
{
class Program
{
static void Main(string[] args)
{
string[] filePaths = Directory.GetFiles(@"c:\MyDir", "a*");
foreach (string filename in filePaths)
Console.WriteLine(filename);
}
}
}
|
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #C.2B.2B | C++ | #include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>
using namespace boost::filesystem;
int main()
{
path current_dir(".");
// list all files starting with a
boost::regex pattern("a.*");
for (directory_iterator iter(current_dir), end;
iter != end;
++iter)
{
boost::smatch match;
std::string fn = iter->path().filename().string(); // must make local variable
if (boost::regex_match( fn, match, pattern))
{
std::cout << match[0] << "\n";
}
}
} |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #Phix | Phix | with javascript_semantics
sequence supply = {50,60,50,50},
demand = {30,20,70,30,60},
costs = {{16,16,13,22,17},
{14,14,13,19,15},
{19,19,20,23,50},
{50,12,50,15,11}}
sequence row_done = repeat(false,length(supply)),
col_done = repeat(false,length(demand))
function diff(integer j, leng, bool is_row)
integer min1 = #3FFFFFFF, min2 = min1, min_p = -1
for i=1 to leng do
if not iff(is_row?col_done:row_done)[i] then
integer c = iff(is_row?costs[j,i]:costs[i,j])
if c<min1 then
min2 = min1
min1 = c
min_p = i
elsif c<min2 then
min2 = c
end if
end if
end for
return {min2-min1,min1,min_p,j}
end function
function max_penalty(integer len1, len2, bool is_row)
integer pc = -1, pm = -1, mc = -1, md = -#3FFFFFFF
for i=1 to len1 do
if not iff(is_row?row_done:col_done)[i] then
sequence res2 = diff(i, len2, is_row)
if res2[1]>md then
{md,mc,pc,pm} = res2
end if
end if
end for
return {md,mc}&iff(is_row?{pm,pc}:{pc,pm})
end function
integer supply_left = sum(supply),
total_cost = 0
sequence results = repeat(repeat(0,length(demand)),length(supply))
while supply_left>0 do
sequence cell = min(max_penalty(length(supply), length(demand), true),
max_penalty(length(demand), length(supply), false))
integer {{},{},r,c} = cell,
q = min(demand[c], supply[r])
demand[c] -= q
col_done[c] = (demand[c]==0)
supply[r] -= q
row_done[r] = (supply[r]==0)
results[r, c] = q
supply_left -= q
total_cost += q * costs[r, c]
end while
printf(1," A B C D E\n")
for i=1 to length(supply) do
printf(1,"%c ",'Z'-length(supply)+i)
for j=1 to length(demand) do
printf(1,"%4d",results[i,j])
end for
printf(1,"\n")
end for
printf(1,"\nTotal cost = %d\n", total_cost)
|
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #Clojure | Clojure | (import java.nio.file.FileSystems)
(defn match-files [f pattern]
(.matches (.getPathMatcher (FileSystems/getDefault) (str "glob:*" pattern)) (.toPath f)))
(defn walk-directory [dir pattern]
(let [directory (clojure.java.io/file dir)]
(map #(.getPath %) (filter #(match-files % pattern) (.listFiles directory)))))
|
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #ColdFusion | ColdFusion | <cfdirectory action="list" directory="C:\temp" filter="*.html" name="dirListing">
<cfoutput query="dirListing">
#dirListing.name# (#dirListing.type#)<br>
</cfoutput> |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #Python | Python | from collections import defaultdict
costs = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},
'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},
'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},
'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}
demand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60}
cols = sorted(demand.iterkeys())
supply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50}
res = dict((k, defaultdict(int)) for k in costs)
g = {}
for x in supply:
g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g])
for x in demand:
g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x])
while g:
d = {}
for x in demand:
d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x]
s = {}
for x in supply:
s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]]
f = max(d, key=lambda n: d[n])
t = max(s, key=lambda n: s[n])
t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t)
v = min(supply[f], demand[t])
res[f][t] += v
demand[t] -= v
if demand[t] == 0:
for k, n in supply.iteritems():
if n != 0:
g[k].remove(t)
del g[t]
del demand[t]
supply[f] -= v
if supply[f] == 0:
for k, n in demand.iteritems():
if n != 0:
g[k].remove(f)
del g[f]
del supply[f]
for n in cols:
print "\t", n,
print
cost = 0
for g in sorted(costs):
print g, "\t",
for n in cols:
y = res[g][n]
if y != 0:
print y,
cost += y * costs[g][n]
print "\t",
print
print "\n\nTotal Cost = ", cost |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #Common_Lisp | Common Lisp | (defun walk-directory (directory pattern)
(directory (merge-pathnames pattern directory))) |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #D | D | void main() {
import std.stdio, std.file;
dirEntries(".", "*.*", SpanMode.shallow).writeln;
} |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ██ 9 ██
8 ██ 8 ██
7 ██ ██ 7 ██≈≈≈≈≈≈≈≈██
6 ██ ██ ██ 6 ██≈≈██≈≈≈≈██
5 ██ ██ ██ ████ 5 ██≈≈██≈≈██≈≈████
4 ██ ██ ████████ 4 ██≈≈██≈≈████████
3 ██████ ████████ 3 ██████≈≈████████
2 ████████████████ ██ 2 ████████████████≈≈██
1 ████████████████████ 1 ████████████████████
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem – a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #11l | 11l | F water_collected(tower)
V l = tower.len
V highest_left = [0] [+] (1 .< l).map(n -> max(@tower[0 .< n]))
V highest_right = (1 .< l).map(n -> max(@tower[n .< @l])) [+] [0]
V water_level = (0 .< l).map(n -> max(min(@highest_left[n], @highest_right[n]) - @tower[n], 0))
print(‘highest_left: ’highest_left)
print(‘highest_right: ’highest_right)
print(‘water_level: ’water_level)
print(‘tower_level: ’tower)
print(‘total_water: ’sum(water_level))
print(‘’)
R sum(water_level)
V towers = [
[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
print(towers.map(tower -> water_collected(tower))) |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #Racket | Racket | #lang racket
(define-values (1st 2nd 3rd) (values first second third))
(define-syntax-rule (?: x t f) (if (zero? x) f t))
(define (hash-ref2
hsh# key-1 key-2
#:fail-2 (fail-2 (λ () (error 'hash-ref2 "key-2:~a is not found in hash" key-2)))
#:fail-1 (fail-1 (λ () (error 'hash-ref2 "key-1:~a is not found in hash" key-1))))
(hash-ref (hash-ref hsh# key-1 fail-1) key-2 fail-2))
(define (VAM costs all-supply all-demand)
(define (reduce-g/x g/x x#-- x x-v y y-v)
(for/fold ((rv (?: x-v g/x (hash-remove g/x x))))
(#:when (zero? y-v) ((k n) (in-hash x#--)) #:unless (zero? n))
(hash-update rv k (curry remove y))))
(define (cheapest-candidate/tie-break candidates)
(define cand-max3 (3rd (argmax 3rd candidates)))
(argmin 2nd (for/list ((cand candidates) #:when (= (3rd cand) cand-max3)) cand)))
(let vam-loop
((res (hash))
(supply all-supply)
(g/supply
(for/hash ((x (in-hash-keys all-supply)))
(define costs#x (hash-ref costs x))
(define key-fn (λ (g) (hash-ref costs#x g)))
(values x (sort (hash-keys costs#x) < #:key key-fn #:cache-keys? #t))))
(demand all-demand)
(g/demand
(for/hash ((x (in-hash-keys all-demand)))
(define key-fn (λ (g) (hash-ref2 costs g x)))
(values x (sort (hash-keys costs) < #:key key-fn #:cache-keys? #t)))))
(cond
[(and (hash-empty? supply) (hash-empty? demand)) res]
[(or (hash-empty? supply) (hash-empty? demand)) (error 'VAM "Unbalanced supply / demand")]
[else
(define D
(let ((candidates
(for/list ((x (in-hash-keys demand)))
(match-define (hash-table ((== x) (and g#x (list g#x.0 _ ...))) _ ...) g/demand)
(define z (hash-ref2 costs g#x.0 x))
(match g#x
[(list _ g#x.1 _ ...) (list x z (- (hash-ref2 costs g#x.1 x) z))]
[(list _) (list x z z)]))))
(cheapest-candidate/tie-break candidates)))
(define S
(let ((candidates
(for/list ((x (in-hash-keys supply)))
(match-define (hash-table ((== x) (and g#x (list g#x.0 _ ...))) _ ...) g/supply)
(define z (hash-ref2 costs x g#x.0))
(match g#x
[(list _ g#x.1 _ ...) (list x z (- (hash-ref2 costs x g#x.1) z))]
[(list _) (list x z z)]))))
(cheapest-candidate/tie-break candidates)))
(define-values (d s)
(let ((t>f? (if (= (3rd D) (3rd S)) (> (2nd S) (2nd D)) (> (3rd D) (3rd S)))))
(if t>f? (values (1st D) (1st (hash-ref g/demand (1st D))))
(values (1st (hash-ref g/supply (1st S))) (1st S)))))
(define v (min (hash-ref supply s) (hash-ref demand d)))
(define d-v (- (hash-ref demand d) v))
(define s-v (- (hash-ref supply s) v))
(define demand-- (?: d-v (hash-set demand d d-v) (hash-remove demand d)))
(define supply-- (?: s-v (hash-set supply s s-v) (hash-remove supply s)))
(vam-loop
(hash-update res s (λ (h) (hash-update h d (λ (x) (+ v x)) 0)) hash)
supply-- (reduce-g/x g/supply supply-- s s-v d d-v)
demand-- (reduce-g/x g/demand demand-- d d-v s s-v))])))
(define (vam-solution-cost costs demand?cols solution)
(match demand?cols
[(? list? demand-cols)
(for*/sum ((g (in-hash-keys costs)) (n (in-list demand-cols)))
(* (hash-ref2 solution g n #:fail-2 0) (hash-ref2 costs g n)))]
[(hash-table (ks _) ...) (vam-solution-cost costs (sort ks symbol<? solution))]))
(define (describe-VAM-solution costs demand sltn)
(define demand-cols (sort (hash-keys demand) symbol<?))
(string-join
(map
(curryr string-join "\t")
`(,(map ~a (cons "" demand-cols))
,@(for/list ((g (in-hash-keys costs)))
(cons (~a g) (for/list ((c demand-cols)) (~a (hash-ref2 sltn g c #:fail-2 "-")))))
()
("Total Cost:" ,(~a (vam-solution-cost costs demand-cols sltn)))))
"\n"))
;; --------------------------------------------------------------------------------------------------
(let ((COSTS (hash 'W (hash 'A 16 'B 16 'C 13 'D 22 'E 17)
'X (hash 'A 14 'B 14 'C 13 'D 19 'E 15)
'Y (hash 'A 19 'B 19 'C 20 'D 23 'E 50)
'Z (hash 'A 50 'B 12 'C 50 'D 15 'E 11)))
(DEMAND (hash 'A 30 'B 20 'C 70 'D 30 'E 60))
(SUPPLY (hash 'W 50 'X 60 'Y 50 'Z 50)))
(displayln (describe-VAM-solution COSTS DEMAND (VAM COSTS SUPPLY DEMAND)))) |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #DCL | DCL | * matches any number of characters
& matches exactly any one character |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #Delphi | Delphi |
program Walk_a_directory;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.IOUtils;
var
Files: TArray<string>;
FileName, Directory: string;
begin
Directory := TDirectory.GetCurrentDirectory; // dir = '.', work to
Files := TDirectory.GetFiles(Directory, '*.*');
for FileName in Files do
begin
Writeln(FileName);
end;
Readln;
end.
|
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ██ 9 ██
8 ██ 8 ██
7 ██ ██ 7 ██≈≈≈≈≈≈≈≈██
6 ██ ██ ██ 6 ██≈≈██≈≈≈≈██
5 ██ ██ ██ ████ 5 ██≈≈██≈≈██≈≈████
4 ██ ██ ████████ 4 ██≈≈██≈≈████████
3 ██████ ████████ 3 ██████≈≈████████
2 ████████████████ ██ 2 ████████████████≈≈██
1 ████████████████████ 1 ████████████████████
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem – a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #8080_Assembly | 8080 Assembly | org 100h
jmp demo
;;; Calculate the amount of water a row of towers will hold
;;; Note: this will destroy the input array.
;;; Input: DE = tower array, BC = length of array
;;; Output: A = amount of water
water: xra a ; Start with no water
sta w_out+1
wscanr: mov h,d ; HL = right edge
mov l,e
dad b
wscrlp: dcx h
call cmp16 ; Reached beginning?
jnc w_out ; Then stop
mov a,m ; Otherwise, if current tower is zero
ora a
jz wscrlp ; Then keep scanning
push b ; Keep length
push d ; Keep array begin
mvi b,0 ; No blocks yet
xchg ; HL = left scanning edge, DE = right
wscanl: mov a,m ; Get current column
ora a ; Is zero?
jz wunit ; Then see if an unit of water must be added
dcr m ; Otherwise, decrease column
inr b ; Increase blocks
jmp wnext
wunit: mov a,b ; Any blocks?
ora a
jz wnext
lda w_out+1 ; If so, add water
inr a
sta w_out+1
wnext: inx h ; Next column
call cmp16
jnc wscanl ; Until right edge reached
mov a,b
cmc ; Check if more than 1 block left
rar
ora a
pop d ; Restore array begin
pop b ; and length
jnz wscanr ; If more than 1 block, keep scanning
w_out: mvi a,0 ; Load water into A
ret
;;; 16-bit compare DE to HL
cmp16: mov a,d
cmp h
rnz
mov a,e
cmp l
ret
;;; Calculate and print the amount of water for each input
demo: lxi h,series
load: mov e,m ; Load pointer
inx h
mov d,m
inx h
mov c,m ; Load length
inx h
mov b,m
inx h
mov a,d ; If pointer is zero,
ora e
rz ; stop.
push h ; Otherwise, save the series pointer
call water ; Calculate amount of water
call printa ; Output amount of water
pop h ; Restore series pointer
jmp load ; Load next example
;;; Print A as integer value
printa: lxi d,num ; Pointer to number string
mvi c,10 ; Divisor
digit: mvi b,-1 ; Quotient
dloop: inr b ; Divide (by trial subtraction)
sub c
jnc dloop
adi '0'+10 ; ASCII digit from remainder
dcx d ; Store ASCII digit
stax d
mov a,b ; Continue with quotient
ana a ; If not zero
jnz digit
mvi c,9 ; 9 = CP/M print string syscall
jmp 5 ; Print number string
db '***' ; Output number placeholder
num: db ' $'
;;; Series
t1: db 1,5,3,7,2
t2: db 5,3,7,2,6,4,5,9,1,2
t3: db 2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1
t4: db 5,5,5,5
t5: db 5,6,7,8
t6: db 8,7,7,6
t7: db 6,7,10,7,6
t_end: equ $
;;; Lengths and pointers
series: dw t1,t2-t1
dw t2,t3-t2
dw t3,t4-t3
dw t4,t5-t4
dw t5,t6-t5
dw t6,t7-t6
dw t7,t_end-t7
dw 0 |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #AutoHotkey | AutoHotkey | ;------------------------------------------------------------------------
Gui, 1: +E0x20 +Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs
Gui, 1: Show, NA
hwnd1 := WinExist()
OnExit, Exit
If !pToken := Gdip_Startup()
{
MsgBox, 48, gdiplus error!, Gdiplus failed to start. Please ensure you have gdiplus on your system
ExitApp
}
Width :=1400, Height := 1050
hbm := CreateDIBSection(Width, Height)
hdc := CreateCompatibleDC()
obm := SelectObject(hdc, hbm)
G := Gdip_GraphicsFromHDC(hdc)
Gdip_SetSmoothingMode(G, 4)
;------------------------------------------------------------------------
w := 300, h := 200
xmin := A_ScreenWidth/2-w/2 , xmax := A_ScreenWidth/2+w/2
ymin := A_ScreenHeight/2-h/2 , ymax := A_ScreenHeight/2+h/2
colors := ["C0C0C0","808080","FFFFFF","800000","FF0000","800080","FF00FF","008000"
,"00FF00","808000","FFFF00","000080","0000FF","008080","00FFFF"]
site := []
loop, 15
{
Random, x, % xmin, % xmax
Random, y, % ymin, % ymax
site[A_Index, "x"] := x
site[A_Index, "y"] := y
}
y:= ymin
while (y<=ymax)
{
x:=xmin
while (x<=xmax)
{
distance := []
for S, coord in site
distance[dist(x, y, coord.x, coord.y)] := S
CS := Closest_Site(distance)
pBrush := Gdip_BrushCreateSolid("0xFF" . colors[CS])
Gdip_FillEllipse(G, pBrush, x, y, 2, 2)
x++
}
UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)
y++
}
pBrush := Gdip_BrushCreateSolid(0xFF000000)
for S, coord in site
Gdip_FillEllipse(G, pBrush, coord.x, coord.y, 4, 4)
UpdateLayeredWindow(hwnd1, hdc, 0, 0, Width, Height)
;------------------------------------------------------------------------
Gdip_DeleteBrush(pBrush)
SelectObject(hdc, obm)
DeleteObject(hbm)
DeleteDC(hdc)
Gdip_DeleteGraphics(G)
return
;------------------------------------------------------------------------
Dist(x1,y1,x2,y2){
return Sqrt((x2-x1)**2 + (y2-y1)**2)
}
;------------------------------------------------------------------------
Closest_Site(distance){
for d, i in distance
if A_Index = 1
min := d, site := i
else
min := min < d ? min : d
, site := min < d ? site : i
return site
}
;------------------------------------------------------------------------
Exit:
Gdip_Shutdown(pToken)
ExitApp
Return
;------------------------------------------------------------------------ |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #Raku | Raku | my %costs =
:W{:16A, :16B, :13C, :22D, :17E},
:X{:14A, :14B, :13C, :19D, :15E},
:Y{:19A, :19B, :20C, :23D, :50E},
:Z{:50A, :12B, :50C, :15D, :11E};
my %demand = :30A, :20B, :70C, :30D, :60E;
my %supply = :50W, :60X, :50Y, :50Z;
my @cols = %demand.keys.sort;
my %res;
my %g = (|%supply.keys.map: -> $x { $x => [%costs{$x}.sort(*.value)».key]}),
(|%demand.keys.map: -> $x { $x => [%costs.keys.sort({%costs{$_}{$x}})]});
while (+%g) {
my @d = %demand.keys.map: -> $x
{[$x, my $z = %costs{%g{$x}[0]}{$x},%g{$x}[1] ?? %costs{%g{$x}[1]}{$x} - $z !! $z]}
my @s = %supply.keys.map: -> $x
{[$x, my $z = %costs{$x}{%g{$x}[0]},%g{$x}[1] ?? %costs{$x}{%g{$x}[1]} - $z !! $z]}
@d = |@d.grep({ (.[2] == max @d».[2]) }).&min: :by(*.[1]);
@s = |@s.grep({ (.[2] == max @s».[2]) }).&min: :by(*.[1]);
my ($t, $f) = @d[2] == @s[2] ?? (@s[1],@d[1]) !! (@d[2],@s[2]);
my ($d, $s) = $t > $f ?? (@d[0],%g{@d[0]}[0]) !! (%g{@s[0]}[0], @s[0]);
my $v = %supply{$s} min %demand{$d};
%res{$s}{$d} += $v;
%demand{$d} -= $v;
if (%demand{$d} == 0) {
%supply.grep( *.value != 0 )».key.map: -> $v
{ %g{$v}.splice((%g{$v}.first: * eq $d, :k),1) };
%g{$d}:delete;
%demand{$d}:delete;
}
%supply{$s} -= $v;
if (%supply{$s} == 0) {
%demand.grep( *.value != 0 )».key.map: -> $v
{ %g{$v}.splice((%g{$v}.first: * eq $s, :k),1) };
%g{$s}:delete;
%supply{$s}:delete;
}
}
say join "\t", flat '', @cols;
my $total;
for %costs.keys.sort -> $g {
print "$g\t";
for @cols -> $col {
print %res{$g}{$col} // '-', "\t";
$total += (%res{$g}{$col} // 0) * %costs{$g}{$col};
}
print "\n";
}
say "\nTotal cost: $total"; |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #E | E | def walkDirectory(directory, pattern) {
for name => file ? (name =~ rx`.*$pattern.*`) in directory {
println(name)
}
} |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #Elena | Elena | import system'io;
import system'routines;
import extensions'routines;
public program()
{
var dir := Directory.assign("c:\MyDir");
dir.getFiles("a.*").forEach:printingLn;
} |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ██ 9 ██
8 ██ 8 ██
7 ██ ██ 7 ██≈≈≈≈≈≈≈≈██
6 ██ ██ ██ 6 ██≈≈██≈≈≈≈██
5 ██ ██ ██ ████ 5 ██≈≈██≈≈██≈≈████
4 ██ ██ ████████ 4 ██≈≈██≈≈████████
3 ██████ ████████ 3 ██████≈≈████████
2 ████████████████ ██ 2 ████████████████≈≈██
1 ████████████████████ 1 ████████████████████
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem – a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #8086_Assembly | 8086 Assembly | cpu 8086
org 100h
section .text
jmp demo
;;; Calculate the amount of water a row of towers will hold
;;; Note: this will destroy the input array.
;;; Input: DX = tower array, CX = length of array
;;; Output: AX = amount of water
water: xor ax,ax ; Amount of water starts at zero
xor bx,bx ; BH = zero, BL = block count
.scanr: mov di,dx ; DI = right edge of towers
add di,cx
.rloop: dec di
cmp di,dx ; Reached beginning?
jl .out ; Then calculation is done.
cmp bh,[di] ; Otherwise, if the tower is zero,
je .rloop ; Keep scanning
xor bl,bl ; Set block count to zero
mov si,dx ; SI = left scanning edge
.scanl: cmp bh,[si] ; Is the column empty?
je .unit ; Then see whether to add an unit of water
dec byte [si] ; Otherwise, remove block from tower
inc bx ; And count it
jmp .next
.unit: test bl,bl ; Any blocks?
jz .next
inc ax ; If so, add unit of water
.next: inc si ; Scan rightward
cmp si,di ; Reached the right edge?
jbe .scanl ; If not, keep going
shr bl,1 ; If more than 1 block,
jnz .scanr ; Keep going
.out: ret
;;; Calculate and print the amount of water for each input
demo: mov si,series
.loop: lodsw ; Load pointer
test ax,ax ; If 0,
jz .done ; we're done.
xchg ax,dx
lodsw ; Load length
xchg ax,cx
push si ; Keep array pointer
call water ; Calculate amount of water
call prax ; Print AX
pop si ; Restore array pointer
jmp .loop
.done: ret
;;; Print AX as number
prax: mov bx,num ; Pointer to end of number string
mov cx,10 ; Divisor
.dgt: xor dx,dx ; Divide by 10
div cx
add dl,'0' ; Add ASCII 0 to remainder
dec bx ; Store digit
mov [bx],dl
test ax,ax ; If number not zero yet
jnz .dgt ; Find rest of digits
mov dx,bx ; Print number string
mov ah,9
int 21h
ret
section .data
db '*****' ; Output number placeholder
num: db ' $'
;;; Series
t1: db 1,5,3,7,2
t2: db 5,3,7,2,6,4,5,9,1,2
t3: db 2,6,3,5,2,8,1,4,2,2,5,3,5,7,4,1
t4: db 5,5,5,5
t5: db 5,6,7,8
t6: db 8,7,7,6
t7: db 6,7,10,7,6
t_end: equ $
;;; Lengths and pointers
series: dw t1,t2-t1
dw t2,t3-t2
dw t3,t4-t3
dw t4,t5-t4
dw t5,t6-t5
dw t6,t7-t6
dw t7,t_end-t7
dw 0 |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #BASIC256 | BASIC256 | global ancho, alto
ancho = 500 : alto = 500
clg
graphsize ancho, alto
function hypot(a, b)
return sqr(a^2+b^2)
end function
subroutine Generar_diagrama_Voronoi(ancho, alto, num_celdas)
dim nx(num_celdas+1)
dim ny(num_celdas+1)
dim nr(num_celdas+1)
dim ng(num_celdas+1)
dim nb(num_celdas+1)
for i = 0 to num_celdas
nx[i] = int(rand * ancho)
ny[i] = int(rand * alto)
nr[i] = int(rand * 256) + 1
ng[i] = int(rand * 256) + 1
nb[i] = int(rand * 256) + 1
next i
for y = 1 to alto
for x = 1 to ancho
dmin = hypot(ancho-1, alto-1)
j = -1
for i = 1 to num_celdas
d = hypot(nx[i]-x, ny[i]-y)
if d < dmin then dmin = d : j = i
next i
color rgb(nr[j], ng[j], nb[j])
plot (x, y)
next x
next y
end subroutine
call Generar_diagrama_Voronoi(ancho, alto, 25)
refresh
imgsave "Voronoi_diagram.jpg", "jpg"
end |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #REXX | REXX | /* REXX ***************************************************************
* Solve the Transportation Problem using Vogel's Approximation
Default Input
2 3 # of sources / # of demands
25 35 sources
20 30 10 demands
3 5 7 cost matrix <
3 2 5
* 20201210 support no input file -courtesy GS
* Note: correctness of input is not checked
* 20210102 restored Vogel's Approximation and added Optimization
* 20210103 eliminated debug code
**********************************************************************/
Signal On Halt
Signal On Novalue
Signal On Syntax
Parse Arg fid
If fid='' Then
fid='input1.txt'
Call init
m.=0
Do Forever
dmax.=0
dmax=0
Do r=1 To rr
dr.r=''
Do c=1 To cc
If cost.r.c<>'*' Then
dr.r=dr.r cost.r.c
End
dr.r=words(dr.r) dr.r
dr.r=diff(dr.r)
If dr.r>dmax Then Do; dmax=dr.r; dmax.0='R'; dmax.1=r; dmax.2=dr.r; End
End
Do c=1 To cc
dc.c=''
Do r=1 To rr
If cost.r.c<>'*' Then
dc.c=dc.c cost.r.c
End
dc.c=words(dc.c) dc.c
dc.c=diff(dc.c)
If dc.c>dmax Then Do; dmax=dc.c; dmax.0='C'; dmax.1=c; dmax.2=dc.c; End
End
cmin=999
Select
When dmax.0='R' Then Do
r=dmax.1
Do c=1 To cc
If cost.r.c<>'*' &,
cost.r.c<cmin Then Do
cmin=cost.r.c
cx=c
End
End
Call allocate r cx
End
When dmax.0='C' Then Do
c=dmax.1
Do r=1 To rr
If cost.r.c<>'*' &,
cost.r.c<cmin Then Do
cmin=cost.r.c
rx=r
End
End
Call allocate rx c
End
Otherwise
Leave
End
End
Do r=1 To rr
Do c=1 To cc
If cost.r.c<>'*' Then Do
Call allocate r c
cost.r.c='*'
End
End
End
Call show_alloc 'Vogel''s Approximation'
Do r=1 To rr
Do c=1 To cc
cost.r.c=word(matrix.r.c,3) /* restore cost.*.* */
End
End
Call steppingstone
Exit
/**********************************************************************
* Subroutines for Vogel's Approximation
**********************************************************************/
init:
If lines(fid)=0 Then Do
Say 'Input file not specified or not found. Using default input instead.'
fid='Default input'
in.1=sourceline(4)
Parse Var in.1 numSources .
Do i=2 To numSources+3
in.i=sourceline(i+3)
End
End
Else Do
Do i=1 By 1 while lines(fid)>0
in.i=linein(fid)
End
End
Parse Var in.1 numSources numDestinations . 1 rr cc .
source.=0
demand.=0
source_sum=0
Do i=1 To numSources
Parse Var in.2 source.i in.2
ss.i=source.i
source_in.i=source.i
source_sum=source_sum+source.i
End
l=linein(fid)
demand_sum=0
Do i=1 To numDestinations
Parse Var in.3 demand.i in.3
dd.i=demand.i
demand_in.i=demand.i
demand_sum=demand_sum+demand.i
End
Do i=1 To numSources
j=i+3
l=in.j
Do j=1 To numDestinations
Parse Var l cost.i.j l
End
End
Do i=1 To numSources
ol=format(source.i,3)
Do j=1 To numDestinations
ol=ol format(cost.i.j,4)
End
End
ol=' '
Do j=1 To numDestinations
ol=ol format(demand.j,4)
End
Select
When source_sum=demand_sum Then Nop /* balanced */
When source_sum>demand_sum Then Do /* unbalanced - add dummy demand */
Say 'This is an unbalanced case (sources exceed demands). We add a dummy consumer.'
cc=cc+1
demand.cc=source_sum-demand_sum
demand_in.cc=demand.cc
dd.cc=demand.cc
Do r=1 To rr
cost.r.cc=0
End
End
Otherwise /* demand_sum>source_sum */ Do /* unbalanced - add dummy source */
Say 'This is an unbalanced case (demands exceed sources). We add a dummy source.'
rr=rr+1
source.rr=demand_sum-source_sum
source_in.rr=source.rr
ss.rr=source.rr
Do c=1 To cc
cost.rr.c=0
End
End
End
Say 'Sources / Demands / Cost'
ol=' '
Do c=1 To cc
ol=ol format(demand.c,3)
End
Say ol
Do r=1 To rr
ol=format(source.r,4)
Do c=1 To cc
ol=ol format(cost.r.c,3)
matrix.r.c=r c cost.r.c 0
End
Say ol
End
Return
allocate: Procedure Expose m. source. demand. cost. rr cc matrix.
Parse Arg r c
sh=min(source.r,demand.c)
source.r=source.r-sh
demand.c=demand.c-sh
m.r.c=sh
matrix.r.c=subword(matrix.r.c,1,3) sh
If source.r=0 Then Do
Do c=1 To cc
cost.r.c='*'
End
End
If demand.c=0 Then Do
Do r=1 To rr
cost.r.c='*'
End
End
Return
diff: Procedure
Parse Value arg(1) With n list
If n<2 Then Return 0
list=wordsort(list)
Return word(list,2)-word(list,1)
wordsort: Procedure
/**********************************************************************
* Sort the list of words supplied as argument. Return the sorted list
**********************************************************************/
Parse Arg wl
wa.=''
wa.0=0
Do While wl<>''
Parse Var wl w wl
Do i=1 To wa.0
If wa.i>w Then Leave
End
If i<=wa.0 Then Do
Do j=wa.0 To i By -1
ii=j+1
wa.ii=wa.j
End
End
wa.i=w
wa.0=wa.0+1
End
swl=''
Do i=1 To wa.0
swl=swl wa.i
End
/* Say swl */
Return strip(swl)
show_alloc: Procedure Expose matrix. rr cc demand_in. source_in.
Parse Arg header
If header='' Then
Return
Say ''
Say header
total=0
ol=' '
Do c=1 to cc
ol=ol format(demand_in.c,3)
End
Say ol
as=''
Do r=1 to rr
ol=format(source_in.r,4)
a=word(matrix.r.1,4)
If a=0.0000000001 Then a=0
If a>0 Then
ol=ol format(a,3)
Else
ol=ol ' - '
total=total+word(matrix.r.1,4)*word(matrix.r.1,3)
Do c=2 To cc
a=word(matrix.r.c,4)
If a=0.0000000001 Then a=0
If a>0 Then
ol=ol format(a,3)
Else
ol=ol ' - '
total=total+word(matrix.r.c,4)*word(matrix.r.c,3)
as=as a
End
Say ol
End
Say 'Total costs:' format(total,4,1)
Return
/**********************************************************************
* Subroutines for Optimization
**********************************************************************/
steppingstone: Procedure Expose matrix. cost. rr cc matrix. demand_in.,
source_in. ms fid move cnt.
maxReduction=0
move=''
Call fixDegenerateCase
Do r=1 To rr
Do c=1 To cc
Parse Var matrix.r.c r c cost qrc
If qrc=0 Then Do
path=getclosedpath(r,c)
If pelems(path)<4 Then Do
Iterate
End
reduction = 0
lowestQuantity = 1e10
leavingCandidate = ''
plus=1
pathx=path
Do While pathx<>''
Parse Var pathx s '|' pathx
If plus Then
reduction=reduction+word(s,3)
Else Do
reduction=reduction-word(s,3)
If word(s,4)<lowestQuantity Then Do
leavingCandidate = s
lowestQuantity = word(s,4)
End
End
plus=\plus
End
If reduction < maxreduction Then Do
move=path
leaving=leavingCandidate
maxReduction = reduction
End
End
End
End
if move<>'' Then Do
quant=word(leaving,4)
If quant=0 Then Do
Call show_alloc 'Optimum'
Exit
End
plus=1
Do While move<>''
Parse Var move m '|' move
Parse Var m r c cpu qrc
Parse Var matrix.r.c vr vc vcost vquant
If plus Then
nquant=vquant+quant
Else
nquant=vquant-quant
matrix.r.c = vr vc vcost nquant
plus=\plus
End
move=''
Call steppingStone
End
Else
Call show_alloc 'Optimal Solution' fid
Return
getclosedpath: Procedure Expose matrix. cost. rr cc matrix.
Parse Arg rd,cd
path=rd cd cost.rd.cd word(matrix.rd.cd,4)
do r=1 To rr
Do c=1 To cc
If word(matrix.r.c,4)>0 Then Do
path=path'|'r c cost.r.c word(matrix.r.c,4)
End
End
End
path=magic(path)
Return stones(path)
magic: Procedure
Parse Arg list
Do Forever
list_1=remove_1(list)
If list_1=list Then Leave
list=list_1
End
Return list_1
remove_1: Procedure
Parse Arg list
cntr.=0
cntc.=0
Do i=1 By 1 While list<>''
parse Var list e.i '|' list
Parse Var e.i r c .
cntr.r=cntr.r+1
cntc.c=cntc.c+1
End
n=i-1
keep.=1
Do i=1 To n
Parse Var e.i r c .
If cntr.r<2 |,
cntc.c<2 Then Do
keep.i=0
End
End
list=e.1
Do i=2 To n
If keep.i Then
list=list'|'e.i
End
Return list
stones: Procedure
Parse Arg lst
tstc=lst
Do i=1 By 1 While tstc<>''
Parse Var tstc o.i '|' tstc
end
stones=lst
o.0=i-1
prev=o.1
Do i=1 To o.0
st.i=prev
k=i//2
nbrs=getNeighbors(prev,lst)
Parse Var nbrs n.1 '|' n.2
If k=0 Then
prev=n.2
Else
prev=n.1
End
stones=st.1
Do i=2 To o.0
stones=stones'|'st.i
End
Return stones
getNeighbors: Procedure Expose o.
parse Arg s, lst
Do i=1 To 4
Parse Var lst o.i '|' lst
End
nbrs.=''
sr=word(s,1)
sc=word(s,2)
Do i=1 To o.0
If o.i<>s Then Do
or=word(o.i,1)
oc=word(o.i,2)
If or=sr & nbrs.0='' Then
nbrs.0 = o.i
else if oc=sc & nbrs.1='' Then
nbrs.1 = o.i
If nbrs.0<>'' & nbrs.1<>'' Then
Leave
End
End
return nbrs.0'|'nbrs.1
m1: Procedure
Parse Arg z
Return z-1
pelems: Procedure
Call Trace 'O'
Parse Arg p
n=0
Do While p<>''
Parse Var p x '|' p
If x<>'' Then n=n+1
End
Return n
fixDegenerateCase: Procedure Expose matrix. rr cc ms
Call matrixtolist
If (rr+cc-1)<>ms Then Do
Do r=1 To rr
Do c=1 To cc
If word(matrix.r.c,4)=0 Then Do
matrix.r.c=subword(matrix.r.c,1,3) 1.e-10
Return
End
End
End
End
Return
matrixtolist: Procedure Expose matrix. rr cc ms
ms=0
list=''
Do r=1 To rr
Do c=1 To cc
If word(matrix.r.c,4)>0 Then Do
list=list'|'matrix.r.c
ms=ms+1
End
End
End
Return strip(list,,'|')
Novalue:
Say 'Novalue raised in line' sigl
Say sourceline(sigl)
Say 'Variable' condition('D')
Signal lookaround
Syntax:
Say 'Syntax raised in line' sigl
Say sourceline(sigl)
Say 'rc='rc '('errortext(rc)')'
halt:
lookaround:
If fore() Then Do
Say 'You can look around now.'
Trace ?R
Nop
End
Exit 12 |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #Elixir | Elixir | # current directory
IO.inspect File.ls!
dir = "/users/public"
IO.inspect File.ls!(dir) |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #Emacs_Lisp | Emacs Lisp | (directory-files "/some/dir/name"
nil ;; just the filenames, not full paths
"\\.c\\'" ;; regexp
t) ;; don't sort the filenames
;;=> ("foo.c" "bar.c" ...) |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ██ 9 ██
8 ██ 8 ██
7 ██ ██ 7 ██≈≈≈≈≈≈≈≈██
6 ██ ██ ██ 6 ██≈≈██≈≈≈≈██
5 ██ ██ ██ ████ 5 ██≈≈██≈≈██≈≈████
4 ██ ██ ████████ 4 ██≈≈██≈≈████████
3 ██████ ████████ 3 ██████≈≈████████
2 ████████████████ ██ 2 ████████████████≈≈██
1 ████████████████████ 1 ████████████████████
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem – a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #Action.21 | Action! | PROC PrintArray(BYTE ARRAY a BYTE len)
BYTE i
Put('[)
FOR i=0 TO len-1
DO
IF i>0 THEN
Put(32)
FI
PrintB(a(i))
OD
Put('])
RETURN
BYTE FUNC Max(BYTE ARRAY a BYTE start,stop)
BYTE i,res
res=0
FOR i=start TO stop
DO
IF a(i)>res THEN
res=a(i)
FI
OD
RETURN (res)
BYTE FUNC CalcWater(BYTE ARRAY a BYTE len)
BYTE water,i,maxL,maxR,lev
IF len<3 THEN
RETURN (0)
FI
water=0
FOR i=1 TO len-2
DO
maxL=Max(a,0,i-1)
maxR=Max(a,i+1,len-1)
IF maxL<maxR THEN
lev=maxL
ELSE
lev=maxR
FI
IF a(i)<lev THEN
water==+lev-a(i)
FI
OD
RETURN (water)
PROC Test(BYTE ARRAY a BYTE len)
BYTE water
water=CalcWater(a,len)
PrintArray(a,len)
PrintF(" holds %B water units%E%E",water)
RETURN
PROC Main()
DEFINE COUNT="7"
BYTE ARRAY
a1=[1 5 3 7 2],
a2=[5 3 7 2 6 4 5 9 1 2],
a3=[2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1],
a4=[5 5 5 5],
a5=[5 6 7 8],
a6=[8 7 7 6],
a7=[6 7 10 7 6]
Test(a1,5)
Test(a2,10)
Test(a3,16)
Test(a4,4)
Test(a5,4)
Test(a6,4)
Test(a7,5)
RETURN |
http://rosettacode.org/wiki/Voronoi_diagram | Voronoi diagram | A Voronoi diagram is a diagram consisting of a number of sites.
Each Voronoi site s also has a Voronoi cell consisting of all points closest to s.
Task
Demonstrate how to generate and display a Voroni diagram.
See algo K-means++ clustering.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N_SITES 150
double site[N_SITES][2];
unsigned char rgb[N_SITES][3];
int size_x = 640, size_y = 480;
inline double sq2(double x, double y)
{
return x * x + y * y;
}
#define for_k for (k = 0; k < N_SITES; k++)
int nearest_site(double x, double y)
{
int k, ret = 0;
double d, dist = 0;
for_k {
d = sq2(x - site[k][0], y - site[k][1]);
if (!k || d < dist) {
dist = d, ret = k;
}
}
return ret;
}
/* see if a pixel is different from any neighboring ones */
int at_edge(int *color, int y, int x)
{
int i, j, c = color[y * size_x + x];
for (i = y - 1; i <= y + 1; i++) {
if (i < 0 || i >= size_y) continue;
for (j = x - 1; j <= x + 1; j++) {
if (j < 0 || j >= size_x) continue;
if (color[i * size_x + j] != c) return 1;
}
}
return 0;
}
#define AA_RES 4 /* average over 4x4 supersampling grid */
void aa_color(unsigned char *pix, int y, int x)
{
int i, j, n;
double r = 0, g = 0, b = 0, xx, yy;
for (i = 0; i < AA_RES; i++) {
yy = y + 1. / AA_RES * i + .5;
for (j = 0; j < AA_RES; j++) {
xx = x + 1. / AA_RES * j + .5;
n = nearest_site(xx, yy);
r += rgb[n][0];
g += rgb[n][1];
b += rgb[n][2];
}
}
pix[0] = r / (AA_RES * AA_RES);
pix[1] = g / (AA_RES * AA_RES);
pix[2] = b / (AA_RES * AA_RES);
}
#define for_i for (i = 0; i < size_y; i++)
#define for_j for (j = 0; j < size_x; j++)
void gen_map()
{
int i, j, k;
int *nearest = malloc(sizeof(int) * size_y * size_x);
unsigned char *ptr, *buf, color;
ptr = buf = malloc(3 * size_x * size_y);
for_i for_j nearest[i * size_x + j] = nearest_site(j, i);
for_i for_j {
if (!at_edge(nearest, i, j))
memcpy(ptr, rgb[nearest[i * size_x + j]], 3);
else /* at edge, do anti-alias rastering */
aa_color(ptr, i, j);
ptr += 3;
}
/* draw sites */
for (k = 0; k < N_SITES; k++) {
color = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;
for (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {
if (i < 0 || i >= size_y) continue;
for (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {
if (j < 0 || j >= size_x) continue;
ptr = buf + 3 * (i * size_x + j);
ptr[0] = ptr[1] = ptr[2] = color;
}
}
}
printf("P6\n%d %d\n255\n", size_x, size_y);
fflush(stdout);
fwrite(buf, size_y * size_x * 3, 1, stdout);
}
#define frand(x) (rand() / (1. + RAND_MAX) * x)
int main()
{
int k;
for_k {
site[k][0] = frand(size_x);
site[k][1] = frand(size_y);
rgb [k][0] = frand(256);
rgb [k][1] = frand(256);
rgb [k][2] = frand(256);
}
gen_map();
return 0;
} |
http://rosettacode.org/wiki/Vogel%27s_approximation_method | Vogel's approximation method | Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.
The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that:
A will require 30 hours of work,
B will require 20 hours of work,
C will require 70 hours of work,
D will require 30 hours of work, and
E will require 60 hours of work.
They have identified 4 contractors willing to do the work, called “W”, “X”, “Y”, and “Z”.
W has 50 hours available to commit to working,
X has 60 hours available,
Y has 50 hours available, and
Z has 50 hours available.
The cost per hour for each contractor for each task is summarized by the following table:
A B C D E
W 16 16 13 22 17
X 14 14 13 19 15
Y 19 19 20 23 50
Z 50 12 50 15 11
The task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:
Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply<total demand)
Step 2: Determine the penalty cost for each row and column by subtracting the lowest cell cost in the row or column from the next lowest cell cost in the same row or column.
Step 3: Select the row or column with the highest penalty cost (breaking ties arbitrarily or choosing the lowest-cost cell).
Step 4: Allocate as much as possible to the feasible cell with the lowest transportation cost in the row or column with the highest penalty cost.
Step 5: Repeat steps 2, 3 and 4 until all requirements have been meet.
Step 6: Compute total transportation cost for the feasible allocations.
For this task assume that the model is balanced.
For each task and contractor (row and column above) calculating the difference between the smallest two values produces:
A B C D E W X Y Z
1 2 2 0 4 4 3 1 0 1 E-Z(50)
Determine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).
Adjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.
Repeat until all supply and demand is met:
2 2 2 0 3 2 3 1 0 - C-W(50)
3 5 5 7 4 35 - 1 0 - E-X(10)
4 5 5 7 4 - - 1 0 - C-X(20)
5 5 5 - 4 - - 0 0 - A-X(30)
6 - 19 - 23 - - - 4 - D-Y(30)
- - - - - - - - - B-Y(20)
Finally calculate the cost of your solution. In the example given it is £3100:
A B C D E
W 50
X 30 20 10
Y 20 30
Z 50
The optimal solution determined by GLPK is £3100:
A B C D E
W 50
X 10 20 20 10
Y 20 30
Z 50
Cf.
Transportation problem | #Ruby | Ruby | # VAM
#
# Nigel_Galloway
# September 1st., 2013
COSTS = {W: {A: 16, B: 16, C: 13, D: 22, E: 17},
X: {A: 14, B: 14, C: 13, D: 19, E: 15},
Y: {A: 19, B: 19, C: 20, D: 23, E: 50},
Z: {A: 50, B: 12, C: 50, D: 15, E: 11}}
demand = {A: 30, B: 20, C: 70, D: 30, E: 60}
supply = {W: 50, X: 60, Y: 50, Z: 50}
COLS = demand.keys
res = {}; COSTS.each_key{|k| res[k] = Hash.new(0)}
g = {}; supply.each_key{|x| g[x] = COSTS[x].keys.sort_by{|g| COSTS[x][g]}}
demand.each_key{|x| g[x] = COSTS.keys.sort_by{|g| COSTS[g][x]}}
until g.empty?
d = demand.collect{|x,y| [x, z = COSTS[g[x][0]][x], g[x][1] ? COSTS[g[x][1]][x] - z : z]}
dmax = d.max_by{|n| n[2]}
d = d.select{|x| x[2] == dmax[2]}.min_by{|n| n[1]}
s = supply.collect{|x,y| [x, z = COSTS[x][g[x][0]], g[x][1] ? COSTS[x][g[x][1]] - z : z]}
dmax = s.max_by{|n| n[2]}
s = s.select{|x| x[2] == dmax[2]}.min_by{|n| n[1]}
t,f = d[2]==s[2] ? [s[1], d[1]] : [d[2],s[2]]
d,s = t > f ? [d[0],g[d[0]][0]] : [g[s[0]][0],s[0]]
v = [supply[s], demand[d]].min
res[s][d] += v
demand[d] -= v
if demand[d] == 0 then
supply.reject{|k, n| n == 0}.each_key{|x| g[x].delete(d)}
g.delete(d)
demand.delete(d)
end
supply[s] -= v
if supply[s] == 0 then
demand.reject{|k, n| n == 0}.each_key{|x| g[x].delete(s)}
g.delete(s)
supply.delete(s)
end
end
COLS.each{|n| print "\t", n}
puts
cost = 0
COSTS.each_key do |g|
print g, "\t"
COLS.each do |n|
y = res[g][n]
print y if y != 0
cost += y * COSTS[g][n]
print "\t"
end
puts
end
print "\n\nTotal Cost = ", cost |
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #Erlang | Erlang | 8> filelib:fold_files( "/tmp", ".*", false, fun(File, Acc) -> [File|Acc] end, []).
["/tmp/.X0-lock","/tmp/.cron-check-4000-was-here",
"/tmp/kerneloops.XyN0SP","/tmp/npicagwD7tf"]
9> filelib:fold_files( "/tmp", "k.*P", false, fun(File, Acc) -> [File|Acc] end, []).
["/tmp/kerneloops.XyN0SP"]
|
http://rosettacode.org/wiki/Walk_a_directory/Non-recursively | Walk a directory/Non-recursively | Task
Walk a given directory and print the names of files matching a given pattern.
(How is "pattern" defined? substring match? DOS pattern? BASH pattern? ZSH pattern? Perl regular expression?)
Note: This task is for non-recursive methods. These tasks should read a single directory, not an entire directory tree.
Note: Please be careful when running any code presented here.
Related task
Walk Directory Tree (read entire directory tree).
| #Euphoria | Euphoria | include file.e
procedure show(sequence pattern)
sequence f
f = dir(pattern)
for i = 1 to length(f) do
puts(1,f[i][D_NAME])
puts(1,'\n')
end for
end procedure
show("*.*") |
http://rosettacode.org/wiki/Water_collected_between_towers | Water collected between towers | Task
In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains,
completely filling all convex enclosures in the chart with water.
9 ██ 9 ██
8 ██ 8 ██
7 ██ ██ 7 ██≈≈≈≈≈≈≈≈██
6 ██ ██ ██ 6 ██≈≈██≈≈≈≈██
5 ██ ██ ██ ████ 5 ██≈≈██≈≈██≈≈████
4 ██ ██ ████████ 4 ██≈≈██≈≈████████
3 ██████ ████████ 3 ██████≈≈████████
2 ████████████████ ██ 2 ████████████████≈≈██
1 ████████████████████ 1 ████████████████████
In the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.
Write a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.
Calculate the number of water units that could be collected by bar charts representing each of the following seven series:
[[1, 5, 3, 7, 2],
[5, 3, 7, 2, 6, 4, 5, 9, 1, 2],
[2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],
[5, 5, 5, 5],
[5, 6, 7, 8],
[8, 7, 7, 6],
[6, 7, 10, 7, 6]]
See, also:
Four Solutions to a Trivial Problem – a Google Tech Talk by Guy Steele
Water collected between towers on Stack Overflow, from which the example above is taken)
An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.
| #Ada | Ada | with Ada.Text_IO;
procedure Water_Collected is
type Bar_Index is new Positive;
type Natural_Array is array (Bar_Index range <>) of Natural;
subtype Bar_Array is Natural_Array;
subtype Water_Array is Natural_Array;
function Flood (Bars : Bar_Array; Forward : Boolean) return Water_Array is
R : Water_Array (Bars'Range);
H : Natural := 0;
begin
if Forward then
for A in R'Range loop
H := Natural'Max (H, Bars (A));
R (A) := H - Bars (A);
end loop;
else
for A in reverse R'Range loop
H := Natural'Max (H, Bars (A));
R (A) := H - Bars (A);
end loop;
end if;
return R;
end Flood;
function Fold (Left, Right : Water_Array) return Water_Array is
R : Water_Array (Left'Range);
begin
for A in R'Range loop
R (A) := Natural'Min (Left (A), Right (A));
end loop;
return R;
end Fold;
function Fill (Bars : Bar_Array) return Water_Array
is (Fold (Flood (Bars, Forward => True),
Flood (Bars, Forward => False)));
function Sum_Of (Bars : Natural_Array) return Natural is
Sum : Natural := 0;
begin
for Bar of Bars loop
Sum := Sum + Bar;
end loop;
return Sum;
end Sum_Of;
procedure Show (Bars : Bar_Array) is
use Ada.Text_IO;
Water : constant Water_Array := Fill (Bars);
begin
Put ("The series: [");
for Bar of Bars loop
Put (Bar'Image);
Put (" ");
end loop;
Put ("] holds ");
Put (Sum_Of (Water)'Image);
Put (" units of water.");
New_Line;
end Show;
begin
Show ((1, 5, 3, 7, 2));
Show ((5, 3, 7, 2, 6, 4, 5, 9, 1, 2));
Show ((2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1));
Show ((5, 5, 5, 5));
Show ((5, 6, 7, 8));
Show ((8, 7, 7, 6));
Show ((6, 7, 10, 7, 6));
end Water_Collected; |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.