約 2,956,971 件
https://w.atwiki.jp/kani_3/pages/20.html
オーディオプレーヤ "Exaile"の曲情報取得プラグイン(pyGrabCDInfo) Exaileのプラグインを作ってみました。(Linux環境でのみ動作確認を行っています) pyGrabCDInfo.pyというファイルのみです。 pyGrabCDInfo.pyを ~/.exaile/plugins/に置き、Exaileを再起動してください。 Exaile起動後、PluginManagerを開いて、Enableチェックボックスを ONにすることで有効になります。 このプラグインが有効になっている状態でExaileが起動すると、 Exaileのウインドウに”grabCDDB”というボタンが追加されています。 ネットワークに接続されている状態で、PCにCDをトレイに挿入し、 CDの曲名を表示してください(FileメニューのOpenDiscを選択)。 CDの情報がExaileのウインドウに表示された後、もし文字化けが あった場合には、grabCDDBボタンをおせば、ネットワーク経由で情報を 再取得し、文字化けを解消してくれます。(きっと) 実行するためには、以下のものが必要です。 exaile python pygtk CDDB DiscID httplib xml.sax ソースコードは以下の通りです。 (実際のスクリプトファイルはこのページの一番下に添付してあります) import gtk import plugins import CDDB import DiscID import httplib import xml.sax from xml.sax.handler import ContentHandler PLUGIN_NAME = CD InfoGraber PLUGIN_AUTHORS = [ kani jkani4@gmail.com ] PLUGIN_VERSION = 0.1 PLUGIN_ENABLED = False PLUGIN_DESCRIPTION = r Get CD Information such as album name from freedb2.org. b = gtk.Button() PLUGIN_ICON = b.render_icon(gtk.STOCK_MEDIA_PLAY, gtk.ICON_SIZE_MENU) b.destroy() URL_CDDB_TRACKTYPE_ORG = http //tracktype.org 80/~cddb/cddb.cgi URL_FREEDB2_ORG = www.freedb2.org CONNS = plugins.SignalContainer() ## def get_conf_str(name, defStr) return APP.settings.get_str(name, default=defStr, plugin=plugins.name(__file__)) ## def set_conf_str(name, someStr) APP.settings.set_str(name, someStr, plugin=plugins.name(__file__)) # # class Freedb2XMLHandler(ContentHandler) ## def __init__(self) ContentHandler.__init__(self) self.album = self.artist = self.year = self.genre = self.trackNames = {} self.tmpStr = self.inTrack = False self.trackNo = self.tagDict = { artist 0, title 1, year 2, genre 3, track 4, number 5 } ## def startElement(self, name, attrs) self.tmpStr = if name in self.tagDict if self.tagDict[name] == self.tagDict[ track ] self.inTrack = True self.trackNo = ## def endElement(self, name) if not name in self.tagDict return tagType = self.tagDict[name] if tagType == self.tagDict[ artist ] self.artist += self.tmpStr elif tagType == self.tagDict[ title ] if self.inTrack self.trackNames[int(self.trackNo)] = self.tmpStr else self.album += self.tmpStr elif tagType == self.tagDict[ number ] self.trackNo += self.tmpStr elif tagType == self.tagDict[ year ] self.year += self.tmpStr elif tagType == self.tagDict[ genre ] self.genre += self.tmpStr if tagType == self.tagDict[ track ] self.inTrack = False ## def characters(self, content) self.tmpStr += content ## def count_tracks(self) return len(self.trackNames) ## def get_track_name(self, trackNo) if trackNo in self.trackNames return self.trackNames[trackNo] return ## def get_track_name_dict(self) return self.trackNames ## def get_artist(self) return self.artist ## def get_album(self) return self.album ## def get_year(self) return self.year ## def get_genre(self) return self.genre # # def showErrorMsg(msgStr) if len(msgStr) == 0 return dialog = gtk.MessageDialog(APP.window, buttons=gtk.BUTTONS_OK, type=gtk.MESSAGE_INFO, message_format=msgStr) dialog.run() dialog.destroy() # # def update_track_info(trackList, artist, album, year, genre, trackNames) if trackList == None return trkCnt = len(trackNames) if trkCnt == 0 showErrorMsg( Current playlist has no tracks.. ) return songs = trackList.get_songs() if songs == None return if len(songs) != trkCnt showErrorMsg("The number of track in the current playlist is different from CDDB s one ") return for i in range(trkCnt) songs[i].title = trackNames[i+1] songs[i].album = album songs[i].artist = artist songs[i].year = year songs[i].genre = genre trackList.set_songs(songs) # # def get_cd_category_and_discid(cdDevice, serverURL) category = discID = try disc = DiscID.open(cdDevice) disc_info = DiscID.disc_id(disc) (status, info) = CDDB.query(disc_info, serverURL) except showErrorMsg( can not get cddb information. ) return (category, discID) # status # 200 success # 210 multiple inexact maches ware found # 211 multiple exact maches ware found # other error if status in [210, 211] info = info[0] status = 200 if status == 200 category = info[ category ] discID = info[ disc_id ] return (category, discID) # # def grab_cd_info(widget, app) if app == None return if app.tracks == None or len(app.tracks.get_songs()) == 0 showErrorMsg( There are no tracks selected. ) return # # Get categroy and disc_id of CD that is in the cd drive. # device = APP.settings.get_str( cd_device , /dev/cdrom ) try (category, discID) = get_cd_category_and_discid(device, URL_CDDB_TRACKTYPE_ORG) if category == or discID == raise -1 except showErrorMsg( Can not get category or disc_id. ) progWind.close() return # # Connect to www.freedb2.org, and get cd information in xml format. # try con = httplib.HTTPConnection(URL_FREEDB2_ORG) con.request( GET , /xml/%s/%s % (category, discID), body= , headers={ User-Agent Python/2.5 }) except showErrorMsg( Can not get xml from www.freedb2.org ) progWind.close() return # # Parse xml # try handler = Freedb2XMLHandler() response = con.getresponse() xmldata = response.read() parser = xml.sax.make_parser() parser.setContentHandler(handler) parser.feed(xmldata) except showErrorMsg( Can not parse xml. ) progWind.close() return if handler.count_tracks() == 0 showErrorMsg( there is no tracks. ) progWind.close() return # # Update the current playlist with grabbed information. # update_track_info(app.tracks, handler.get_artist(), handler.get_album(), handler.get_year(), handler.get_genre(), handler.get_track_name_dict()) ### # # Below describes functions for exaile plugin. # ### gToolBar = None gCnvButton = None # # def initialize() Called when the plugin is enabled. # # Append custom button to reload audio cd track information # from CDDB global gToolBar global gCnvButton if gCnvButton == None gToolBar = APP.xml.get_widget( play_toolbar ) gCnvButton = gtk.Button( grabCDDB ) gToolBar.pack_start(gCnvButton, True, False, 0) gToolBar.show_all() gCnvButton.connect( clicked , grab_cd_info, APP) return True # # def destroy() Called when the plugin is disabled. pass
https://w.atwiki.jp/slimelv1024/pages/66.html
package sort; public class MyData implements SortableData{ private String name; private int value; public MyData(String n,int v){ name=n; value=v; } public String getName(){ return name; } public int getValue(){ return value; } public int getSortKey(){ return value; } public String toString(){ return name+" "+value; } }
https://w.atwiki.jp/ookowaikowai/pages/31.html
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Net; using System.Net.Sockets; using System.Windows.Forms; using System.Text.RegularExpressions; namespace DesignProject { class UDPMessage { //メッセージの種別 public const int MESSAGE_INT = 0; public const int MESSAGE_STRING = 1; public const int MESSAGE_CHARACTER = 2; public const int MESSAGE_SYSTEM = 3; //システムメッセージの種別 public const int SYSTEM_CONNECT = 0; public const int SYSTEM_CLOSE = 1; public int type { get; private set; } public int dataLength { get; private set; } public byte[] data { get; private set; } public UDPMessage(int type, byte[] data) { this.type = type; this.data = data; this.dataLength = data.Length; } public UDPMessage(byte[] data) { int index = 0; this.type = BitConverter.ToInt32(data, index); index += 4; this.dataLength = BitConverter.ToInt32(data, index); index += 4; this.data = new byte[this.dataLength]; Array.ConstrainedCopy(data, index, this.data, 0, this.dataLength); } public byte[] ToByte() { byte[] result = new byte[4 + 4 + this.dataLength]; int index = 0; byte[] temp = BitConverter.GetBytes(this.type); Array.ConstrainedCopy(temp, 0, result, index, temp.Length); index += temp.Length; temp = BitConverter.GetBytes(this.dataLength); Array.ConstrainedCopy(temp, 0, result, index, temp.Length); index += temp.Length; Array.ConstrainedCopy(this.data, 0, result, index, this.data.Length); return(result); } //データをint型へ変換 public int DataToInt() { return (BitConverter.ToInt32(this.data, 0)); } //データをstring型へ変換 public string DataToString() { Encoding sjisEnc = Encoding.GetEncoding("Shift_JIS"); return (sjisEnc.GetString(this.data, 0, this.dataLength)); } //データをCharacter型へ変換 public Character DataToCharacter() { return(new Character(this.data)); } } class UDPStateObject { public NetworkUDP network; public UDPStateObject(NetworkUDP network) { this.network = network; } } class NetworkUDP { private UdpClient udp; private IPEndPoint remote; public IPEndPoint clientEndPoint { get { return (this.isReceived ? this.remote null); } } //private Queue byte[] sendDataQueue; private Queue byte[] receiveDataQueue; //public int sendCount { get { return (this.sendDataQueue.Count); } } public int receiveCount { get { return (this.receiveDataQueue.Count); } } private Thread receiveThread; public bool isReceived { get; private set; } public bool isClientEnd { get; private set; } public bool isReceiving { get; private set; } public NetworkUDP(int port) { this.udp = new UdpClient(port); //this.sendDataQueue = new Queue byte[] (); this.receiveDataQueue = new Queue byte[] (); this.receiveThread = null; this.isReceived = false; this.isClientEnd = false; this.isReceiving = false; } public void Close() { Console.WriteLine("CloseClient "); this.isClientEnd = true; if (this.isReceiving) { this.receiveThread.Abort(); this.receiveThread.Join(); } this.udp.Close(); } private void Send(byte[] data, IPEndPoint endPoint) { Console.WriteLine("SendStart"); this.udp.Send(data, data.Length, endPoint); Console.WriteLine("SendEnd"); } //public void Send(byte[] data, string ipAddress, int port) //{ // Send(data, new IPEndPoint(IPAddress.Parse(ipAddress), port)); //} //public void Send(int data, string ipAddress, int port) //{ // Send(BitConverter.GetBytes(data), new IPEndPoint(IPAddress.Parse(ipAddress), port)); //} private void StartSend(byte[] data, IPEndPoint endPoint) { Console.WriteLine("SendStart"); this.udp.BeginSend(data, data.Length, new AsyncCallback(SendCallback), new UDPStateObject(this)); } private static void SendCallback(IAsyncResult ar) { UDPStateObject state = (UDPStateObject)(ar.AsyncState); if (!state.network.isClientEnd) { try { int sendBytes = state.network.udp.EndSend(ar); Console.WriteLine("SendEnd " + sendBytes); } catch (Exception e) { Console.WriteLine(e.Message + e.TargetSite); } } } //int型のデータ送信用 public void SendIntMessage(int data, IPEndPoint endPoint) { UDPMessage message = new UDPMessage(UDPMessage.MESSAGE_INT, BitConverter.GetBytes(data)); Send(message.ToByte(), endPoint); } //string型のデータ送信用 public void SendStringMessage(string data, IPEndPoint endPoint) { Encoding sjisEnc = Encoding.GetEncoding("Shift_JIS"); UDPMessage message = new UDPMessage(UDPMessage.MESSAGE_STRING, sjisEnc.GetBytes(data)); Send(message.ToByte(), endPoint); } //Character型のデータ送信用 public void SendCharacterMessage(Character data, IPEndPoint endPoint) { UDPMessage message = new UDPMessage(UDPMessage.MESSAGE_SYSTEM, data.ToByte()); Send(message.ToByte(), endPoint); } //システムメッセージ送信用 public void SendSystemMessage(int data, IPEndPoint endPoint) { UDPMessage message = new UDPMessage(UDPMessage.MESSAGE_SYSTEM, BitConverter.GetBytes(data)); Send(message.ToByte(), endPoint); } private void StartReceive() { if (!this.isClientEnd) { this.udp.BeginReceive(ReceiveCallback, new UDPStateObject(this)); } } private static void ReceiveCallback(IAsyncResult ar) { UDPStateObject state = (UDPStateObject)(ar.AsyncState); if (!state.network.isClientEnd) { try { byte[] data = state.network.udp.EndReceive(ar, ref state.network.remote); state.network.receiveDataQueue.Enqueue(data); //state.network.data = state.network.udp.EndReceive(ar, ref state.network.remote); //Console.WriteLine(Encoding.ASCII.GetString(data, 0, data.Length)); Console.WriteLine(BitConverter.ToString(data)); Console.WriteLine("Received from " + state.network.remote.Address + " " + state.network.remote.Port); state.network.isReceived = true; } catch (Exception e) { Console.WriteLine(e.Message + e.TargetSite); } } } private void RunReceive() { while (true) { StartReceive(); Thread.Sleep(100); } } public void StartReceiveThread() { this.receiveThread = new Thread(new ThreadStart(this.RunReceive)); this.receiveThread.Start(); this.isReceiving = true; Console.WriteLine("ReceiveStart"); } public byte[] GetReceiveData() { if (this.receiveDataQueue.Count != 0) { return (this.receiveDataQueue.Dequeue()); } return (null); } public UDPMessage GetReceiveMessage() { if (this.receiveDataQueue.Count != 0) { return (new UDPMessage(this.receiveDataQueue.Dequeue())); } return (null); } static string clip = ""; static void GetClipboardText() { if (Clipboard.ContainsText()) { clip = Clipboard.GetText(); } } public static IPEndPoint GetClipIP() { Thread t = new Thread(GetClipboardText); t.SetApartmentState(ApartmentState.STA); t.Start(); t.Join(); Regex regex = new Regex("(([0-9]{1,3})([.])([0-9]{1,3})([.])([0-9]{1,3})([.])([0-9]{1,3}))([ ])([0-9]{1,5})"); if (regex.IsMatch(clip)) { string ip = regex.Match(clip).Groups[1].ToString(); string port = regex.Match(clip).Groups[10].ToString(); //Console.WriteLine(ip + " " + port); return (new IPEndPoint(IPAddress.Parse(ip), int.Parse(port))); } return(null); } public static void SetClipboardText() { Clipboard.SetText(GlobalIP.GetGIP.Get().ToString() + " " + "10800"); } public static void SetClipIP() { Thread t = new Thread(SetClipboardText); t.SetApartmentState(ApartmentState.STA); t.Start(); t.Join(); } public static int[] GetIPArray(IPEndPoint ip) { int[] ipport = new int[17]; string str = ip.ToString(); int writeIndex = 0; //int section = 2; Regex regex = new Regex("(([0-9]{1,3})([.])([0-9]{1,3})([.])([0-9]{1,3})([.])([0-9]{1,3}))([ ])([0-9]{1,5})"); if (regex.IsMatch(str)) { for (int section = 2; section 10; section += 2) { string num = regex.Match(str).Groups[section].Value; for (int i = 0; i num.Length; i++) { ipport[writeIndex * 3 + 3 - num.Length + i] = int.Parse(num[i].ToString()); } writeIndex += 1; } string port = regex.Match(str).Groups[10].Value; for (int i = 0; i port.Length; i++) { ipport[12 + i] = int.Parse(port[i].ToString()); } } //for (int i = 0; i 17; i++) //{ // Console.WriteLine(ipport[i]); //} return (ipport); } public static IPEndPoint GetIPFromArray(int[] array) { string ip = ""; for (int i = 0; i 4; i++) { if(i != 0){ ip += "."; } for (int j = 0; j 3; j++) { if (!((j == 0) (array[i * 3 + j].ToString().Equals("0")))) { ip += array[i * 3 + j].ToString(); } } } string port = ""; for(int i = 0; i 5; i ++){ port += array[12 + i].ToString(); } return (new IPEndPoint(IPAddress.Parse(ip), int.Parse(port))); } public static string GetIPStringFromArray(int[] array) { string ip = ""; for (int i = 0; i 4; i++) { if (i != 0) { ip += "."; } for (int j = 0; j 3; j++) { ip += array[i * 3 + j].ToString(); } } string port = ""; for (int i = 0; i 5; i++) { port += array[12 + i].ToString(); } return (ip + " " + port); } } }
https://w.atwiki.jp/c21coterie/pages/625.html
問い51 http //odz.sakura.ne.jp/projecteuler/index.php?cmd=read page=Problem%2051 *3の第1桁を置き換えることで, 13, 23, 43, 53, 73, 83という6つの素数が得られる. 56**3の第3桁と第4桁を同じ数で置き換ることを考えよう. この5桁の数は7つの素数をもつ最初の例である 56003, 56113, 56333, 56443, 56663, 56773, 56993. よって, この族の最初の数である 56003は, このような性質を持つ最小の素数である. 桁を同じ数で置き換えることで8つの素数が得られる最小の素数を求めよ. (注 連続した桁でなくても良い) 解法 100万までの素数をvectorに格納し、各素数それぞれについて*文字にチェンジした全パタンを求めてその出現回数をカウントしてみました。 答えは正しいですし34秒で答えは出るのですが何か間違ったコードを書いてる感がすごくあります。 C++なら遅くても数秒程度で答えが出るコードが正しいコードのような気がします。 答えはもっとシンプル。 そんな気がするのでこの問題後日再チャレンジする予定です。 #include stdio.h #include map #include string #include vector #include stdlib.h #include iostream #include string.h #include set struct S{ int num,count; }; std set std string patternSet; std map std string,S memo; const int up=1000000; std vector int sosuu; bool so[up+1]; void setMemo(char text[10],char num,int p,int n){ if(p==0)patternSet.clear(); if(num!=-1){ if(patternSet.find(text)==patternSet.end()){ patternSet.insert(text); if(memo.find(text)==memo.end()){ S s; s.count=1; s.num=n; memo[text]=s; }else{ memo[text].count++; } } } if(text[p]== \0 )return; if(num==-1){ setMemo(text,-1,p+1,n); char c=text[p]; text[p]= * ; setMemo(text,c,p+1,n); text[p]=c; }else{ setMemo(text,num,p+1,n); if(text[p]==num){ text[p]= * ; setMemo(text,num,p+1,n); text[p]=num; } } } void setSo(){ int i2; memset(so,true,sizeof(so)); so[0]=so[1]=false; for(int i=4;i =up;i+=2)so[i]=false; sosuu.push_back(2); for(int i=3;i =up;i+=2){ if(so[i]==false)continue; sosuu.push_back(i); i2=i*2; for(int j=i*3;j =up;j+=i2){ so[j]=false; } } } int main(){ setSo(); int num; std string str,str2; for(int i=0;i sosuu.size();i++){ int p=sosuu[i]; char text[10]; sprintf(text,"%d",p); setMemo(text,-1,0,p); //std cout "\n"; } int ans=up+1; std cout memo["56**3"].count "\n"; for(std map std string,S iterator it=memo.begin();it!=memo.end();it++){ if((*it).second.count==8 ans (*it).second.num){ ans=(*it).second.num; } } printf("%d",ans); } 問い52 http //odz.sakura.ne.jp/projecteuler/index.php?cmd=read page=Problem%2052 解法 この問題は本当はコードを書くまでもなく1/7の性質について知っていたら簡単に解ける問題です。 一応コードを書いてみました。 #include stdio.h int main(){ for(int i=2;i 10;i++){ int memo[7],num=1,count[10]={0}; bool ok=true; for(int j=0;j 6;j++){ num*=10; memo[j]=num/i; num%=i; if(count[num]==1)ok=false; count[num]++; } if(num==1 ok==true){ for(int j=0;j 6;j++)printf("%d",memo[j]); break; } } } 問い53 http //odz.sakura.ne.jp/projecteuler/index.php?cmd=read page=Problem%2053 パスカルの三角形を101段目まで書いたとき、100万を超える項は何個あるかという問題です。 解法 パスカルの三角形を計算して100万以上になったらその影響下にある項は全て100万で統一して計算するのが一番シンプルですが、それもいいのですが無意味に計算量を抑えて遊んでみました。 一段ずつ上からパスカルの三角形に基づき計算します。 左端から計算して100万を超えたらそこより右は計算しないでその段の残りの項の数からその段の100万を超えた項の数を求め次の段へ計算をすすめます。 この手法なら問題が100000段とかになっても計算量がそんなに増えない程度しか利点がありません。 1段目0C0から計算が始まるので100Crだと101段目まで計算する点に注意するくらいです。 #include stdio.h #include string.h #include time.h int main(){ double start=clock(); int memo[102]={0,1,0},ans=0; for(int n=1;n =101;n++){ int next[102]={0}; int r; for(r=1;r =n;r++){ next[r]=memo[r-1]+memo[r]; if(next[r] =1000*1000)break; } if(r n){ if(n%2==0){ ans+=(n/2-r+1)*2; }else{ ans+=(n+1)/2==r?1 1+((n+1)/2-r)*2; } } memcpy(memo,next,sizeof(next)); } printf("ans=%d time=%lf",ans,clock()-start); } 問い54 http //odz.sakura.ne.jp/projecteuler/index.php?cmd=read page=Problem%2054 2人対戦のポーカーの手札が1000勝負分与えられるのでプレーヤAの勝った回数を答えよという問題。、 解法 役を判定する関数を全部書いて大きい役からチェックしスコアを算出してみました。 役の中で一番大きな数字をスコアに加算することでコードを少し簡略化したつもりです。 役の排他性を考えたポーカーの考案者は中々素晴らしいものがありますね。 スートで判定するということがないのでコードは少し簡単です。 #include stdio.h #include algorithm struct CARD{ int num; char suit; void set(char text[3]){ if(text[0]== T ){ num=10; }else if(text[0]== J ){ num=11; }else if(text[0]== Q ){ num=12; }else if(text[0]== K ){ num=13; }else if(text[0]== A ){ num=14;//1は一番大きな数として扱う }else{ num=text[0]- 0 ; } suit=text[1]; } bool operator (const CARD c)const{ if(c.num!=num)return num c.num; return suit c.suit; } }; CARD cardsA[5],cardsB[5]; int onePairs(CARD cards[5]){ int point=1000; for(int i=0;i 4;i++){ if(cards[i].num==cards[i+1].num)return point+cards[i].num; } return 0; } int TwoPairs(CARD cards[5]){ int point=2000; if(cards[0].num==cards[1].num){ if(cards[2].num==cards[3].num){ return point+cards[3].num; } if(cards[3].num==cards[4].num){ return point+cards[3].num; } } if(cards[1].num==cards[2].num cards[3].num==cards[4].num){ return point+cards[3].num; } return 0; } int ThreeOfAKind(CARD cards[5]){ int point=3000; if(cards[0].num==cards[2].num||cards[1].num==cards[3].num||cards[2].num==cards[4].num){ return point+cards[2].num; } return 0; } int Straight(CARD cards[5]){ int point=4000; int num=cards[0].num; for(int i=1;i 5;i++){ num++; if(cards[i].num!=num)return 0; } return point+cards[4].num; } int flash(CARD cards[5]){ int point=5000; if(cards[0].suit==cards[1].suit cards[1].suit==cards[2].suit cards[2].suit==cards[3].suit cards[3].suit==cards[4].suit){ return point+cards[4].num; } return 0; } int FullHouse(CARD cards[5]){ int point=6000; if(cards[0].num==cards[1].num cards[2].num==cards[4].num)return point+cards[2].num; if(cards[0].num==cards[2].num cards[3].num==cards[4].num)return point+cards[3].num; return 0; } int FourOfAKind(CARD cards[5]){ int point=7000; if(cards[0].num==cards[3].num){ return point+cards[0].num; } if(cards[1].num==cards[4].num){ return point+cards[1].num; } return 0; } int StraightFlush(CARD cards[5]){ int point=8000; if(flash(cards)!=0 Straight(cards)!=0){ return point+cards[4].num; } return 0; } int RoyalFlush(CARD cards[5]){ int point=9000; if(flash(cards)!=0 cards[0].num==10 cards[1].num==11 cards[2].num==12 cards[3].num==13 cards[4].num==14){ return point+14; } return 0; } int calc(CARD cards[5]){ int point; if((point=RoyalFlush(cards))!=0)return point; if((point=StraightFlush(cards))!=0)return point; if((point=FourOfAKind(cards))!=0)return point; if((point=FullHouse(cards))!=0)return point; if((point=flash(cards))!=0)return point; if((point=Straight(cards))!=0)return point; if((point=ThreeOfAKind(cards))!=0)return point; if((point=TwoPairs(cards))!=0)return point; if((point=onePairs(cards))!=0)return point; return 0; } int lastCheck(CARD cardsA[5],CARD cardsB[5]){ for(int i=4;i =0;i--){ if(cardsA[i].num cardsB[i].num)return 1; if(cardsA[i].num cardsB[i].num)return -1; } return 0; } void print(CARD cards[5]){ printf("("); for(int i=0;i 5;i++)printf("%d%c ",cards[i].num,cards[i].suit); printf(")"); } int main(){ char c[3],c1; int ans=0; while(1){ bool last=false; for(int i=0;i 5;i++){ if(scanf("%s",c)==EOF){ last=true; break; } cardsA[i].set(c); } if(last==true)break; for(int i=0;i 5;i++){ scanf("%s",c); cardsB[i].set(c); } std sort(cardsA,cardsA+5); std sort(cardsB,cardsB+5); //print(cardsA); //print(cardsB); int p1=calc(cardsA); int p2=calc(cardsB); //printf("(%d %d)\n",p1,p2); if(p1==p2)p1+=lastCheck(cardsA,cardsB); if(p1 p2)ans++; } printf("ans%d",ans); } 問い55 http //odz.sakura.ne.jp/projecteuler/index.php?cmd=read page=Problem%2055 10000未満のLychrel数はいくつあるか? 解法 定義通り素朴に計算してみました。 (defun toRev(n) (parse-integer (reverse (princ-to-string n)))) (let ((a) (ans 0)) (dotimes (i 9999) (setq a (+ 1 i)) (dotimes (j 50) (setq a (+ a (toRev a))) (if (= a (toRev a)) (setq ans (+ ans 1) j 50) )))(- 9999 ans)) 問い56 a^b (a,b<100の自然数)として各桁の和の最大値を求めよ。 解法 Lispで力づくで解いてました。 賢い方法ありますかね、これ。 (defun ketaSum(n) (apply # + (map list # digit-char-p (princ-to-string n)))) (let ((ans 0) (a 0)) (dotimes (i 99) (dotimes (j 99) (setq a (ketaSum (expt (+ 1 i) (+ 1 j)))) (if ( ans a) (setq ans a) )))ans) 問い57 http //odz.sakura.ne.jp/projecteuler/index.php?cmd=read page=Problem%2057 2の平方根を連分数で表したとき、連分数の項によっては分子の方が分母より桁数が多くなる。 1000項目までで分子の方が大きい項の数を数えよ。 解法 数式をそのまま再帰式になおすだけです。 saikl関数が数式を表します。 一番底が5/2で始まり再帰を戻るたびに項が大きくなっていきます。 (defvar ans 0) (defun saiki(deep) (let ((a 0) (re 0)) (if (= deep 1000) (setq a (/ 5 2)) (setq a (+ 2 (/ 1 (saiki (+ 1 deep)))))) (setq ans (+ ans (check (- a 1))))a)) saiki (defun check (n) (let ((a (numerator n)) (b (denominator n)) (re 0)) (if ( (length (princ-to-string b)) (length (princ-to-string a))) (setq re 1) (setq re 0))re)) saiki (defun main() (setq ans 0) (saiki 0) ans) (main ) 問い58 http //odz.sakura.ne.jp/projecteuler/index.php?cmd=read page=Problem%2058 渦巻きに配置された格子の対角線上にある素数の数を調べ上げよ 解法 なにやらみなさん色々凝ったコードを書いているようですが素朴に計算しても十分速度的に間に合います。 #include stdio.h bool isPrime(int n){ for(int i=2;i*i =n;i+=(i 1)+1){ if(n%i==0)return false; } return true; } int main(){ int all=0,count=0,size=3,num=1; while(1){ for(int i=0;i 4;i++){ num+=size-1; if(isPrime(num)==true)count++; } all+=4; if(count*10 =all)break; size+=2; } printf("%d",size); } 問い60 http //odz.sakura.ne.jp/projecteuler/index.php?cmd=read page=Problem%2060 素数3, 7, 109, 673は非凡な性質を持っている. 任意の2つの素数を任意の順で繋げると, また素数になっている. 例えば, 7と109を用いると, 7109と1097の両方が素数である. これら4つの素数の和は792である. これは, このような性質をもつ4つの素数の組の和の中で最小である. 任意の2つの素数を繋げたときに別の素数が生成される, 5つの素数の組の和の中で最小のものを求めよ. 解法 全然だめです、賢い解法思いつきません。 素数を点、結合可能な素数の組を線からなるグラフとみて、3万以下の素数についてグラフが五望星をなしている場所を探索で探してみましたがコードは膨らむし速度は出ないしで駄目ですね。 グラフの生成部分が物凄く遅くc++なのに答えを出すのに34秒もかかってます。 こんなコードではプロジェクトオイラーでは負け組みな気がします。 #include stdio.h #include vector #include algorithm #include map #include stdlib.h #include set #include string.h #include string #include time.h const int up=100000; std vector __int64 sosuu; bool isPrime[up+1]; std map int,std set int cons; int ans=0; void setPrime(){ int i2; memset(isPrime,true,sizeof(isPrime)); isPrime[0]=isPrime[1]=false; for(int i=4;i =up;i+=2)isPrime[i]=false; sosuu.push_back(2); for(int i=3;i =up;i+=2){ if(isPrime[i]==false)continue; sosuu.push_back(i); i2=i*2; for(int j=i*3;j =up;j+=i2){ isPrime[j]=false; } } } bool checkPrime(__int64 n){ if(n 2)return false; for(int i=0;sosuu[i]*sosuu[i] =n;i++){ if(n%sosuu[i]==0)return false; } return true; } void setConnect(){ char text[20]; __int64 a,b; for(int i=0;sosuu[i] =30000;i++){ for(int j=i+1;sosuu[j] =30000;j++){ sprintf(text,"%I64lld%I64lld",sosuu[i],sosuu[j]); sscanf(text,"%I64lld", a); sprintf(text,"%I64lld%I64lld",sosuu[j],sosuu[i]); sscanf(text,"%I64lld", b); if(checkPrime(a)==true checkPrime(b)==true){ cons[sosuu[i]].insert(sosuu[j]); } } } } bool addOK(std set int perm,int addNum){ for(std set int iterator it=perm.begin();it!=perm.end();it++){ if(cons[(*it)].find(addNum)==cons[(*it)].end())return false; } return true; } void print(std set int perm,int num){ printf("解候補の組(%d ",num); for(std set int iterator it=perm.begin();it!=perm.end();it++){ printf("%d ",(*it)); } printf(")\n"); } void saiki(int num,std set int iterator it,int count,int wa,std set int perm){ if(ans!=0 ans =wa)return; if(count==4){ print(perm,num); ans=wa; return; } int wa2; if(count!=0)it++; for(;it!=cons[num].end();it++){ if(addOK(perm,(*it))==true){ wa2=wa+(*it); perm.insert(*it); saiki(num,it,count+1,wa2,perm); perm.erase(*it); } } } int main(){ double start=clock(); setPrime(); printf("処理0終了\n"); setConnect(); printf("処理1終了 サイズ%d\n",cons.size()); std set int perm; for(std map int,std set int iterator it=cons.begin();it!=cons.end();it++){ if((*it).second.size() 3)saiki((*it).first,(*it).second.begin(),0,(*it).first,perm); } printf("\nans=%d time=%lf",ans,clock()-start); }
https://w.atwiki.jp/sklab/pages/22.html
イテレータ クラス内において、反復処理の機能をシンプルに書くことが出来る。 yield return文を用いる事で、順に値を返すことを可能とする。 class Program { public static IEnumerable MethodShow(){ yield return "January"; yield return "Feburuary"; yield return "March"; } static void Main(string[] args){ foreach( var s in Program.MethodShow){ Console.WriteLine(val); } } }
https://w.atwiki.jp/javadsge/pages/2267.html
!DOCTYPE html html head script src="http //fb.me/react-0.13.3.js" /script script src="http //fb.me/JSXTransformer-0.13.3.js" /script /head body div id="ap2" /div div id="ap3" /div script type="text/jsx" var Hex = React.createClass({ render function() { return ( h1 A /h1 ); } }); var Den = React.createClass({ render function() { return ( h1 B /h1 ); } }); var m231 = React.render( Hex/ ,document.getElementById( ap2 )); var m232 = React.render( Den/ ,document.getElementById( ap3 )); /script /body /html
https://w.atwiki.jp/fattencho/pages/15.html
Perl ワンライナー エンコード echo "@" | perl -ne s/([^\w ])/"%".unpack("H2",$1)/eg;s/ /\+/g;print;print "\n"; デコード perl -MURI Escape -wle print uri_unescape $ARGV[0] http //ja.wikipedia.org/wiki/%E3%81%93%E3%81%88%E9%83%A8 # perlでデーモン作成 #!/usr/local/bin/perl use strict; use warnings; my $PID; my $PID_FILE = "/home/fattencho/daemon.pid"; my $SLEEP_INTERVAL = 10; main(@ARGV); exit(0); sub main { my ($act) = @_; $act ||=""; if ($act eq "start"){ #daemonの起動 #複数の起動はできません if( get_pid_file() ){ print "$0 is already running\n"; return; } init(); action(); return; } if ($act eq "stop"){ #daemonの停止 my $pid = get_pid_file(); if(not defined $pid){ print "$0 is not running\n"; return; } #pid fileを削除すると、後でkillされます return del_pid_file(); } print "usage $0 [start|stop]\n"; return; } sub init { my $pid = fork; # Fork failure. if($pid 0){ exit -1; } # Fork success. elsif($pid){ exit 0; } #signal送信時に実行するmethod $SIG{INT} = $SIG{HUP} = $SIG{QUIT} = $SIG{KILL} = $SIG{TERM} = interrupt ; $PID = $$; set_pid_file($PID); } sub action { while(1) { sleep($SLEEP_INTERVAL); #pidファイルが削除されていれば、自分自身をkillします if (not get_pid_file() ){ kill $PID; return; } } } sub interrupt { my ($sig) = @_; $SIG{$sig} = IGNORE ; return del_pid_file(); } sub get_pid_file { #pid fileの名称とpidの取得 return undef if not -e $PID_FILE; open my $fh, $PID_FILE or die "can t open $PID_FILE $!"; my ($line) = $fh ; close $fh or die "can t close $PID_FILE $!"; my ($pid) = $line =~ /(\d+)/o; return ($PID_FILE,$pid); } sub get_pid_file { #pid fileの名称とpidの取得 return undef if not -e $PID_FILE; open my $fh, $PID_FILE or die "can t open $PID_FILE $!"; my ($line) = $fh ; close $fh or die "can t close $PID_FILE $!"; my ($pid) = $line =~ /(\d+)/o; return ($PID_FILE,$pid); } sub set_pid_file { #pid fileにpidを書き込み my ($process_id) = @_; open my $fh, " $PID_FILE" or die "can t open $PID_FILE $!"; print $fh $process_id; close $fh or die "can t close $PID_FILE $!"; } sub del_pid_file { unlink $PID_FILE or die "can t unlink $PID_FILE $!"; } 1;
https://w.atwiki.jp/mityugioh/pages/129.html
第6回パルファン杯 大会要項 日時 2012/4/21 12 30 受付開始 13 00 大会開始 場所 パルファン3 室蘭市高砂町5丁目18-6 地図(Googleマップ) 大会形式 スイスドロー×4後、上位8名による決勝トーナメント ※2012年3月の制限を適用します 参加費 500円 ※ドリンク(コーヒー or ウーロン茶)代含む 参加枠 24名(参加希望者多数の場合、事前に抽選) 景品 参加賞としてRETURN OF THE DUELIST 1パックを参加者全員に贈呈します。 優勝 RETURN OF THE DUELIST 8パック 準優勝 RETURN OF THE DUELIST 5パック 3位 RETURN OF THE DUELIST 2パック 4位 RETURN OF THE DUELIST 1パック 大会規則 基本的にKONAMI公式のマスタールール2に準拠します。 禁止・制限カードリストについては最新の物を適用します。 大会開始前にデッキ内容とハンドルネームを所定の紙に書いて提出してもらいます。 大会参加者は上記の提出内容を当wikiに記載することを承諾するものとします。 参加受付 登録ページ 大会結果 コメント 大会内容について質問等ありましたらどうぞ。 名前 コメント
https://w.atwiki.jp/comedians/pages/1790.html
U-turnをお気に入りに追加 U-turnとは U-turnの70%は果物で出来ています。U-turnの18%はハッタリで出来ています。U-turnの5%は媚びで出来ています。U-turnの3%は陰謀で出来ています。U-turnの2%は下心で出来ています。U-turnの2%は愛で出来ています。 U-turnの報道 北海道U・Iターンフェア2022春(WEB合同企業説明会) - 経済部労働政策局産業人材課 - hokkaido.lg.jp アンジャッシュ渡部、「初対面で印象悪すぎ」と土田晃之が明かす(SmartFLASH) - Yahoo!ニュース - Yahoo!ニュース 右折レーンはいつでもUターンしていいの?【今さら聞けない交通ルール】 | clicccar.com - clicccar.com(クリッカー) 土田晃之「有吉弘行を3ヵ月でクビに...後にも先にも有吉を追い込んだのは”S”... - テレビ東京 緊急時でもないのに高速道路で堂々とUターン! この強引なおまわりさんは実在する!? 【交通取締情報】 - MotorFan[モーターファン] buntaro(R) Waraji Sandalsはただのサンダルではありません!! - PR TIMES 土田晃之がヒロミに暴露された「ボキャ天」時代のコンビ不仲ぶりが闇すぎる! (2020年1月10日) - エキサイトニュース ECのミカタ 企業HP 株式会社U-turn - ECのミカタ 土田晃之が起こした「Uターン事故」で「ボキャブラ」世代がザワザワ - アサジョ 欅坂メンバーが土田のためにU-turnのネタを再現! ファン「出来がすごい」と歓喜 - ZAKZAK U-turnのウィキペディア U-turn Amazon.co.jp ウィジェット U-turnの掲示板 名前(HN) カキコミ すべてのコメントを見る U-turnのリンク #blogsearch2 ページ先頭へ U-turn このページについて このページはU-turnのインターネット上の情報を時系列に網羅したリンク集のようなものです。ブックマークしておけば、日々更新されるU-turnに関連する最新情報にアクセスすることができます。 情報収集はプログラムで行っているため、名前が同じであるが異なるカテゴリーの情報が掲載される場合があります。ご了承ください。 リンク先の内容を保証するものではありません。ご自身の責任でクリックしてください。
https://w.atwiki.jp/liltan/pages/7.html
平面幾何計算 class Double2D{ double x; double y; static final double EPS = 1.0E-9; Double2D(double x,double y){ this.x = x; this.y = y; } @Override public boolean equals(Object o){ Double2D p = (Double2D)o; return x==p.x y==p.y; } public double squareDist(Double2D p){ return (x-p.x)*(x-p.x) + (y-p.y)*(y-p.y); } public double dist(Double2D p){ return Math.sqrt(this.squareDist(p)); } // thisとpを通る半径rの円の中心 public Double2D[] centerOfPassingCircle1(Double2D p,double r){ if(this.dist(p) r) return null; // 境界条件はテキトー double a = p.x - x; double b = p.y - y; double d = this.dist(p); double qx0 = x / 2 + p.x / 2 + Math.sqrt(r - d*d/4)*(-b)/d; double qy0 = y / 2 + p.y / 2 + Math.sqrt(r - d*d/4)*a/d; double qx1 = x / 2 + p.x / 2 - Math.sqrt(r - d*d/4)*(-b)/d; double qy1 = y / 2 + p.y / 2 - Math.sqrt(r - d*d/4)*a/d; Double2D[] ret = new Double2D[2]; ret[0] = new Double2D(qx0,qy0); ret[1] = new Double2D(qx1,qy1); return ret; } // 三点の作る三角形の面積 public static double squareOfTriangle(Double2D p1,Double2D p2,Double2D p3){ double x1 = p1.x-p2.x; double x2 = p3.x-p2.x; double y1 = p1.y-p2.y; double y2 = p3.y-p2.y; double s = (x1*y2-x2*y1)/2; return Math.abs(s); } // 多角形の内部にあるかどうか 自己ループはないものとする public static boolean inPolygon(ArrayList Double2D poly){ double acc = 0.0; int n = poly.size(); for(int i=0;i n-1;i++){ acc += arg(poly.get(i),poly.get(i+1)); } acc += arg(poly.get(n-1),poly.get(0)); if(Math.abs(acc) EPS) return false; else return true; } // -Pi theta Pi の範囲で偏角を返す 複素数でいう Arg(p2/p1) public static double arg(Double2D p1,Double2D p2){ double ax = p1.x; double ay = p1.y; double bx = p2.x; double by = p2.y; double theta = Math.atan2((ax*by-ay*bx)/(ax*ax+ay*ay),(ax*bx+ay*by)/(ax*ax+ay*ay)); return theta; } // 外接円の中心 Online Judge 検証なし 簡易検証あり public static Double2D centerOfCircumscribingCircle(Double2D p1, Double2D p2, Double2D p3){ double x1 = p1.x, y1 = p1.y, x2 = p2.x, y2 = p2.y, x3 = p3.x, y3 = p3.y; double det = (x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)); if(Math.abs(det) EPS) return null; double sx = -y1*(x2*x2+y2*y2-x3*x3-y3*y3) -y2*(x3*x3+y3*y3-x1*x1-y1*y1) -y3*(x1*x1+y1*y1-x2*x2-y2*y2); double sy = x1*(x2*x2+y2*y2-x3*x3-y3*y3) +x2*(x3*x3+y3*y3-x1*x1-y1*y1) +x3*(x1*x1+y1*y1-x2*x2-y2*y2); return new Double2D(0.5*sx/det, 0.5*sy/det); } } class Line{ double a; double b; double c; static final double EPS = 1.0E-9; Line(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } Line(Double2D p1,Double2D p2){ this.a = p1.y-p2.y; this.b = -p1.x+p2.x; this.c = -p1.x*(p1.y-p2.y)+p1.y*(p1.x-p2.x); } // 線分と線分の交点 ない場合は null // 2線分が重なりをもつときは考えていない public Double2D crossPoint(Line l){ // 平行 if(Math.abs(this.a*l.b-this.b*l.a) EPS){ return null; } else{ double x = (-l.b*this.c+this.b*l.c)/(this.a*l.b-this.b*l.a); double y = (l.a*this.c-this.a*l.c)/(this.a*l.b-this.b*l.a); return new Double2D(x,y); } } } class Circle{ double x; double y; double r; static final double EPS = 1.0E-9; Circle(double x, double y, double r) { this.x = x; this.y = y; this.r = r; } public double centerDist(Circle c){ return Math.sqrt((x-c.x)*(x-c.x)+(y-c.y)*(y-c.y)); } // 2円の交点 public Double2D[] crossPoint1(Circle c){ double d = centerDist(c); if(r+c.r d) return null; // 境界条件はテキトー double d1 = (d*d + r*r - c.r*c.r)/(2*d); double ex = x + (c.x-x)*d1/d; double ey = y + (c.y-y)*d1/d; double l = Math.sqrt(r*r-d1*d1); double lx = -(c.y-y)*l/d; double ly = (c.x-x)*l/d; Double2D[] ret = new Double2D[2]; ret[0] = new Double2D(ex+lx, ey+ly); ret[1] = new Double2D(ex-lx, ey-ly); return ret; } // 1点を通る接線 public Line[] tangentLine(Double2D p){ Line[] ret = new Line[2]; if(Math.abs((x-p.x)*(x-p.x)-r*r) EPS){ ret[0] = new Line(1, 0, -p.x); double m = ((y-p.y)*(y-p.y)-r*r)/(2*(x-p.x)*(y-p.y)); ret[1] = new Line(m, -1, -m*p.x+p.y); } else{ double m1 = ((x-p.x)*(y-p.y)+r*Math.sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y)-r*r))/((x-p.x)*(x-p.x)-r*r); double m2 = ((x-p.x)*(y-p.y)-r*Math.sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y)-r*r))/((x-p.x)*(x-p.x)-r*r); ret[0] = new Line(m1, -1, -m1*p.x+p.y); ret[1] = new Line(m2, -1, -m2*p.x+p.y); } return ret; } } class LineSegment{ Double2D p1; Double2D p2; static final double EPS = 1.0E-9; LineSegment(double x1, double y1, double x2, double y2){ p1 = new Double2D(x1, y1); p2 = new Double2D(x2, y2); } // 2線分が重なりをもつときは考えていない public Double2D crossPoint(LineSegment ls){ Double2D p3 = ls.p1; Double2D p4 = ls.p2; if(fcompare(Math.max(p1.x, p2.x), Math.min(p3.x, p4.x)) 0 || fcompare(Math.max(p3.x, p4.x), Math.min(p1.x, p2.x)) 0 || fcompare(Math.max(p1.y, p2.y), Math.min(p3.y, p4.y)) 0 || fcompare(Math.max(p3.y, p4.y), Math.min(p1.y, p2.y)) 0) return null; double dx00 = p2.x - p1.x; double dy00 = p2.y - p1.y; double dx01 = p3.x - p1.x; double dy01 = p3.y - p1.y; double dx02 = p4.x - p1.x; double dy02 = p4.y - p1.y; double dx10 = p4.x - p3.x; double dy10 = p4.y - p3.y; double dx11 = p1.x - p3.x; double dy11 = p1.y - p3.y; double dx12 = p2.x - p3.x; double dy12 = p2.y - p3.y; // 平行 if(Math.abs(dx00*dy10-dy00*dx10) EPS){ if(p1.x==p3.x p1.y==p3.y) return p1; if(p1.x==p4.x p1.y==p4.y) return p1; if(p2.x==p3.x p2.y==p3.y) return p2; if(p2.x==p4.x p2.y==p4.y) return p2; } if(fcompare((dx00*dy01-dx01*dy00)*(dx00*dy02-dx02*dy00), 0) =0 fcompare((dx10*dy11-dx11*dy10)*(dx10*dy12-dx12*dy10), 0) =0){ Line l1 = new Line(p1, p2); Line l2 = new Line(p3, p4); return l1.crossPoint(l2); } else return null; } private int fcompare(double a, double b){ if(Math.abs(a-b) EPS) return 0; if(a b) return 1; else return -1; } } 空間幾何計算 class Double3D{ double x; double y; double z; Double3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public double dist(Double3D p){ double dx = p.x-this.x; double dy = p.y-this.y; double dz = p.z-this.z; return Math.sqrt(dx*dx+dy*dy+dz*dz); } //determinant of matrix |a1 a2 a3| where a1,a2,a3 are column vectors public static double det(Double3D a1,Double3D a2,Double3D a3){ double d1 = a1.x*(a2.y*a3.z-a2.z*a3.y); double d2 = a1.y*(a2.x*a3.z-a2.z*a3.x); double d3 = a1.z*(a2.x*a3.y-a2.y*a3.x); return d1-d2+d3; } /* solution of linear equation * where coefficient matrix is (a1 a2 a3) and c is constant vector * when the solution is not unique, return null */ public static Double3D solveLinearEquation(Double3D a1,Double3D a2,Double3D a3,Double3D c){ double d = det(a1,a2,a3); if(Math.abs(d) 1E-10) return null; double o1 = det(c,a2,a3); double o2 = det(a1,c,a3); double o3 = det(a1,a2,c); return new Double3D(o1/d,o2/d,o3/d); } /* center of circumcircle of Triangle pqr * when p,q,r are on a line, return null */ public static Double3D centerOfCircumCircle(Double3D p,Double3D q,Double3D r){ double a11 = 2*(p.x-q.x); double a12 = 2*(p.y-q.y); double a13 = 2*(p.z-q.z); double c1 = p.x*p.x+p.y*p.y+p.z*p.z-q.x*q.x-q.y*q.y-q.z*q.z; double a21 = 2*(p.x-r.x); double a22 = 2*(p.y-r.y); double a23 = 2*(p.z-r.z); double c2 = p.x*p.x+p.y*p.y+p.z*p.z-r.x*r.x-r.y*r.y-r.z*r.z; double a31 = p.y*q.z+q.y*r.z+r.y*p.z-p.z*q.y-q.z*r.y-r.z*p.y; double a32 = p.z*q.x+q.z*r.x+r.z*p.x-p.x*q.z-q.x*r.z-r.x*p.z; double a33 = p.x*q.y+q.x*r.y+r.x*p.y-p.y*q.x-q.y*r.x-r.y*p.x; double c3 = det(p,q,r); Double3D a1 = new Double3D(a11,a21,a31); Double3D a2 = new Double3D(a12,a22,a32); Double3D a3 = new Double3D(a13,a23,a33); Double3D c = new Double3D(c1,c2,c3); return solveLinearEquation(a1,a2,a3,c); } /* center of circumsphere of tetrahedron pqrs * when p,q,r,s are on a plane, return null */ public static Double3D centerOfCircumSphere(Double3D p,Double3D q,Double3D r,Double3D s){ double a11 = 2*(p.x-q.x); double a12 = 2*(p.y-q.y); double a13 = 2*(p.z-q.z); double c1 = p.x*p.x+p.y*p.y+p.z*p.z-q.x*q.x-q.y*q.y-q.z*q.z; double a21 = 2*(p.x-r.x); double a22 = 2*(p.y-r.y); double a23 = 2*(p.z-r.z); double c2 = p.x*p.x+p.y*p.y+p.z*p.z-r.x*r.x-r.y*r.y-r.z*r.z; double a31 = 2*(p.x-s.x); double a32 = 2*(p.y-s.y); double a33 = 2*(p.z-s.z); double c3 = p.x*p.x+p.y*p.y+p.z*p.z-s.x*s.x-s.y*s.y-s.z*s.z; Double3D a1 = new Double3D(a11,a21,a31); Double3D a2 = new Double3D(a12,a22,a32); Double3D a3 = new Double3D(a13,a23,a33); Double3D c = new Double3D(c1,c2,c3); return solveLinearEquation(a1,a2,a3,c); } public static Double3D midpoint(Double3D p,Double3D q){ return new Double3D((p.x+q.x)/2,(p.y+q.y)/2,(p.z+q.z)/2); } } 高速Kruskal with 高速MFSet O(NlogN)のMFsetを用いたKruskalのアルゴリズム. class KruskalSolver{ int n; double[][] dist; double len; private PriorityQueue Edge q; KruskalSolver(int n,double dist[][]){ this.n = n; this.dist = dist; this.q = new PriorityQueue Edge (); this.len = 0.0; for(int i=0;i n;i++){ for(int j=i+1;j n;j++){ if(dist[i][j] Double.MAX_VALUE){ q.offer(new Edge(i, j, dist[i][j])); } } } //Kruskal s algorithm MFSet mfs = new MFSet(n); while(!q.isEmpty()){ Edge e = q.poll(); int i = e.p1; int j = e.p2; if(mfs.find(i)!=mfs.find(j)){ mfs.merge(mfs.find(i),mfs.find(j)); len += e.length; } } } } class Edge implements Comparable Edge { int p1; int p2; double length; Edge(int i,int j,double l){ p1 = i; p2 = j; length = l; } public int compareTo(Edge e){ if(length e.length) return 1; else if(length==e.length) return 0; else return -1; } } class MFSet{ int n; private int[] setsize; private int[] firstelem; private int[] set; private int[] next; MFSet(int n){ this.n = n; setsize = new int[n]; Arrays.fill(setsize, 1); firstelem = new int[n]; for(int i=0;i n;i++) firstelem[i] = i; set = new int[n]; for(int i=0;i n;i++) set[i] = i; next = new int[n]; for(int i=0;i n;i++) next[i] = -1; } int find(int x){ return set[x]; } void merge(int a, int b){ if(setsize[a] setsize[b]){ merge(b, a); return; } int i = firstelem[b]; while(next[i] =0){ set[i] = a; i = next[i]; } set[i] = a; next[i] = firstelem[a]; firstelem[a] = firstelem[b]; setsize[a] = setsize[a] + setsize[b]; setsize[b] = 0; firstelem[b] = -1; } } Kruskal O(N^2)のMFSetを用いたKruskalのアルゴリズム. class KruskalSolver{ int n; double[][] dist; double len; private PriorityQueue Edge q; int[] set; KruskalSolver(int n,double dist[][]){ this.n = n; this.dist = dist; this.len = 0.0; this.q = new PriorityQueue Edge (); this.set = new int[n]; for(int i=0;i n;i++) set[i] = i; for(int i=0;i n;i++){ for(int j=i+1;j n;j++){ if(dist[i][j] Double.MAX_VALUE){ q.offer(new Edge(i, j, dist[i][j])); } } } //Kruskal s algorithm while(!q.isEmpty()){ Edge e = q.poll(); int i = e.p1; int j = e.p2; int si = set[i]; int sj = set[j]; if(si!=sj){ len += e.length; for(int k=0;k n;k++){ if(set[k]==sj) set[k] = si; } } } } } class Edge implements Comparable Edge { int p1; int p2; double length; Edge(int i,int j,double l){ p1 = i; p2 = j; length = l; } public int compareTo(Edge e){ if(length e.length) return 1; else if(length==e.length) return 0; else return -1; } } Floyd 全点対間最短路. class FloydSolver{ int n; double[][] cost; int[][] path; FloydSolver(int n, double[][] dist) { this.n = n; cost = new double[n][n]; path = new int[n][n]; for(int i=0;i n;i++){ for(int j=0;j n;j++){ cost[i][j] = dist[i][j]; path[i][j] = -1; } } for(int k=0;k n;k++){ for(int i=0;i n;i++){ for(int j=0;j n;j++){ if(cost[i][k]==Double.MAX_VALUE || cost[k][j]==Double.MAX_VALUE) continue; if(cost[i][k]+cost[k][j] cost[i][j]){ cost[i][j] = cost[i][k] + cost[k][j]; path[i][j] = k; } } } } } public double pathLength(int v1, int v2){ return cost[v1][v2]; } public ArrayList Integer path(int v1, int v2){ if(cost[v1][v2]==Double.MAX_VALUE) return null; ArrayList Integer ret = new ArrayList Integer (); ret.add(v1); path(v1, v2, ret); ret.add(v2); return ret; } private void path(int v1, int v2, ArrayList Integer ret){ int k = path[v1][v2]; if(k==-1) return; else{ path(v1, k, ret); ret.add(k); path(k, v2, ret); } } } 最大流問題 class MaxFlowSolver { int size;//number of nodes int source;//nodeID of source int sink;//nodeID of sink int[][] network; int[] prev; MaxFlowSolver(int n, int s, int t, int[][] net) { size = n; source = s; sink = t; network = net; prev = new int[size]; } public int solve() { int flow = 0; while (searchPath()) { int flowinc = Integer.MAX_VALUE; // calculate how much flow increases int v = sink; while (prev[v] Integer.MAX_VALUE) { flowinc = Math.min(flowinc, network[prev[v]][v]); v = prev[v]; } //flow increases flow += flowinc; //update network array v = sink; while(prev[v] Integer.MAX_VALUE){ network[prev[v]][v] -= flowinc; network[v][prev[v]] += flowinc; v = prev[v]; } } return flow; } //search shortest path from source to sink by BFS private boolean searchPath() { Arrays.fill(prev, -1); Queue Integer q = new LinkedList Integer (); q.offer(source); prev[source] = Integer.MAX_VALUE; L while (!q.isEmpty()) { int u = q.poll(); for (int i = 0; i size; i++) { if (prev[i] 0 network[u][i] 0) { prev[i] = u; //discoverd path to sink if (i == sink) break L; q.offer(i); } } } return prev[sink] =0; } }